Merge branch 'master' into 6702-gce-node-create-fix
[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     def __init__(self, auth_kwargs, list_kwargs, create_kwargs,
34                  driver_class, retry_wait=1, max_retry_wait=180):
35         """Base initializer for compute node drivers.
36
37         Arguments:
38         * auth_kwargs: A dictionary of arguments that are passed into the
39           driver_class constructor to instantiate a libcloud driver.
40         * list_kwargs: A dictionary of arguments that are passed to the
41           libcloud driver's list_nodes method to return the list of compute
42           nodes.
43         * create_kwargs: A dictionary of arguments that are passed to the
44           libcloud driver's create_node method to create a new compute node.
45         * driver_class: The class of a libcloud driver to use.
46         """
47
48         super(BaseComputeNodeDriver, self).__init__(retry_wait, max_retry_wait,
49                                          logging.getLogger(str(type(self))),
50                                          type(self),
51                                          None)
52         self.real = self._create_driver(driver_class, **auth_kwargs)
53         self.list_kwargs = list_kwargs
54         self.create_kwargs = create_kwargs
55         # Transform entries in create_kwargs.  For each key K, if this class
56         # has an _init_K method, remove the entry and call _init_K with the
57         # corresponding value.  If _init_K returns None, the entry stays out
58         # of the dictionary (we expect we're holding the value somewhere
59         # else, like an instance variable).  Otherwise, _init_K returns a
60         # key-value tuple pair, and we add that entry to create_kwargs.
61         for key in self.create_kwargs.keys():
62             init_method = getattr(self, '_init_' + key, None)
63             if init_method is not None:
64                 new_pair = init_method(self.create_kwargs.pop(key))
65                 if new_pair is not None:
66                     self.create_kwargs[new_pair[0]] = new_pair[1]
67
68         self.sizes = {sz.id: sz for sz in self.real.list_sizes()}
69
70     def _init_ping_host(self, ping_host):
71         self.ping_host = ping_host
72
73     def _init_ssh_key(self, filename):
74         with open(filename) as ssh_file:
75             key = NodeAuthSSHKey(ssh_file.read())
76         return 'auth', key
77
78     def search_for(self, term, list_method, key=attrgetter('id'), **kwargs):
79         """Return one matching item from a list of cloud objects.
80
81         Raises ValueError if the number of matching objects is not exactly 1.
82
83         Arguments:
84         * term: The value that identifies a matching item.
85         * list_method: A string that names the method to call on this
86           instance's libcloud driver for a list of objects.
87         * key: A function that accepts a cloud object and returns a
88           value search for a `term` match on each item.  Returns the
89           object's 'id' attribute by default.
90         """
91         cache_key = (list_method, term)
92         if cache_key not in self.SEARCH_CACHE:
93             items = getattr(self.real, list_method)(**kwargs)
94             results = [item for item in items
95                        if key(item) == term]
96             count = len(results)
97             if count != 1:
98                 raise ValueError("{} returned {} results for '{}'".format(
99                         list_method, count, term))
100             self.SEARCH_CACHE[cache_key] = results[0]
101         return self.SEARCH_CACHE[cache_key]
102
103     def list_nodes(self):
104         return self.real.list_nodes(**self.list_kwargs)
105
106     def arvados_create_kwargs(self, size, arvados_node):
107         """Return dynamic keyword arguments for create_node.
108
109         Subclasses must override this method.  It should return a dictionary
110         of keyword arguments to pass to the libcloud driver's create_node
111         method.  These arguments will extend the static arguments in
112         create_kwargs.
113
114         Arguments:
115         * size: The node size that will be created (libcloud NodeSize object)
116         * arvados_node: The Arvados node record that will be associated
117           with this cloud node, as returned from the API server.
118         """
119         raise NotImplementedError("BaseComputeNodeDriver.arvados_create_kwargs")
120
121     def broken(self, cloud_node):
122         """Return true if libcloud has indicated the node is in a "broken" state."""
123         return False
124
125     def _make_ping_url(self, arvados_node):
126         return 'https://{}/arvados/v1/nodes/{}/ping?ping_secret={}'.format(
127             self.ping_host, arvados_node['uuid'],
128             arvados_node['info']['ping_secret'])
129
130     def create_node(self, size, arvados_node):
131         kwargs = self.create_kwargs.copy()
132         kwargs.update(self.arvados_create_kwargs(size, arvados_node))
133         kwargs['size'] = size
134         return self.real.create_node(**kwargs)
135
136     def post_create_node(self, cloud_node):
137         # ComputeNodeSetupActor calls this method after the cloud node is
138         # created.  Any setup tasks that need to happen afterward (e.g.,
139         # tagging) should be done in this method.
140         pass
141
142     def sync_node(self, cloud_node, arvados_node):
143         # When a compute node first pings the API server, the API server
144         # will automatically assign some attributes on the corresponding
145         # node record, like hostname.  This method should propagate that
146         # information back to the cloud node appropriately.
147         raise NotImplementedError("BaseComputeNodeDriver.sync_node")
148
149     @classmethod
150     def node_fqdn(cls, node):
151         # This method should return the FQDN of the node object argument.
152         # Different clouds store this in different places.
153         raise NotImplementedError("BaseComputeNodeDriver.node_fqdn")
154
155     @classmethod
156     def node_start_time(cls, node):
157         # This method should return the time the node was started, in
158         # seconds since the epoch UTC.
159         raise NotImplementedError("BaseComputeNodeDriver.node_start_time")
160
161     @classmethod
162     def is_cloud_exception(cls, exception):
163         # libcloud compute drivers typically raise bare Exceptions to
164         # represent API errors.  Return True for any exception that is
165         # exactly an Exception, or a better-known higher-level exception.
166         return (isinstance(exception, cls.CLOUD_ERRORS) or
167                 type(exception) is Exception)
168
169     # Now that we've defined all our own methods, delegate generic, public
170     # attributes of libcloud drivers that we haven't defined ourselves.
171     def _delegate_to_real(attr_name):
172         return property(
173             lambda self: getattr(self.real, attr_name),
174             lambda self, value: setattr(self.real, attr_name, value),
175             doc=getattr(getattr(NodeDriver, attr_name), '__doc__', None))
176
177     _locals = locals()
178     for _attr_name in dir(NodeDriver):
179         if (not _attr_name.startswith('_')) and (_attr_name not in _locals):
180             _locals[_attr_name] = _delegate_to_real(_attr_name)