3 from __future__ import absolute_import, print_function
9 import libcloud.compute.providers as cloud_provider
10 import libcloud.compute.types as cloud_types
12 from . import BaseComputeNodeDriver
13 from .. import arvados_node_fqdn, arvados_timestamp, ARVADOS_TIMEFMT
15 class ComputeNodeDriver(BaseComputeNodeDriver):
16 """Compute node driver wrapper for GCE
18 This translates cloud driver requests to GCE's specific parameters.
20 DEFAULT_DRIVER = cloud_provider.get_driver(cloud_types.Provider.GCE)
23 def __init__(self, auth_kwargs, list_kwargs, create_kwargs,
24 driver_class=DEFAULT_DRIVER):
25 list_kwargs = list_kwargs.copy()
26 tags_str = list_kwargs.pop('tags', '')
27 if not tags_str.strip():
28 self.node_tags = frozenset()
30 self.node_tags = frozenset(t.strip() for t in tags_str.split(','))
31 create_kwargs = create_kwargs.copy()
32 create_kwargs.setdefault('external_ip', None)
33 create_kwargs.setdefault('ex_metadata', {})
34 super(ComputeNodeDriver, self).__init__(
35 auth_kwargs, list_kwargs, create_kwargs,
37 self._disktype_links = {dt.name: self._object_link(dt)
38 for dt in self.real.ex_list_disktypes()}
41 def _name_key(cloud_object):
42 return cloud_object.name
45 def _object_link(cloud_object):
46 return cloud_object.extra.get('selfLink')
48 def _init_image(self, image_name):
49 return 'image', self.search_for(
50 image_name, 'list_images', self._name_key)
52 def _init_network(self, network_name):
53 return 'ex_network', self.search_for(
54 network_name, 'ex_list_networks', self._name_key)
56 def _init_service_accounts(self, service_accounts_str):
57 return 'ex_service_accounts', json.loads(service_accounts_str)
59 def _init_ssh_key(self, filename):
60 # SSH keys are delivered to GCE nodes via ex_metadata: see
61 # http://stackoverflow.com/questions/26752617/creating-sshkeys-for-gce-instance-using-libcloud
62 with open(filename) as ssh_file:
63 self.create_kwargs['ex_metadata']['sshKeys'] = (
64 'root:' + ssh_file.read().strip())
66 def arvados_create_kwargs(self, arvados_node):
67 cluster_id, _, node_id = arvados_node['uuid'].split('-')
68 name = 'compute-{}-{}'.format(node_id, cluster_id)
75 'diskType': self._disktype_links['pd-standard'],
76 'sourceImage': self._object_link(self.create_kwargs['image']),
82 # Boot images rely on this device name to find the SSD.
83 # Any change must be coordinated in the image.
86 {'diskType': self._disktype_links['local-ssd'],
91 result = {'name': name,
92 'ex_metadata': self.create_kwargs['ex_metadata'].copy(),
93 'ex_tags': list(self.node_tags),
94 'ex_disks_gce_struct': disks,
96 result['ex_metadata'].update({
97 'arv-ping-url': self._make_ping_url(arvados_node),
98 'booted_at': time.strftime(ARVADOS_TIMEFMT, time.gmtime()),
99 'hostname': arvados_node_fqdn(arvados_node),
103 def list_nodes(self):
104 # The GCE libcloud driver only supports filtering node lists by zone.
105 # Do our own filtering based on tag list.
106 return [node for node in
107 super(ComputeNodeDriver, self).list_nodes()
108 if self.node_tags.issubset(node.extra.get('tags', []))]
111 def _find_metadata(cls, metadata_items, key):
112 # Given a list of two-item metadata dictonaries, return the one with
113 # the named key. Raise KeyError if not found.
115 return next(data_dict for data_dict in metadata_items
116 if data_dict.get('key') == key)
117 except StopIteration:
121 def _get_metadata(cls, metadata_items, key, *default):
123 return cls._find_metadata(metadata_items, key)['value']
129 def sync_node(self, cloud_node, arvados_node):
130 # We can't store the FQDN on the name attribute or anything like it,
131 # because (a) names are static throughout the node's life (so FQDN
132 # isn't available because we don't know it at node creation time) and
133 # (b) it can't contain dots. Instead stash it in metadata.
134 hostname = arvados_node_fqdn(arvados_node)
135 metadata_req = cloud_node.extra['metadata'].copy()
136 metadata_items = metadata_req.setdefault('items', [])
138 self._find_metadata(metadata_items, 'hostname')['value'] = hostname
140 metadata_items.append({'key': 'hostname', 'value': hostname})
141 response = self.real.connection.async_request(
142 '/zones/{}/instances/{}/setMetadata'.format(
143 cloud_node.extra['zone'].name, cloud_node.name),
144 method='POST', data=metadata_req)
145 if not response.success():
146 raise Exception("setMetadata error: {}".format(response.error))
149 def node_fqdn(cls, node):
150 # See sync_node comment.
151 return cls._get_metadata(node.extra['metadata'].get('items', []),
155 def node_start_time(cls, node):
157 return arvados_timestamp(cls._get_metadata(
158 node.extra['metadata']['items'], 'booted_at'))