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