summaryrefslogtreecommitdiff
path: root/open-vm-tools/services/vmtoolsd/threadPool.c
blob: b7fd7ae66c214a3390608a20a8b08c9a58389db6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
/*********************************************************
 * Copyright (C) 2010-2015 VMware, Inc. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation version 2.1 and no later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the Lesser GNU General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA.
 *
 *********************************************************/

/**
 * @file threadPool.c
 *
 * Implementation of the shared thread pool defined in threadPool.h.
 */

#include <limits.h>
#include <string.h>
#include "vmware.h"
#include "toolsCoreInt.h"
#include "serviceObj.h"
#include "vmware/tools/threadPool.h"

#define DEFAULT_MAX_IDLE_TIME       5000
#define DEFAULT_MAX_THREADS         5
#define DEFAULT_MAX_UNUSED_THREADS  0

typedef struct ThreadPoolState {
   ToolsCorePool  funcs;
   gboolean       active;
   ToolsAppCtx   *ctx;
   GThreadPool   *pool;
   GQueue        *workQueue;
   GPtrArray     *threads;
   GMutex        *lock;
   guint          nextWorkId;
} ThreadPoolState;


typedef struct WorkerTask {
   guint             id;
   guint             srcId;
   ToolsCorePoolCb   cb;
   gpointer          data;
   GDestroyNotify    dtor;
} WorkerTask;


typedef struct StandaloneTask {
   gboolean          active;
   ToolsCorePoolCb   cb;
   ToolsCorePoolCb   interrupt;
   gpointer          data;
   GThread          *thread;
   GDestroyNotify    dtor;
} StandaloneTask;


static ThreadPoolState gState;


/*
 *******************************************************************************
 * ToolsCorePoolCompareTask --                                            */ /**
 *
 * Compares two WorkerTask instances.
 *
 * @param[in] p1  Pointer to WorkerTask.
 * @param[in] p2  Pointer to WorkerTask.
 *
 * @return > 0, 0, < 0  if p1's ID is less than, equal, or greater than p2's.
 *
 *******************************************************************************
 */

static gint
ToolsCorePoolCompareTask(gconstpointer p1,
                         gconstpointer p2)
{
   const WorkerTask *t1 = p1;
   const WorkerTask *t2 = p2;

   if (t1 != NULL && t2 != NULL) {
      return (t2->id - t1->id);
   }

   if (t1 == NULL && t2 == NULL) {
      return 0;
   }

   return (t1 != NULL) ? -1 : 1;
}


/*
 *******************************************************************************
 * ToolsCorePoolDestroyThread --                                          */ /**
 *
 * Releases resources associated with a StandaloneTask, joining the thread
 * that's executing it.
 *
 * @param[in] data   A StandaloneTask.
 *
 *******************************************************************************
 */

static void
ToolsCorePoolDestroyThread(gpointer data)
{
   StandaloneTask *task = data;
   g_thread_join(task->thread);
   if (task->dtor != NULL) {
      task->dtor(task->data);
   }
   g_free(task);
}


/*
 *******************************************************************************
 * ToolsCorePoolDestroyTask --                                            */ /**
 *
 * Frees memory associated with a WorkerTask, calling its destructor if one is
 * registered.
 *
 * @param[in] data   A WorkerTask.
 *
 *******************************************************************************
 */

static void
ToolsCorePoolDestroyTask(gpointer data)
{
   WorkerTask *work = data;
   if (work->dtor != NULL) {
      work->dtor(work->data);
   }
   g_free(work);
}


/*
 *******************************************************************************
 * ToolsCorePoolDoWork --                                                 */ /**
 *
 * Execute a work item.
 *
 * @param[in] data   A WorkerTask.
 *
 * @return FALSE
 *
 *******************************************************************************
 */

static gboolean
ToolsCorePoolDoWork(gpointer data)
{
   WorkerTask *work = data;

   /*
    * In single threaded mode, remove the task being executed from the queue.
    * In multi-threaded mode, the thread pool callback already did this.
    */
   if (gState.pool == NULL) {
      g_mutex_lock(gState.lock);
      g_queue_remove(gState.workQueue, work);
      g_mutex_unlock(gState.lock);
   }

   work->cb(gState.ctx, work->data);
   return FALSE;
}


/*
 *******************************************************************************
 * ToolsCorePoolNoOp --                                                   */ /**
 *
 * Idle callback for destroying a standalone thread. Does nothing, since the
 * actual destruction is done by ToolsCorePoolDestroyThread.
 *
 * @param[in] data   Unused.
 *
 * @return FALSE
 *
 *******************************************************************************
 */

static gboolean
ToolsCorePoolNoOp(gpointer data)
{
   return FALSE;
}


/*
 *******************************************************************************
 * ToolsCorePoolRunThread --                                              */ /**
 *
 * Standalone thread runner. Executes the task associated with the thread, and
 * schedule a task to clean up the thread state when done.
 *
 * @param[in] data   A StandaloneTask.
 *
 * @return NULL
 *
 *******************************************************************************
 */

static gpointer
ToolsCorePoolRunThread(gpointer data)
{
   StandaloneTask *task = data;

   task->cb(gState.ctx, task->data);
   task->active = FALSE;

   g_mutex_lock(gState.lock);
   /* If not active, the shutdown function will clean things up. */
   if (gState.active) {
      g_ptr_array_remove(gState.threads, task);
      g_idle_add_full(G_PRIORITY_DEFAULT_IDLE,
                      ToolsCorePoolNoOp,
                      task,
                      ToolsCorePoolDestroyThread);
   }
   g_mutex_unlock(gState.lock);

   return NULL;
}


/*
 *******************************************************************************
 * ToolsCorePoolRunWorker --                                              */ /**
 *
 * Thread pool callback function. Dequeues the next work item from the work
 * queue and execute it.
 *
 * @param[in] state        Description of state.
 * @param[in] clientData   Description of clientData.
 *
 *******************************************************************************
 */

static void
ToolsCorePoolRunWorker(gpointer state,
                       gpointer clientData)
{
   WorkerTask *work;

   g_mutex_lock(gState.lock);
   work = g_queue_pop_tail(gState.workQueue);
   g_mutex_unlock(gState.lock);

   ASSERT(work != NULL);

   ToolsCorePoolDoWork(work);
   ToolsCorePoolDestroyTask(work);
}


/*
 *******************************************************************************
 * ToolsCorePoolSubmit --                                                 */ /**
 *
 * Submits a new task for execution in one of the shared worker threads.
 *
 * @see ToolsCorePool_SubmitTask()
 *
 * @param[in] ctx    Application context.
 * @param[in] cb     Function to execute the task.
 * @param[in] data   Opaque data for the task.
 * @param[in] dtor   Destructor for the task data.
 *
 * @return New task's ID, or 0 on error.
 *
 *******************************************************************************
 */

static guint
ToolsCorePoolSubmit(ToolsAppCtx *ctx,
                    ToolsCorePoolCb cb,
                    gpointer data,
                    GDestroyNotify dtor)
{
   guint id = 0;
   WorkerTask *task = g_malloc0(sizeof *task);

   task->srcId = 0;
   task->cb = cb;
   task->data = data;
   task->dtor = dtor;

   g_mutex_lock(gState.lock);

   if (!gState.active) {
      g_free(task);
      goto exit;
   }

   /*
    * XXX: a reeeeeeeeeally long running task could cause clashes (e.g., reusing
    * the same task ID after the counter wraps). That shouldn't really happen in
    * practice (and is an abuse of the thread pool, and could cause issues if
    * someone sets the pool size to 0 or 1), but it might be good to have more
    * fail-safe code here.
    */
   if (gState.nextWorkId + 1 == UINT_MAX) {
      task->id = UINT_MAX;
      gState.nextWorkId = 0;
   } else {
      task->id = ++gState.nextWorkId;
   }

   id = task->id;

   /*
    * We always add the task to the queue, even in single threaded mode, so
    * that it can be canceled. In single threaded mode, it's unlikely someone
    * will be able to cancel it before it runs, but they can try.
    */
   g_queue_push_head(gState.workQueue, task);

   if (gState.pool != NULL) {
      GError *err = NULL;

      /* The client data pointer is bogus, just to avoid passing NULL. */
      g_thread_pool_push(gState.pool, &gState, &err);
      if (err == NULL) {
         goto exit;
      } else {
         g_warning("error sending work request, executing in service thread: %s",
                   err->message);
         g_clear_error(&err);
      }
   }

   /* Run the task in the service's thread. */
   task->srcId = g_idle_add_full(G_PRIORITY_DEFAULT_IDLE,
                                 ToolsCorePoolDoWork,
                                 task,
                                 ToolsCorePoolDestroyTask);

exit:
   g_mutex_unlock(gState.lock);
   return id;
}


/*
 *******************************************************************************
 * ToolsCorePoolCancel --                                                 */ /**
 *
 * Cancels a queue task.
 *
 * @see ToolsCorePool_CancelTask()
 *
 * @param[in] id  Task ID.
 *
 *******************************************************************************
 */

static void
ToolsCorePoolCancel(guint id)
{
   GList *taskLnk;
   WorkerTask *task = NULL;
   WorkerTask search = { id, };

   g_return_if_fail(id != 0);

   g_mutex_lock(gState.lock);
   if (!gState.active) {
      goto exit;
   }

   taskLnk = g_queue_find_custom(gState.workQueue, &search, ToolsCorePoolCompareTask);
   if (taskLnk != NULL) {
      task = taskLnk->data;
      g_queue_delete_link(gState.workQueue, taskLnk);
   }

exit:
   g_mutex_unlock(gState.lock);

   if (task != NULL) {
      if (task->srcId > 0) {
         g_source_remove(task->srcId);
      } else {
         ToolsCorePoolDestroyTask(task);
      }
   }
}


/*
 *******************************************************************************
 * ToolsCorePoolStart --                                                  */ /**
 *
 * Start a new task in a dedicated thread.
 *
 * @see ToolsCorePool_StartThread()
 *
 * @param[in] ctx       Application context.
 * @param[in] cb        Callback that executes the task.
 * @param[in] interrupt Callback that interrupts the task.
 * @param[in] data      Opaque data.
 * @param[in] dtor      Destructor for the task data.
 *
 * @return TRUE iff thread was successfully started.
 *
 *******************************************************************************
 */

static gboolean
ToolsCorePoolStart(ToolsAppCtx *ctx,
                   ToolsCorePoolCb cb,
                   ToolsCorePoolCb interrupt,
                   gpointer data,
                   GDestroyNotify dtor)
{
   GError *err = NULL;
   StandaloneTask *task = NULL;

   g_mutex_lock(gState.lock);
   if (!gState.active) {
      goto exit;
   }

   task = g_malloc0(sizeof *task);
   task->active = TRUE;
   task->cb = cb;
   task->interrupt = interrupt;
   task->data = data;
   task->dtor = dtor;
   task->thread = g_thread_create(ToolsCorePoolRunThread, task, TRUE, &err);

   if (err == NULL) {
      g_ptr_array_add(gState.threads, task);
   } else {
      g_warning("failed to start thread: %s.", err->message);
      g_clear_error(&err);
      g_free(task);
      task = NULL;
   }

exit:
   g_mutex_unlock(gState.lock);
   return task != NULL;
}


/*
 *******************************************************************************
 * ToolsCorePool_Init --                                                  */ /**
 *
 * Initializes the shared thread pool. Reads configuration data from the
 * container-specific section of the config dictionary, so different containers
 * can have different configuration. Exports the thread pool functions through
 * the service's object.
 *
 * @param[in] ctx Application context.
 *
 *******************************************************************************
 */

void
ToolsCorePool_Init(ToolsAppCtx *ctx)
{
   gint maxThreads;
   GError *err = NULL;

   ToolsServiceProperty prop = { TOOLS_CORE_PROP_TPOOL };

   gState.funcs.submit = ToolsCorePoolSubmit;
   gState.funcs.cancel = ToolsCorePoolCancel;
   gState.funcs.start = ToolsCorePoolStart;
   gState.ctx = ctx;

   maxThreads = g_key_file_get_integer(ctx->config, ctx->name,
                                       "pool.maxThreads", &err);
   if (err != NULL) {
      maxThreads = DEFAULT_MAX_THREADS;
      g_clear_error(&err);
   }

   if (maxThreads > 0) {
      gState.pool = g_thread_pool_new(ToolsCorePoolRunWorker,
                                      NULL, maxThreads, FALSE, &err);
      if (err == NULL) {
#if GLIB_CHECK_VERSION(2, 10, 0)
         gint maxIdleTime;
         gint maxUnused;

         maxIdleTime = g_key_file_get_integer(ctx->config, ctx->name,
                                              "pool.maxIdleTime", &err);
         if (err != NULL || maxIdleTime <= 0) {
            maxIdleTime = DEFAULT_MAX_IDLE_TIME;
            g_clear_error(&err);
         }

         maxUnused = g_key_file_get_integer(ctx->config, ctx->name,
                                            "pool.maxUnusedThreads", &err);
         if (err != NULL || maxUnused < 0) {
            maxUnused = DEFAULT_MAX_UNUSED_THREADS;
            g_clear_error(&err);
         }

         g_thread_pool_set_max_idle_time(maxIdleTime);
         g_thread_pool_set_max_unused_threads(maxUnused);
#endif
      } else {
         g_warning("error initializing thread pool, running single threaded: %s",
                   err->message);
         g_clear_error(&err);
      }
   }

   gState.active = TRUE;
   gState.lock = g_mutex_new();
   gState.threads = g_ptr_array_new();
   gState.workQueue = g_queue_new();

   ToolsCoreService_RegisterProperty(ctx->serviceObj, &prop);
   g_object_set(ctx->serviceObj, TOOLS_CORE_PROP_TPOOL, &gState.funcs, NULL);
}


/*
 *******************************************************************************
 * ToolsCorePool_Shutdown --                                              */ /**
 *
 * Shuts down the shared thread pool. This function will interrupt any running
 * threads (by calling their registered interrupt function), and wait for all
 * running tasks to finish before cleaning the remaining tasks and shared state.
 *
 * @param[in] ctx Application context.
 *
 *******************************************************************************
 */

void
ToolsCorePool_Shutdown(ToolsAppCtx *ctx)
{
   guint i;

   g_mutex_lock(gState.lock);
   gState.active = FALSE;
   g_mutex_unlock(gState.lock);

   /* Notify all spawned threads to stop. */
   for (i = 0; i < gState.threads->len; i++) {
      StandaloneTask *task = g_ptr_array_index(gState.threads, i);
      if (task->active && task->interrupt) {
         task->interrupt(gState.ctx, task->data);
      }
   }

   /* Stop the thread pool. */
   if (gState.pool != NULL) {
      g_thread_pool_free(gState.pool, TRUE, TRUE);
   }

   /* Join all spawned threads. */
   for (i = 0; i < gState.threads->len; i++) {
      StandaloneTask *task = g_ptr_array_index(gState.threads, i);
      ToolsCorePoolDestroyThread(task);
   }

   /* Destroy all pending tasks. */
   while (1) {
      WorkerTask *task = g_queue_pop_tail(gState.workQueue);
      if (task != NULL) {
         ToolsCorePoolDestroyTask(task);
      } else {
         break;
      }
   }

   /* Cleanup. */
   g_ptr_array_free(gState.threads, TRUE);
   g_queue_free(gState.workQueue);
   g_mutex_free(gState.lock);
   memset(&gState, 0, sizeof gState);
   g_object_set(ctx->serviceObj, TOOLS_CORE_PROP_TPOOL, NULL, NULL);
}