2 # Copyright (C) The Arvados Authors. All rights reserved.
4 # SPDX-License-Identifier: AGPL-3.0
6 from __future__ import absolute_import, print_function
9 from operator import attrgetter
11 import libcloud.common.types as cloud_types
12 from libcloud.compute.base import NodeDriver, NodeAuthSSHKey
14 from ...config import CLOUD_ERRORS
15 from .. import RetryMixin
17 class BaseComputeNodeDriver(RetryMixin):
18 """Abstract base class for compute node drivers.
20 libcloud drivers abstract away many of the differences between
21 cloud providers, but managing compute nodes requires some
22 cloud-specific features (e.g., keeping track of node FQDNs and
23 boot times). Compute node drivers are responsible for translating
24 the node manager's cloud requests to a specific cloud's
27 Subclasses must implement arvados_create_kwargs, sync_node,
28 node_fqdn, and node_start_time.
33 def _create_driver(self, driver_class, **auth_kwargs):
34 return driver_class(**auth_kwargs)
38 self.sizes = {sz.id: sz for sz in self.real.list_sizes()}
40 def __init__(self, auth_kwargs, list_kwargs, create_kwargs,
41 driver_class, retry_wait=1, max_retry_wait=180):
42 """Base initializer for compute node drivers.
45 * auth_kwargs: A dictionary of arguments that are passed into the
46 driver_class constructor to instantiate a libcloud driver.
47 * list_kwargs: A dictionary of arguments that are passed to the
48 libcloud driver's list_nodes method to return the list of compute
50 * create_kwargs: A dictionary of arguments that are passed to the
51 libcloud driver's create_node method to create a new compute node.
52 * driver_class: The class of a libcloud driver to use.
55 super(BaseComputeNodeDriver, self).__init__(retry_wait, max_retry_wait,
56 logging.getLogger(self.__class__.__name__),
59 self.real = self._create_driver(driver_class, **auth_kwargs)
60 self.list_kwargs = list_kwargs
61 self.create_kwargs = create_kwargs
62 # Transform entries in create_kwargs. For each key K, if this class
63 # has an _init_K method, remove the entry and call _init_K with the
64 # corresponding value. If _init_K returns None, the entry stays out
65 # of the dictionary (we expect we're holding the value somewhere
66 # else, like an instance variable). Otherwise, _init_K returns a
67 # key-value tuple pair, and we add that entry to create_kwargs.
68 for key in self.create_kwargs.keys():
69 init_method = getattr(self, '_init_' + key, None)
70 if init_method is not None:
71 new_pair = init_method(self.create_kwargs.pop(key))
72 if new_pair is not None:
73 self.create_kwargs[new_pair[0]] = new_pair[1]
77 def _init_ping_host(self, ping_host):
78 self.ping_host = ping_host
80 def _init_ssh_key(self, filename):
81 with open(filename) as ssh_file:
82 key = NodeAuthSSHKey(ssh_file.read())
85 def search_for_now(self, term, list_method, key=attrgetter('id'), **kwargs):
86 """Return one matching item from a list of cloud objects.
88 Raises ValueError if the number of matching objects is not exactly 1.
91 * term: The value that identifies a matching item.
92 * list_method: A string that names the method to call for a
94 * key: A function that accepts a cloud object and returns a
95 value search for a `term` match on each item. Returns the
96 object's 'id' attribute by default.
99 list_func = getattr(self, list_method)
100 except AttributeError:
101 list_func = getattr(self.real, list_method)
102 items = list_func(**kwargs)
103 results = [item for item in items if key(item) == term]
106 raise ValueError("{} returned {} results for {!r}".format(
107 list_method, count, term))
110 def search_for(self, term, list_method, key=attrgetter('id'), **kwargs):
111 """Return one cached matching item from a list of cloud objects.
113 See search_for_now() for details of arguments and exceptions.
114 This method caches results, so it's good to find static cloud objects
115 like node sizes, regions, etc.
117 cache_key = (list_method, term)
118 if cache_key not in self.SEARCH_CACHE:
119 self.SEARCH_CACHE[cache_key] = self.search_for_now(
120 term, list_method, key, **kwargs)
121 return self.SEARCH_CACHE[cache_key]
123 def list_nodes(self, **kwargs):
124 l = self.list_kwargs.copy()
126 return self.real.list_nodes(**l)
128 def create_cloud_name(self, arvados_node):
129 """Return a cloud node name for the given Arvados node record.
131 Subclasses must override this method. It should return a string
132 that can be used as the name for a newly-created cloud node,
133 based on identifying information in the Arvados node record.
136 * arvados_node: This Arvados node record to seed the new cloud node.
138 raise NotImplementedError("BaseComputeNodeDriver.create_cloud_name")
140 def arvados_create_kwargs(self, size, arvados_node):
141 """Return dynamic keyword arguments for create_node.
143 Subclasses must override this method. It should return a dictionary
144 of keyword arguments to pass to the libcloud driver's create_node
145 method. These arguments will extend the static arguments in
149 * size: The node size that will be created (libcloud NodeSize object)
150 * arvados_node: The Arvados node record that will be associated
151 with this cloud node, as returned from the API server.
153 raise NotImplementedError("BaseComputeNodeDriver.arvados_create_kwargs")
155 def broken(self, cloud_node):
156 """Return true if libcloud has indicated the node is in a "broken" state."""
159 def _make_ping_url(self, arvados_node):
160 return 'https://{}/arvados/v1/nodes/{}/ping?ping_secret={}'.format(
161 self.ping_host, arvados_node['uuid'],
162 arvados_node['info']['ping_secret'])
165 def _name_key(cloud_object):
166 return cloud_object.name
168 def create_node(self, size, arvados_node):
170 kwargs = self.create_kwargs.copy()
171 kwargs.update(self.arvados_create_kwargs(size, arvados_node))
172 kwargs['size'] = size
173 return self.real.create_node(**kwargs)
174 except CLOUD_ERRORS as create_error:
175 # Workaround for bug #6702: sometimes the create node request
176 # succeeds but times out and raises an exception instead of
177 # returning a result. If this happens, we get stuck in a retry
178 # loop forever because subsequent create_node attempts will fail
179 # due to node name collision. So check if the node we intended to
180 # create shows up in the cloud node list and return it if found.
182 return self.search_for_now(kwargs['name'], 'list_nodes', self._name_key)
186 def post_create_node(self, cloud_node):
187 # ComputeNodeSetupActor calls this method after the cloud node is
188 # created. Any setup tasks that need to happen afterward (e.g.,
189 # tagging) should be done in this method.
192 def sync_node(self, cloud_node, arvados_node):
193 # When a compute node first pings the API server, the API server
194 # will automatically assign some attributes on the corresponding
195 # node record, like hostname. This method should propagate that
196 # information back to the cloud node appropriately.
197 raise NotImplementedError("BaseComputeNodeDriver.sync_node")
200 def node_fqdn(cls, node):
201 # This method should return the FQDN of the node object argument.
202 # Different clouds store this in different places.
203 raise NotImplementedError("BaseComputeNodeDriver.node_fqdn")
206 def node_start_time(cls, node):
207 # This method should return the time the node was started, in
208 # seconds since the epoch UTC.
209 raise NotImplementedError("BaseComputeNodeDriver.node_start_time")
211 def destroy_node(self, cloud_node):
213 return self.real.destroy_node(cloud_node)
214 except CLOUD_ERRORS as destroy_error:
215 # Sometimes the destroy node request succeeds but times out and
216 # raises an exception instead of returning success. If this
217 # happens, we get a noisy stack trace. Check if the node is still
218 # on the node list. If it is gone, we can declare victory.
220 self.search_for_now(cloud_node.id, 'list_nodes')
222 # If we catch ValueError, that means search_for_now didn't find
223 # it, which means destroy_node actually succeeded.
225 # The node is still on the list. Re-raise.
228 # Now that we've defined all our own methods, delegate generic, public
229 # attributes of libcloud drivers that we haven't defined ourselves.
230 def _delegate_to_real(attr_name):
232 lambda self: getattr(self.real, attr_name),
233 lambda self, value: setattr(self.real, attr_name, value),
234 doc=getattr(getattr(NodeDriver, attr_name), '__doc__', None))
239 raise NotImplementedError("BaseComputeNodeDriver.node_id")
242 for _attr_name in dir(NodeDriver):
243 if (not _attr_name.startswith('_')) and (_attr_name not in _locals):
244 _locals[_attr_name] = _delegate_to_real(_attr_name)