Merge branch 'master' into 4232-slow-pipes-n-jobs
[arvados.git] / services / nodemanager / arvnodeman / computenode / driver / __init__.py
1 #!/usr/bin/env python
2
3 from __future__ import absolute_import, print_function
4
5 import libcloud.common.types as cloud_types
6 from libcloud.compute.base import NodeDriver
7
8 from ...config import NETWORK_ERRORS
9
10 class BaseComputeNodeDriver(object):
11     """Abstract base class for compute node drivers.
12
13     libcloud abstracts away many of the differences between cloud providers,
14     but managing compute nodes requires some cloud-specific features (e.g.,
15     on EC2 we use tags to identify compute nodes).  Compute node drivers
16     are responsible for translating the node manager's cloud requests to a
17     specific cloud's vocabulary.
18
19     Subclasses must implement arvados_create_kwargs (to update node
20     creation kwargs with information about the specific Arvados node
21     record), sync_node, and node_start_time.
22     """
23     CLOUD_ERRORS = NETWORK_ERRORS + (cloud_types.LibcloudError,)
24
25     def __init__(self, auth_kwargs, list_kwargs, create_kwargs, driver_class):
26         self.real = driver_class(**auth_kwargs)
27         self.list_kwargs = list_kwargs
28         self.create_kwargs = create_kwargs
29         for key in self.create_kwargs.keys():
30             init_method = getattr(self, '_init_' + key, None)
31             if init_method is not None:
32                 new_pair = init_method(self.create_kwargs.pop(key))
33                 if new_pair is not None:
34                     self.create_kwargs[new_pair[0]] = new_pair[1]
35
36     def _init_ping_host(self, ping_host):
37         self.ping_host = ping_host
38
39     def search_for(self, term, list_method, key=lambda item: item.id):
40         cache_key = (list_method, term)
41         if cache_key not in self.SEARCH_CACHE:
42             results = [item for item in getattr(self.real, list_method)()
43                        if key(item) == term]
44             count = len(results)
45             if count != 1:
46                 raise ValueError("{} returned {} results for '{}'".format(
47                         list_method, count, term))
48             self.SEARCH_CACHE[cache_key] = results[0]
49         return self.SEARCH_CACHE[cache_key]
50
51     def list_nodes(self):
52         return self.real.list_nodes(**self.list_kwargs)
53
54     def arvados_create_kwargs(self, arvados_node):
55         raise NotImplementedError("BaseComputeNodeDriver.arvados_create_kwargs")
56
57     def _make_ping_url(self, arvados_node):
58         return 'https://{}/arvados/v1/nodes/{}/ping?ping_secret={}'.format(
59             self.ping_host, arvados_node['uuid'],
60             arvados_node['info']['ping_secret'])
61
62     def create_node(self, size, arvados_node):
63         kwargs = self.create_kwargs.copy()
64         kwargs.update(self.arvados_create_kwargs(arvados_node))
65         kwargs['size'] = size
66         return self.real.create_node(**kwargs)
67
68     def post_create_node(self, cloud_node):
69         # ComputeNodeSetupActor calls this method after the cloud node is
70         # created.  Any setup tasks that need to happen afterward (e.g.,
71         # tagging) should be done in this method.
72         pass
73
74     def sync_node(self, cloud_node, arvados_node):
75         # When a compute node first pings the API server, the API server
76         # will automatically assign some attributes on the corresponding
77         # node record, like hostname.  This method should propagate that
78         # information back to the cloud node appropriately.
79         raise NotImplementedError("BaseComputeNodeDriver.sync_node")
80
81     @classmethod
82     def node_start_time(cls, node):
83         raise NotImplementedError("BaseComputeNodeDriver.node_start_time")
84
85     @classmethod
86     def is_cloud_exception(cls, exception):
87         # libcloud compute drivers typically raise bare Exceptions to
88         # represent API errors.  Return True for any exception that is
89         # exactly an Exception, or a better-known higher-level exception.
90         return (isinstance(exception, cls.CLOUD_ERRORS) or
91                 getattr(exception, '__class__', None) is Exception)
92
93     # Now that we've defined all our own methods, delegate generic, public
94     # attributes of libcloud drivers that we haven't defined ourselves.
95     def _delegate_to_real(attr_name):
96         return property(
97             lambda self: getattr(self.real, attr_name),
98             lambda self, value: setattr(self.real, attr_name, value),
99             doc=getattr(getattr(NodeDriver, attr_name), '__doc__', None))
100
101     _locals = locals()
102     for _attr_name in dir(NodeDriver):
103         if (not _attr_name.startswith('_')) and (_attr_name not in _locals):
104             _locals[_attr_name] = _delegate_to_real(_attr_name)