Merge branch '9303-kill-nodemanager-on-dead-actor' refs #9303
[arvados.git] / services / nodemanager / arvnodeman / baseactor.py
1 from __future__ import absolute_import, print_function
2
3 import errno
4 import logging
5 import os
6 import signal
7 import time
8 import threading
9 import traceback
10
11 import pykka
12
13 class _TellCallableProxy(object):
14     """Internal helper class for proxying callables."""
15
16     def __init__(self, ref, attr_path):
17         self.actor_ref = ref
18         self._attr_path = attr_path
19
20     def __call__(self, *args, **kwargs):
21         message = {
22             'command': 'pykka_call',
23             'attr_path': self._attr_path,
24             'args': args,
25             'kwargs': kwargs,
26         }
27         self.actor_ref.tell(message)
28
29
30 class TellActorProxy(pykka.ActorProxy):
31     """ActorProxy in which all calls are implemented as using tell().
32
33     The standard pykka.ActorProxy always uses ask() and returns a Future.  If
34     the target method raises an exception, it is placed in the Future object
35     and re-raised when get() is called on the Future.  Unfortunately, most
36     messaging in Node Manager is asynchronous and the caller does not store the
37     Future object returned by the call to ActorProxy.  As a result, exceptions
38     resulting from these calls end up in limbo, neither reported in the logs
39     nor handled by on_failure().
40
41     The TellActorProxy uses tell() instead of ask() and does not return a
42     Future object.  As a result, if the target method raises an exception, it
43     will be logged and on_failure() will be called as intended.
44
45     """
46
47     def __repr__(self):
48         return '<ActorProxy for %s, attr_path=%s>' % (
49             self.actor_ref, self._attr_path)
50
51     def __getattr__(self, name):
52         """Get a callable from the actor."""
53         attr_path = self._attr_path + (name,)
54         if attr_path not in self._known_attrs:
55             self._known_attrs = self._get_attributes()
56         attr_info = self._known_attrs.get(attr_path)
57         if attr_info is None:
58             raise AttributeError('%s has no attribute "%s"' % (self, name))
59         if attr_info['callable']:
60             if attr_path not in self._callable_proxies:
61                 self._callable_proxies[attr_path] = _TellCallableProxy(
62                     self.actor_ref, attr_path)
63             return self._callable_proxies[attr_path]
64         else:
65             raise AttributeError('attribute "%s" is not a callable on %s' % (name, self))
66
67 class TellableActorRef(pykka.ActorRef):
68     """ActorRef adding the tell_proxy() method to get TellActorProxy."""
69
70     def tell_proxy(self):
71         return TellActorProxy(self)
72
73 class BaseNodeManagerActor(pykka.ThreadingActor):
74     """Base class for actors in node manager, redefining actor_ref as a
75     TellableActorRef and providing a default on_failure handler.
76     """
77
78     def __init__(self, *args, **kwargs):
79          super(pykka.ThreadingActor, self).__init__(*args, **kwargs)
80          self.actor_ref = TellableActorRef(self)
81
82     def on_failure(self, exception_type, exception_value, tb):
83         lg = getattr(self, "_logger", logging)
84         if (exception_type in (threading.ThreadError, MemoryError) or
85             exception_type is OSError and exception_value.errno == errno.ENOMEM):
86             lg.critical("Unhandled exception is a fatal error, killing Node Manager")
87             os.kill(os.getpid(), signal.SIGKILL)
88
89     def ping(self):
90         return True
91
92
93 class WatchdogActor(pykka.ThreadingActor):
94     def __init__(self, timeout, *args, **kwargs):
95          super(pykka.ThreadingActor, self).__init__(*args, **kwargs)
96          self.timeout = timeout
97          self.actors = [a.proxy() for a in args]
98          self.actor_ref = TellableActorRef(self)
99          self._later = self.actor_ref.tell_proxy()
100
101     def kill_self(self, act):
102         lg = getattr(self, "_logger", logging)
103         lg.critical("Actor %s watchdog ping time out, killing Node Manager", act)
104         os.kill(os.getpid(), signal.SIGKILL)
105
106     def on_start(self):
107         self._later.run()
108
109     def run(self):
110         a = None
111         try:
112             for a in self.actors:
113                 a.ping().get(self.timeout)
114             time.sleep(20)
115             self._later.run()
116         except:
117             self.kill_self(a)