3 from __future__ import absolute_import, print_function
6 from operator import attrgetter
8 import libcloud.common.types as cloud_types
9 from libcloud.compute.base import NodeDriver, NodeAuthSSHKey
11 from ...config import CLOUD_ERRORS
12 from .. import RetryMixin
14 class BaseComputeNodeDriver(RetryMixin):
15 """Abstract base class for compute node drivers.
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
24 Subclasses must implement arvados_create_kwargs, sync_node,
25 node_fqdn, and node_start_time.
30 def _create_driver(self, driver_class, **auth_kwargs):
31 return driver_class(**auth_kwargs)
35 self.sizes = {sz.id: sz for sz in self.real.list_sizes()}
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.
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
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.
52 super(BaseComputeNodeDriver, self).__init__(retry_wait, max_retry_wait,
53 logging.getLogger(self.__class__.__name__),
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]
74 def _init_ping_host(self, ping_host):
75 self.ping_host = ping_host
77 def _init_ssh_key(self, filename):
78 with open(filename) as ssh_file:
79 key = NodeAuthSSHKey(ssh_file.read())
82 def search_for_now(self, term, list_method, key=attrgetter('id'), **kwargs):
83 """Return one matching item from a list of cloud objects.
85 Raises ValueError if the number of matching objects is not exactly 1.
88 * term: The value that identifies a matching item.
89 * list_method: A string that names the method to call for a
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.
96 list_func = getattr(self, list_method)
97 except AttributeError:
98 list_func = getattr(self.real, list_method)
99 items = list_func(**kwargs)
100 results = [item for item in items if key(item) == term]
103 raise ValueError("{} returned {} results for {!r}".format(
104 list_method, count, term))
107 def search_for(self, term, list_method, key=attrgetter('id'), **kwargs):
108 """Return one cached matching item from a list of cloud objects.
110 See search_for_now() for details of arguments and exceptions.
111 This method caches results, so it's good to find static cloud objects
112 like node sizes, regions, etc.
114 cache_key = (list_method, term)
115 if cache_key not in self.SEARCH_CACHE:
116 self.SEARCH_CACHE[cache_key] = self.search_for_now(
117 term, list_method, key, **kwargs)
118 return self.SEARCH_CACHE[cache_key]
120 def list_nodes(self, **kwargs):
121 l = self.list_kwargs.copy()
123 return self.real.list_nodes(**l)
125 def create_cloud_name(self, arvados_node):
126 """Return a cloud node name for the given Arvados node record.
128 Subclasses must override this method. It should return a string
129 that can be used as the name for a newly-created cloud node,
130 based on identifying information in the Arvados node record.
133 * arvados_node: This Arvados node record to seed the new cloud node.
135 raise NotImplementedError("BaseComputeNodeDriver.create_cloud_name")
137 def arvados_create_kwargs(self, size, arvados_node):
138 """Return dynamic keyword arguments for create_node.
140 Subclasses must override this method. It should return a dictionary
141 of keyword arguments to pass to the libcloud driver's create_node
142 method. These arguments will extend the static arguments in
146 * size: The node size that will be created (libcloud NodeSize object)
147 * arvados_node: The Arvados node record that will be associated
148 with this cloud node, as returned from the API server.
150 raise NotImplementedError("BaseComputeNodeDriver.arvados_create_kwargs")
152 def broken(self, cloud_node):
153 """Return true if libcloud has indicated the node is in a "broken" state."""
156 def _make_ping_url(self, arvados_node):
157 return 'https://{}/arvados/v1/nodes/{}/ping?ping_secret={}'.format(
158 self.ping_host, arvados_node['uuid'],
159 arvados_node['info']['ping_secret'])
162 def _name_key(cloud_object):
163 return cloud_object.name
165 def create_node(self, size, arvados_node):
167 kwargs = self.create_kwargs.copy()
168 kwargs.update(self.arvados_create_kwargs(size, arvados_node))
169 kwargs['size'] = size
170 return self.real.create_node(**kwargs)
171 except CLOUD_ERRORS as create_error:
172 # Workaround for bug #6702: sometimes the create node request
173 # succeeds but times out and raises an exception instead of
174 # returning a result. If this happens, we get stuck in a retry
175 # loop forever because subsequent create_node attempts will fail
176 # due to node name collision. So check if the node we intended to
177 # create shows up in the cloud node list and return it if found.
179 return self.search_for_now(kwargs['name'], 'list_nodes', self._name_key)
183 def post_create_node(self, cloud_node):
184 # ComputeNodeSetupActor calls this method after the cloud node is
185 # created. Any setup tasks that need to happen afterward (e.g.,
186 # tagging) should be done in this method.
189 def sync_node(self, cloud_node, arvados_node):
190 # When a compute node first pings the API server, the API server
191 # will automatically assign some attributes on the corresponding
192 # node record, like hostname. This method should propagate that
193 # information back to the cloud node appropriately.
194 raise NotImplementedError("BaseComputeNodeDriver.sync_node")
197 def node_fqdn(cls, node):
198 # This method should return the FQDN of the node object argument.
199 # Different clouds store this in different places.
200 raise NotImplementedError("BaseComputeNodeDriver.node_fqdn")
203 def node_start_time(cls, node):
204 # This method should return the time the node was started, in
205 # seconds since the epoch UTC.
206 raise NotImplementedError("BaseComputeNodeDriver.node_start_time")
208 def destroy_node(self, cloud_node):
210 return self.real.destroy_node(cloud_node)
211 except CLOUD_ERRORS as destroy_error:
212 # Sometimes the destroy node request succeeds but times out and
213 # raises an exception instead of returning success. If this
214 # happens, we get a noisy stack trace. Check if the node is still
215 # on the node list. If it is gone, we can declare victory.
217 self.search_for_now(cloud_node.id, 'list_nodes')
219 # If we catch ValueError, that means search_for_now didn't find
220 # it, which means destroy_node actually succeeded.
222 # The node is still on the list. Re-raise.
225 # Now that we've defined all our own methods, delegate generic, public
226 # attributes of libcloud drivers that we haven't defined ourselves.
227 def _delegate_to_real(attr_name):
229 lambda self: getattr(self.real, attr_name),
230 lambda self, value: setattr(self.real, attr_name, value),
231 doc=getattr(getattr(NodeDriver, attr_name), '__doc__', None))
236 raise NotImplementedError("BaseComputeNodeDriver.node_id")
239 for _attr_name in dir(NodeDriver):
240 if (not _attr_name.startswith('_')) and (_attr_name not in _locals):
241 _locals[_attr_name] = _delegate_to_real(_attr_name)