Add 'tools/arvbox/' from commit 'd3d368758db1f4a9fa5b89f77b5ee61d68ef5b72'
[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 logging
6 from operator import attrgetter
7
8 import libcloud.common.types as cloud_types
9 from libcloud.compute.base import NodeDriver, NodeAuthSSHKey
10
11 from ...config import NETWORK_ERRORS
12 from .. import RetryMixin
13
14 class BaseComputeNodeDriver(RetryMixin):
15     """Abstract base class for compute node drivers.
16
17     libcloud drivers abstract away many of the differences between
18     cloud providers, but managing compute nodes requires some
19     cloud-specific features (e.g., keeping track of node FQDNs and
20     boot times).  Compute node drivers are responsible for translating
21     the node manager's cloud requests to a specific cloud's
22     vocabulary.
23
24     Subclasses must implement arvados_create_kwargs, sync_node,
25     node_fqdn, and node_start_time.
26     """
27     CLOUD_ERRORS = NETWORK_ERRORS + (cloud_types.LibcloudError,)
28
29     @RetryMixin._retry()
30     def _create_driver(self, driver_class, **auth_kwargs):
31         return driver_class(**auth_kwargs)
32
33     @RetryMixin._retry()
34     def _set_sizes(self):
35         self.sizes = {sz.id: sz for sz in self.real.list_sizes()}
36
37     def __init__(self, auth_kwargs, list_kwargs, create_kwargs,
38                  driver_class, retry_wait=1, max_retry_wait=180):
39         """Base initializer for compute node drivers.
40
41         Arguments:
42         * auth_kwargs: A dictionary of arguments that are passed into the
43           driver_class constructor to instantiate a libcloud driver.
44         * list_kwargs: A dictionary of arguments that are passed to the
45           libcloud driver's list_nodes method to return the list of compute
46           nodes.
47         * create_kwargs: A dictionary of arguments that are passed to the
48           libcloud driver's create_node method to create a new compute node.
49         * driver_class: The class of a libcloud driver to use.
50         """
51
52         super(BaseComputeNodeDriver, self).__init__(retry_wait, max_retry_wait,
53                                          logging.getLogger(self.__class__.__name__),
54                                          type(self),
55                                          None)
56         self.real = self._create_driver(driver_class, **auth_kwargs)
57         self.list_kwargs = list_kwargs
58         self.create_kwargs = create_kwargs
59         # Transform entries in create_kwargs.  For each key K, if this class
60         # has an _init_K method, remove the entry and call _init_K with the
61         # corresponding value.  If _init_K returns None, the entry stays out
62         # of the dictionary (we expect we're holding the value somewhere
63         # else, like an instance variable).  Otherwise, _init_K returns a
64         # key-value tuple pair, and we add that entry to create_kwargs.
65         for key in self.create_kwargs.keys():
66             init_method = getattr(self, '_init_' + key, None)
67             if init_method is not None:
68                 new_pair = init_method(self.create_kwargs.pop(key))
69                 if new_pair is not None:
70                     self.create_kwargs[new_pair[0]] = new_pair[1]
71
72         self._set_sizes()
73
74     def _init_ping_host(self, ping_host):
75         self.ping_host = ping_host
76
77     def _init_ssh_key(self, filename):
78         with open(filename) as ssh_file:
79             key = NodeAuthSSHKey(ssh_file.read())
80         return 'auth', key
81
82     def search_for(self, term, list_method, key=attrgetter('id'), **kwargs):
83         """Return one matching item from a list of cloud objects.
84
85         Raises ValueError if the number of matching objects is not exactly 1.
86
87         Arguments:
88         * term: The value that identifies a matching item.
89         * list_method: A string that names the method to call on this
90           instance's libcloud driver for a list of objects.
91         * key: A function that accepts a cloud object and returns a
92           value search for a `term` match on each item.  Returns the
93           object's 'id' attribute by default.
94         """
95         cache_key = (list_method, term)
96         if cache_key not in self.SEARCH_CACHE:
97             items = getattr(self.real, list_method)(**kwargs)
98             results = [item for item in items
99                        if key(item) == term]
100             count = len(results)
101             if count != 1:
102                 raise ValueError("{} returned {} results for '{}'".format(
103                         list_method, count, term))
104             self.SEARCH_CACHE[cache_key] = results[0]
105         return self.SEARCH_CACHE[cache_key]
106
107     def list_nodes(self):
108         return self.real.list_nodes(**self.list_kwargs)
109
110     def arvados_create_kwargs(self, size, arvados_node):
111         """Return dynamic keyword arguments for create_node.
112
113         Subclasses must override this method.  It should return a dictionary
114         of keyword arguments to pass to the libcloud driver's create_node
115         method.  These arguments will extend the static arguments in
116         create_kwargs.
117
118         Arguments:
119         * size: The node size that will be created (libcloud NodeSize object)
120         * arvados_node: The Arvados node record that will be associated
121           with this cloud node, as returned from the API server.
122         """
123         raise NotImplementedError("BaseComputeNodeDriver.arvados_create_kwargs")
124
125     def broken(self, cloud_node):
126         """Return true if libcloud has indicated the node is in a "broken" state."""
127         return False
128
129     def _make_ping_url(self, arvados_node):
130         return 'https://{}/arvados/v1/nodes/{}/ping?ping_secret={}'.format(
131             self.ping_host, arvados_node['uuid'],
132             arvados_node['info']['ping_secret'])
133
134     @staticmethod
135     def _name_key(cloud_object):
136         return cloud_object.name
137
138     def create_node(self, size, arvados_node):
139         try:
140             kwargs = self.create_kwargs.copy()
141             kwargs.update(self.arvados_create_kwargs(size, arvados_node))
142             kwargs['size'] = size
143             return self.real.create_node(**kwargs)
144         except self.CLOUD_ERRORS:
145             # Workaround for bug #6702: sometimes the create node request
146             # succeeds but times out and raises an exception instead of
147             # returning a result.  If this happens, we get stuck in a retry
148             # loop forever because subsequent create_node attempts will fail
149             # due to node name collision.  So check if the node we intended to
150             # create shows up in the cloud node list and return it if found.
151             node = self.search_for(kwargs['name'], 'list_nodes', self._name_key)
152             if node:
153                 return node
154             else:
155                 # something else went wrong, re-raise the exception
156                 raise
157
158     def post_create_node(self, cloud_node):
159         # ComputeNodeSetupActor calls this method after the cloud node is
160         # created.  Any setup tasks that need to happen afterward (e.g.,
161         # tagging) should be done in this method.
162         pass
163
164     def sync_node(self, cloud_node, arvados_node):
165         # When a compute node first pings the API server, the API server
166         # will automatically assign some attributes on the corresponding
167         # node record, like hostname.  This method should propagate that
168         # information back to the cloud node appropriately.
169         raise NotImplementedError("BaseComputeNodeDriver.sync_node")
170
171     @classmethod
172     def node_fqdn(cls, node):
173         # This method should return the FQDN of the node object argument.
174         # Different clouds store this in different places.
175         raise NotImplementedError("BaseComputeNodeDriver.node_fqdn")
176
177     @classmethod
178     def node_start_time(cls, node):
179         # This method should return the time the node was started, in
180         # seconds since the epoch UTC.
181         raise NotImplementedError("BaseComputeNodeDriver.node_start_time")
182
183     @classmethod
184     def is_cloud_exception(cls, exception):
185         # libcloud compute drivers typically raise bare Exceptions to
186         # represent API errors.  Return True for any exception that is
187         # exactly an Exception, or a better-known higher-level exception.
188         return (isinstance(exception, cls.CLOUD_ERRORS) or
189                 type(exception) is Exception)
190
191     # Now that we've defined all our own methods, delegate generic, public
192     # attributes of libcloud drivers that we haven't defined ourselves.
193     def _delegate_to_real(attr_name):
194         return property(
195             lambda self: getattr(self.real, attr_name),
196             lambda self, value: setattr(self.real, attr_name, value),
197             doc=getattr(getattr(NodeDriver, attr_name), '__doc__', None))
198
199     _locals = locals()
200     for _attr_name in dir(NodeDriver):
201         if (not _attr_name.startswith('_')) and (_attr_name not in _locals):
202             _locals[_attr_name] = _delegate_to_real(_attr_name)