summaryrefslogtreecommitdiff
path: root/server-tools/instance-manager/guardian.cc
blob: 7a9ff3e8367d256f1cf84a1d2816d0f4e558ae83 (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
/* Copyright (C) 2004 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any 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
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */


#if defined(__GNUC__) && defined(USE_PRAGMA_IMPLEMENTATION)
#pragma implementation
#endif

#include "guardian.h"

#include <string.h>
#include <sys/types.h>
#include <signal.h>

#include "instance.h"
#include "instance_map.h"
#include "log.h"
#include "mysql_manager_error.h"


pthread_handler_t guardian(void *arg)
{
  Guardian_thread *guardian_thread= (Guardian_thread *) arg;
  guardian_thread->run();
  return 0;
}


const char *
Guardian_thread::get_instance_state_name(enum_instance_state state)
{
  switch (state) {
  case NOT_STARTED:
    return "offline";

  case STARTING:
    return "starting";

  case STARTED:
    return "online";

  case JUST_CRASHED:
    return "failed";

  case CRASHED:
    return "crashed";

  case CRASHED_AND_ABANDONED:
    return "abandoned";

  case STOPPING:
    return "stopping";
  }

  return NULL; /* just to ignore compiler warning. */
}


Guardian_thread::Guardian_thread(Thread_registry &thread_registry_arg,
                                 Instance_map *instance_map_arg,
                                 uint monitoring_interval_arg) :
  Guardian_thread_args(thread_registry_arg, instance_map_arg,
                       monitoring_interval_arg),
  thread_info(pthread_self()), guarded_instances(0)
{
  pthread_mutex_init(&LOCK_guardian, 0);
  pthread_cond_init(&COND_guardian, 0);
  shutdown_requested= FALSE;
  stopped= FALSE;
  init_alloc_root(&alloc, MEM_ROOT_BLOCK_SIZE, 0);
}


Guardian_thread::~Guardian_thread()
{
  /* delay guardian destruction to the moment when no one needs it */
  pthread_mutex_lock(&LOCK_guardian);
  free_root(&alloc, MYF(0));
  pthread_mutex_unlock(&LOCK_guardian);
  pthread_mutex_destroy(&LOCK_guardian);
  pthread_cond_destroy(&COND_guardian);
}


void Guardian_thread::request_shutdown(bool stop_instances_arg)
{
  pthread_mutex_lock(&LOCK_guardian);
  /* stop instances or just clean up Guardian repository */
  stop_instances(stop_instances_arg);
  shutdown_requested= TRUE;
  pthread_mutex_unlock(&LOCK_guardian);
}


void Guardian_thread::process_instance(Instance *instance,
                                       GUARD_NODE *current_node,
                                       LIST **guarded_instances,
                                       LIST *node)
{
  uint waitchild= (uint) Instance::DEFAULT_SHUTDOWN_DELAY;
  /* The amount of times, Guardian attempts to restart an instance */
  int restart_retry= 100;
  time_t current_time= time(NULL);

  if (current_node->state == STOPPING)
  {
    /* this brach is executed during shutdown */
    if (instance->options.shutdown_delay)
    {
      /*
        NOTE: it is important to check shutdown_delay here, but use
        shutdown_delay_val. The idea is that if the option is unset,
        shutdown_delay will be NULL, but shutdown_delay_val will not be reset.
      */
      waitchild= instance->options.shutdown_delay_val;
    }

    /* this returns TRUE if and only if an instance was stopped for sure */
    if (instance->is_crashed())
      *guarded_instances= list_delete(*guarded_instances, node);
    else if ( (uint) (current_time - current_node->last_checked) > waitchild)
    {
      instance->kill_instance(SIGKILL);
      /*
        Later we do node= node->next. This is ok, as we are only removing
        the node from the list. The pointer to the next one is still valid.
      */
      *guarded_instances= list_delete(*guarded_instances, node);
    }

    return;
  }

  if (instance->is_running())
  {
    /* clear status fields */
    current_node->restart_counter= 0;
    current_node->crash_moment= 0;
    current_node->state= STARTED;
  }
  else
  {
    switch (current_node->state) {
    case NOT_STARTED:
      instance->start();
      current_node->last_checked= current_time;
      log_info("guardian: starting instance %s",
               instance->options.instance_name);
      current_node->state= STARTING;
      break;
    case STARTED:     /* fallthrough */
    case STARTING:    /* let the instance start or crash */
      if (instance->is_crashed())
      {
        current_node->crash_moment= current_time;
        current_node->last_checked= current_time;
        current_node->state= JUST_CRASHED;
        /* fallthrough -- restart an instance immediately */
      }
      else
        break;
    case JUST_CRASHED:
      if (current_time - current_node->crash_moment <= 2)
      {
        instance->start();
        log_info("guardian: starting instance %s",
                 instance->options.instance_name);
      }
      else
        current_node->state= CRASHED;
      break;
    case CRASHED:    /* just regular restarts */
      if (current_time - current_node->last_checked >
          monitoring_interval)
      {
        if ((current_node->restart_counter < restart_retry))
        {
          instance->start();
          current_node->last_checked= current_time;
          current_node->restart_counter++;
          log_info("guardian: restarting instance %s",
                   instance->options.instance_name);
        }
        else
        {
          log_info("guardian: cannot start instance %s. Abandoning attempts "
                   "to (re)start it", instance->options.instance_name);
          current_node->state= CRASHED_AND_ABANDONED;
        }
      }
      break;
    case CRASHED_AND_ABANDONED:
      break; /* do nothing */
    default:
      DBUG_ASSERT(0);
    }
  }
}


/*
  Run guardian thread

  SYNOPSYS
    run()

  DESCRIPTION

    Check for all guarded instances and restart them if needed. If everything
    is fine go and sleep for some time.
*/

void Guardian_thread::run()
{
  Instance *instance;
  LIST *node;
  struct timespec timeout;

  thread_registry.register_thread(&thread_info);

  my_thread_init();
  pthread_mutex_lock(&LOCK_guardian);

  /* loop, until all instances were shut down at the end */
  while (!(shutdown_requested && (guarded_instances == NULL)))
  {
    node= guarded_instances;

    while (node != NULL)
    {
      GUARD_NODE *current_node= (GUARD_NODE *) node->data;
      instance= ((GUARD_NODE *) node->data)->instance;
      process_instance(instance, current_node, &guarded_instances, node);

      node= node->next;
    }
    timeout.tv_sec= time(NULL) + monitoring_interval;
    timeout.tv_nsec= 0;

    /* check the loop predicate before sleeping */
    if (!(shutdown_requested && (!(guarded_instances))))
      thread_registry.cond_timedwait(&thread_info, &COND_guardian,
                                     &LOCK_guardian, &timeout);
  }

  stopped= TRUE;
  pthread_mutex_unlock(&LOCK_guardian);
  /* now, when the Guardian is stopped we can stop the IM */
  thread_registry.unregister_thread(&thread_info);
  thread_registry.request_shutdown();
  my_thread_end();
}


int Guardian_thread::is_stopped()
{
  int var;
  pthread_mutex_lock(&LOCK_guardian);
  var= stopped;
  pthread_mutex_unlock(&LOCK_guardian);
  return var;
}


/*
  Initialize the list of guarded instances: loop through the Instance_map and
  add all of the instances, which don't have 'nonguarded' option specified.

  SYNOPSYS
    Guardian_thread::init()

  NOTE: The operation should be invoked with the following locks acquired:
    - Guardian_thread;
    - Instance_map;

  RETURN
    0 - ok
    1 - error occured
*/

int Guardian_thread::init()
{
  Instance *instance;
  Instance_map::Iterator iterator(instance_map);

  /* clear the list of guarded instances */
  free_root(&alloc, MYF(0));
  init_alloc_root(&alloc, MEM_ROOT_BLOCK_SIZE, 0);
  guarded_instances= NULL;

  while ((instance= iterator.next()))
  {
    if (instance->options.nonguarded)
      continue;

    if (guard(instance, TRUE))                /* do not lock guardian */
      return 1;
  }

  return 0;
}


/*
  Add instance to the Guardian list

  SYNOPSYS
    guard()
    instance           the instance to be guarded
    nolock             whether we prefer do not lock Guardian here,
                       but use external locking instead

  DESCRIPTION

    The instance is added to the guarded instances list. Usually guard() is
    called after we start an instance.

  RETURN
    0 - ok
    1 - error occured
*/

int Guardian_thread::guard(Instance *instance, bool nolock)
{
  LIST *node;
  GUARD_NODE *content;

  node= (LIST *) alloc_root(&alloc, sizeof(LIST));
  content= (GUARD_NODE *) alloc_root(&alloc, sizeof(GUARD_NODE));

  if ((!(node)) || (!(content)))
    return 1;
  /* we store the pointers to instances from the instance_map's MEM_ROOT */
  content->instance= instance;
  content->restart_counter= 0;
  content->crash_moment= 0;
  content->state= NOT_STARTED;
  node->data= (void*) content;

  if (nolock)
    guarded_instances= list_add(guarded_instances, node);
  else
  {
    pthread_mutex_lock(&LOCK_guardian);
    guarded_instances= list_add(guarded_instances, node);
    pthread_mutex_unlock(&LOCK_guardian);
  }

  return 0;
}


/*
  TODO: perhaps it would make sense to create a pool of the LIST nodeents
  and give them upon request. Now we are loosing a bit of memory when
  guarded instance was stopped and then restarted (since we cannot free just
  a piece of the MEM_ROOT).
*/

int Guardian_thread::stop_guard(Instance *instance)
{
  LIST *node;

  pthread_mutex_lock(&LOCK_guardian);

  node= find_instance_node(instance);

  if (node != NULL)
    guarded_instances= list_delete(guarded_instances, node);

  pthread_mutex_unlock(&LOCK_guardian);

  /* if there is nothing to delete it is also fine */
  return 0;
}

/*
  An internal method which is called at shutdown to unregister instances and
  attempt to stop them if requested.

  SYNOPSYS
    stop_instances()
    stop_instances_arg          whether we should stop instances at shutdown

  DESCRIPTION
    Loops through the guarded_instances list and prepares them for shutdown.
    If stop_instances was requested, we need to issue a stop command and change
    the state accordingly. Otherwise we simply delete an entry.

  NOTE
    Guardian object should be locked by the calling function.

  RETURN
    0 - ok
    1 - error occured
*/

int Guardian_thread::stop_instances(bool stop_instances_arg)
{
  LIST *node;
  node= guarded_instances;
  while (node != NULL)
  {
    if (!stop_instances_arg)
    {
      /* just forget about an instance */
      guarded_instances= list_delete(guarded_instances, node);
      /*
        This should still work fine, as we have only removed the
        node from the list. The pointer to the next one is still valid
      */
      node= node->next;
    }
    else
    {
      GUARD_NODE *current_node= (GUARD_NODE *) node->data;
      /*
        If instance is running or was running (and now probably hanging),
        request stop.
      */
      if (current_node->instance->is_running() ||
          (current_node->state == STARTED))
      {
        current_node->state= STOPPING;
        current_node->last_checked= time(NULL);
      }
      else
        /* otherwise remove it from the list */
        guarded_instances= list_delete(guarded_instances, node);
      /* But try to kill it anyway. Just in case */
      current_node->instance->kill_instance(SIGTERM);
      node= node->next;
    }
  }
  return 0;
}


void Guardian_thread::lock()
{
  pthread_mutex_lock(&LOCK_guardian);
}


void Guardian_thread::unlock()
{
  pthread_mutex_unlock(&LOCK_guardian);
}


LIST *Guardian_thread::find_instance_node(Instance *instance)
{
  LIST *node= guarded_instances;

  while (node != NULL)
  {
    /*
      We compare only pointers, as we always use pointers from the
      instance_map's MEM_ROOT.
    */
    if (((GUARD_NODE *) node->data)->instance == instance)
      return node;

    node= node->next;
  }

  return NULL;
}


bool Guardian_thread::is_active(Instance *instance)
{
  bool guarded;

  lock();

  guarded= find_instance_node(instance) != NULL;

  /* is_running() can take a long time, so let's unlock mutex first. */
  unlock();

  if (guarded)
    return true;

  return instance->is_running();
}