Merge branch '8087-arv-cli-request-body-from-file' of https://github.com/wtsi-hgi...
[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 threading
7 import traceback
8
9 import pykka
10
11 class _TellCallableProxy(object):
12     """Internal helper class for proxying callables."""
13
14     def __init__(self, ref, attr_path):
15         self.actor_ref = ref
16         self._attr_path = attr_path
17
18     def __call__(self, *args, **kwargs):
19         message = {
20             'command': 'pykka_call',
21             'attr_path': self._attr_path,
22             'args': args,
23             'kwargs': kwargs,
24         }
25         self.actor_ref.tell(message)
26
27
28 class TellActorProxy(pykka.ActorProxy):
29     """ActorProxy in which all calls are implemented as using tell().
30
31     The standard pykka.ActorProxy always uses ask() and returns a Future.  If
32     the target method raises an exception, it is placed in the Future object
33     and re-raised when get() is called on the Future.  Unfortunately, most
34     messaging in Node Manager is asynchronous and the caller does not store the
35     Future object returned by the call to ActorProxy.  As a result, exceptions
36     resulting from these calls end up in limbo, neither reported in the logs
37     nor handled by on_failure().
38
39     The TellActorProxy uses tell() instead of ask() and does not return a
40     Future object.  As a result, if the target method raises an exception, it
41     will be logged and on_failure() will be called as intended.
42
43     """
44
45     def __repr__(self):
46         return '<ActorProxy for %s, attr_path=%s>' % (
47             self.actor_ref, self._attr_path)
48
49     def __getattr__(self, name):
50         """Get a callable from the actor."""
51         attr_path = self._attr_path + (name,)
52         if attr_path not in self._known_attrs:
53             self._known_attrs = self._get_attributes()
54         attr_info = self._known_attrs.get(attr_path)
55         if attr_info is None:
56             raise AttributeError('%s has no attribute "%s"' % (self, name))
57         if attr_info['callable']:
58             if attr_path not in self._callable_proxies:
59                 self._callable_proxies[attr_path] = _TellCallableProxy(
60                     self.actor_ref, attr_path)
61             return self._callable_proxies[attr_path]
62         else:
63             raise AttributeError('attribute "%s" is not a callable on %s' % (name, self))
64
65 class TellableActorRef(pykka.ActorRef):
66     """ActorRef adding the tell_proxy() method to get TellActorProxy."""
67
68     def tell_proxy(self):
69         return TellActorProxy(self)
70
71 class BaseNodeManagerActor(pykka.ThreadingActor):
72     """Base class for actors in node manager, redefining actor_ref as a
73     TellableActorRef and providing a default on_failure handler.
74     """
75
76     def __init__(self, *args, **kwargs):
77          super(pykka.ThreadingActor, self).__init__(*args, **kwargs)
78          self.actor_ref = TellableActorRef(self)
79
80     def on_failure(self, exception_type, exception_value, tb):
81         lg = getattr(self, "_logger", logging)
82         if (exception_type in (threading.ThreadError, MemoryError) or
83             exception_type is OSError and exception_value.errno == errno.ENOMEM):
84             lg.critical("Unhandled exception is a fatal error, killing Node Manager")
85             os.killpg(os.getpgid(0), 9)