3 from __future__ import absolute_import, print_function
6 from operator import attrgetter
8 import libcloud.common.types as cloud_types
9 from libcloud.common.exceptions import BaseHTTPError
10 from libcloud.compute.base import NodeDriver, NodeAuthSSHKey
12 from ...config import NETWORK_ERRORS
13 from .. import RetryMixin
15 class BaseComputeNodeDriver(RetryMixin):
16 """Abstract base class for compute node drivers.
18 libcloud drivers abstract away many of the differences between
19 cloud providers, but managing compute nodes requires some
20 cloud-specific features (e.g., keeping track of node FQDNs and
21 boot times). Compute node drivers are responsible for translating
22 the node manager's cloud requests to a specific cloud's
25 Subclasses must implement arvados_create_kwargs, sync_node,
26 node_fqdn, and node_start_time.
28 CLOUD_ERRORS = NETWORK_ERRORS + (cloud_types.LibcloudError,)
31 def _create_driver(self, driver_class, **auth_kwargs):
32 return driver_class(**auth_kwargs)
36 self.sizes = {sz.id: sz for sz in self.real.list_sizes()}
38 def __init__(self, auth_kwargs, list_kwargs, create_kwargs,
39 driver_class, retry_wait=1, max_retry_wait=180):
40 """Base initializer for compute node drivers.
43 * auth_kwargs: A dictionary of arguments that are passed into the
44 driver_class constructor to instantiate a libcloud driver.
45 * list_kwargs: A dictionary of arguments that are passed to the
46 libcloud driver's list_nodes method to return the list of compute
48 * create_kwargs: A dictionary of arguments that are passed to the
49 libcloud driver's create_node method to create a new compute node.
50 * driver_class: The class of a libcloud driver to use.
53 super(BaseComputeNodeDriver, self).__init__(retry_wait, max_retry_wait,
54 logging.getLogger(self.__class__.__name__),
57 self.real = self._create_driver(driver_class, **auth_kwargs)
58 self.list_kwargs = list_kwargs
59 self.create_kwargs = create_kwargs
60 # Transform entries in create_kwargs. For each key K, if this class
61 # has an _init_K method, remove the entry and call _init_K with the
62 # corresponding value. If _init_K returns None, the entry stays out
63 # of the dictionary (we expect we're holding the value somewhere
64 # else, like an instance variable). Otherwise, _init_K returns a
65 # key-value tuple pair, and we add that entry to create_kwargs.
66 for key in self.create_kwargs.keys():
67 init_method = getattr(self, '_init_' + key, None)
68 if init_method is not None:
69 new_pair = init_method(self.create_kwargs.pop(key))
70 if new_pair is not None:
71 self.create_kwargs[new_pair[0]] = new_pair[1]
75 def _init_ping_host(self, ping_host):
76 self.ping_host = ping_host
78 def _init_ssh_key(self, filename):
79 with open(filename) as ssh_file:
80 key = NodeAuthSSHKey(ssh_file.read())
83 def search_for_now(self, term, list_method, key=attrgetter('id'), **kwargs):
84 """Return one matching item from a list of cloud objects.
86 Raises ValueError if the number of matching objects is not exactly 1.
89 * term: The value that identifies a matching item.
90 * list_method: A string that names the method to call for a
92 * key: A function that accepts a cloud object and returns a
93 value search for a `term` match on each item. Returns the
94 object's 'id' attribute by default.
97 list_func = getattr(self, list_method)
98 except AttributeError:
99 list_func = getattr(self.real, list_method)
100 items = list_func(**kwargs)
101 results = [item for item in items if key(item) == term]
104 raise ValueError("{} returned {} results for {!r}".format(
105 list_method, count, term))
108 def search_for(self, term, list_method, key=attrgetter('id'), **kwargs):
109 """Return one cached matching item from a list of cloud objects.
111 See search_for_now() for details of arguments and exceptions.
112 This method caches results, so it's good to find static cloud objects
113 like node sizes, regions, etc.
115 cache_key = (list_method, term)
116 if cache_key not in self.SEARCH_CACHE:
117 self.SEARCH_CACHE[cache_key] = self.search_for_now(
118 term, list_method, key, **kwargs)
119 return self.SEARCH_CACHE[cache_key]
121 def list_nodes(self, **kwargs):
122 l = self.list_kwargs.copy()
124 return self.real.list_nodes(**l)
126 def create_cloud_name(self, arvados_node):
127 """Return a cloud node name for the given Arvados node record.
129 Subclasses must override this method. It should return a string
130 that can be used as the name for a newly-created cloud node,
131 based on identifying information in the Arvados node record.
134 * arvados_node: This Arvados node record to seed the new cloud node.
136 raise NotImplementedError("BaseComputeNodeDriver.create_cloud_name")
138 def arvados_create_kwargs(self, size, arvados_node):
139 """Return dynamic keyword arguments for create_node.
141 Subclasses must override this method. It should return a dictionary
142 of keyword arguments to pass to the libcloud driver's create_node
143 method. These arguments will extend the static arguments in
147 * size: The node size that will be created (libcloud NodeSize object)
148 * arvados_node: The Arvados node record that will be associated
149 with this cloud node, as returned from the API server.
151 raise NotImplementedError("BaseComputeNodeDriver.arvados_create_kwargs")
153 def broken(self, cloud_node):
154 """Return true if libcloud has indicated the node is in a "broken" state."""
157 def _make_ping_url(self, arvados_node):
158 return 'https://{}/arvados/v1/nodes/{}/ping?ping_secret={}'.format(
159 self.ping_host, arvados_node['uuid'],
160 arvados_node['info']['ping_secret'])
163 def _name_key(cloud_object):
164 return cloud_object.name
166 def create_node(self, size, arvados_node):
168 kwargs = self.create_kwargs.copy()
169 kwargs.update(self.arvados_create_kwargs(size, arvados_node))
170 kwargs['size'] = size
171 return self.real.create_node(**kwargs)
172 except self.CLOUD_ERRORS as create_error:
173 # Workaround for bug #6702: sometimes the create node request
174 # succeeds but times out and raises an exception instead of
175 # returning a result. If this happens, we get stuck in a retry
176 # loop forever because subsequent create_node attempts will fail
177 # due to node name collision. So check if the node we intended to
178 # create shows up in the cloud node list and return it if found.
180 return self.search_for_now(kwargs['name'], 'list_nodes', self._name_key)
184 def post_create_node(self, cloud_node):
185 # ComputeNodeSetupActor calls this method after the cloud node is
186 # created. Any setup tasks that need to happen afterward (e.g.,
187 # tagging) should be done in this method.
190 def sync_node(self, cloud_node, arvados_node):
191 # When a compute node first pings the API server, the API server
192 # will automatically assign some attributes on the corresponding
193 # node record, like hostname. This method should propagate that
194 # information back to the cloud node appropriately.
195 raise NotImplementedError("BaseComputeNodeDriver.sync_node")
198 def node_fqdn(cls, node):
199 # This method should return the FQDN of the node object argument.
200 # Different clouds store this in different places.
201 raise NotImplementedError("BaseComputeNodeDriver.node_fqdn")
204 def node_start_time(cls, node):
205 # This method should return the time the node was started, in
206 # seconds since the epoch UTC.
207 raise NotImplementedError("BaseComputeNodeDriver.node_start_time")
210 def is_cloud_exception(cls, exception):
211 # libcloud compute drivers typically raise bare Exceptions to
212 # represent API errors. Return True for any exception that is
213 # exactly an Exception, or a better-known higher-level exception.
214 if (type(exception) is BaseHTTPError and
215 exception.message and
216 (exception.message.startswith("InvalidInstanceID.NotFound") or
217 exception.message.startswith("InstanceLimitExceeded"))):
219 return (isinstance(exception, cls.CLOUD_ERRORS) or
220 type(exception) is Exception)
222 def destroy_node(self, cloud_node):
224 return self.real.destroy_node(cloud_node)
225 except self.CLOUD_ERRORS as destroy_error:
226 # Sometimes the destroy node request succeeds but times out and
227 # raises an exception instead of returning success. If this
228 # happens, we get a noisy stack trace. Check if the node is still
229 # on the node list. If it is gone, we can declare victory.
231 self.search_for_now(cloud_node.id, 'list_nodes')
233 # If we catch ValueError, that means search_for_now didn't find
234 # it, which means destroy_node actually succeeded.
236 # The node is still on the list. Re-raise.
239 # Now that we've defined all our own methods, delegate generic, public
240 # attributes of libcloud drivers that we haven't defined ourselves.
241 def _delegate_to_real(attr_name):
243 lambda self: getattr(self.real, attr_name),
244 lambda self, value: setattr(self.real, attr_name, value),
245 doc=getattr(getattr(NodeDriver, attr_name), '__doc__', None))
250 raise NotImplementedError("BaseComputeNodeDriver.node_id")
253 for _attr_name in dir(NodeDriver):
254 if (not _attr_name.startswith('_')) and (_attr_name not in _locals):
255 _locals[_attr_name] = _delegate_to_real(_attr_name)