replace Xrn.get_sliver_id()
[sfa.git] / sfa / openstack / osaggregate.py
1
2 import os
3 import socket
4 import base64
5 import string
6 import random    
7 from collections import defaultdict
8 from nova.exception import ImageNotFound
9 from nova.api.ec2.cloud import CloudController
10 from sfa.util.faults import SfaAPIError
11 from sfa.rspecs.rspec import RSpec
12 from sfa.rspecs.elements.hardware_type import HardwareType
13 from sfa.rspecs.elements.node import Node
14 from sfa.rspecs.elements.sliver import Sliver
15 from sfa.rspecs.elements.login import Login
16 from sfa.rspecs.elements.disk_image import DiskImage
17 from sfa.rspecs.elements.services import Services
18 from sfa.rspecs.elements.interface import Interface
19 from sfa.util.xrn import Xrn
20 from sfa.planetlab.plxrn import PlXrn 
21 from sfa.openstack.osxrn import OSXrn, hrn_to_os_slicename
22 from sfa.rspecs.version_manager import VersionManager
23 from sfa.openstack.security_group import SecurityGroup
24 from sfa.server.threadmanager import ThreadManager
25 from sfa.util.sfalogging import logger
26
27 def pubkeys_to_user_data(pubkeys):
28     user_data = "#!/bin/bash\n\n"
29     for pubkey in pubkeys:
30         pubkey = pubkey.replace('\n', '')
31         user_data += "echo %s >> /root/.ssh/authorized_keys" % pubkey
32         user_data += "\n"
33         user_data += "echo >> /root/.ssh/authorized_keys"
34         user_data += "\n"
35     return user_data
36
37 def instance_to_sliver(instance, slice_xrn=None):
38     sliver_id = None
39     sliver = Sliver({'name': instance.name,
40                      'type': instance.name,
41                      'cpus': str(instance.vcpus),
42                      'memory': str(instance.ram),
43                      'storage':  str(instance.disk)})
44     return sliver
45
46 def image_to_rspec_disk_image(image):
47     img = DiskImage()
48     img['name'] = image['name']
49     img['description'] = image['name']
50     img['os'] = image['name']
51     img['version'] = image['name']    
52     return img
53     
54 class OSAggregate:
55
56     def __init__(self, driver):
57         self.driver = driver
58
59     def get_rspec(self, slice_xrn=None, version=None, options={}):
60         version_manager = VersionManager()
61         version = version_manager.get_version(version)
62         if not slice_xrn:
63             rspec_version = version_manager._get_version(version.type, version.version, 'ad')
64             nodes = self.get_aggregate_nodes()
65         else:
66             rspec_version = version_manager._get_version(version.type, version.version, 'manifest')
67             nodes = self.get_slice_nodes(slice_xrn)
68         rspec = RSpec(version=rspec_version, user_options=options)
69         rspec.version.add_nodes(nodes)
70         return rspec.toxml()
71
72     def get_availability_zones(self):
73         # essex release
74         zones = self.driver.shell.nova_manager.dns_domains.domains()
75
76         if not zones:
77             zones = ['cloud']
78         else:
79             zones = [zone.name for zone in zones]
80         return zones
81
82     def get_slice_nodes(self, slice_xrn):
83         # update nova connection
84         tenant_name = OSXrn(xrn=slice_xrn, type='slice').get_tenant_name()
85         self.driver.shell.nova_manager.connect(tenant=tenant_name)    
86         
87         zones = self.get_availability_zones()
88         name = hrn_to_os_slicename(slice_xrn)
89         instances = self.driver.shell.nova_manager.servers.findall(name=name)
90         rspec_nodes = []
91         for instance in instances:
92             # determine node urn
93             node_xrn = instance.metadata.get('component_id')
94             if not node_xrn:
95                 node_xrn = OSXrn('cloud', type='node')
96             else:
97                 node_xrn = OSXrn(xrn=node_xrn, type='node')
98
99             rspec_node = Node()
100             rspec_node['component_id'] = node_xrn.urn
101             rspec_node['component_name'] = node_xrn.name
102             rspec_node['component_manager_id'] = Xrn(self.driver.hrn, 'authority+cm').get_urn()
103             rspec_node['slivers'] = []
104
105             if instance.metadata.get('client_id'):
106                 rspec_node['client_id'] = instance.metadata.get('client_id')
107             
108             flavor = self.driver.shell.nova_manager.flavors.find(id=instance.flavor['id'])
109             sliver = instance_to_sliver(flavor)
110             rspec_node['slivers'].append(sliver)
111             sliver_xrn = OSXrn(xrn=slice_xrn, type='slice', id=instance.id)
112             rspec_node['sliver_id'] = sliver_xrn.get_urn()
113             image = self.driver.shell.image_manager.get_images(id=instance.image['id'])
114             if isinstance(image, list) and len(image) > 0:
115                 image = image[0]
116             disk_image = image_to_rspec_disk_image(image)
117             sliver['disk_image'] = [disk_image]
118
119             # build interfaces            
120             rspec_node['services'] = []
121             rspec_node['interfaces'] = []
122             addresses = instance.addresses
123             # HACK: public ips are stored in the list of private, but 
124             # this seems wrong. Assume pub ip is the last in the list of 
125             # private ips until openstack bug is fixed.      
126             if addresses.get('private'):
127                 login = Login({'authentication': 'ssh-keys',
128                                'hostname': addresses.get('private')[-1]['addr'],
129                                'port':'22', 'username': 'root'})
130                 service = Services({'login': login})
131                 rspec_node['services'].append(service)    
132             
133             for private_ip in addresses.get('private', []):
134                 if_xrn = PlXrn(auth=self.driver.hrn, 
135                                interface='node%s:eth0' % (instance.hostId)) 
136                 interface = Interface({'component_id': if_xrn.urn})
137                 interface['ips'] =  [{'address': private_ip['addr'],
138                                      #'netmask': private_ip['network'],
139                                      'type': 'ipv%s' % str(private_ip['version'])}]
140                 rspec_node['interfaces'].append(interface) 
141             
142             # slivers always provide the ssh service
143             for public_ip in addresses.get('public', []):
144                 login = Login({'authentication': 'ssh-keys', 
145                                'hostname': public_ip['addr'], 
146                                'port':'22', 'username': 'root'})
147                 service = Services({'login': login})
148                 rspec_node['services'].append(service)
149             rspec_nodes.append(rspec_node)
150         return rspec_nodes
151
152     def get_aggregate_nodes(self):
153         zones = self.get_availability_zones()
154         # available sliver/instance/vm types
155         instances = self.driver.shell.nova_manager.flavors.list()
156         if isinstance(instances, dict):
157             instances = instances.values()
158         # available images
159         images = self.driver.shell.image_manager.get_images_detailed()
160         disk_images  = [image_to_rspec_disk_image(img) for img in images if img['container_format'] in ['ami', 'ovf']]
161         rspec_nodes = []
162         for zone in zones:
163             rspec_node = Node()
164             xrn = OSXrn(zone, type='node')
165             rspec_node['component_id'] = xrn.urn
166             rspec_node['component_name'] = xrn.name
167             rspec_node['component_manager_id'] = Xrn(self.driver.hrn, 'authority+cm').get_urn()
168             rspec_node['exclusive'] = 'false'
169             rspec_node['hardware_types'] = [HardwareType({'name': 'plos-pc'}),
170                                                 HardwareType({'name': 'pc'})]
171             slivers = []
172             for instance in instances:
173                 sliver = instance_to_sliver(instance)
174                 sliver['disk_image'] = disk_images
175                 slivers.append(sliver)
176         
177             rspec_node['slivers'] = slivers
178             rspec_nodes.append(rspec_node) 
179
180         return rspec_nodes 
181
182
183     def create_tenant(self, tenant_name):
184         tenants = self.driver.shell.auth_manager.tenants.findall(name=tenant_name)
185         if not tenants:
186             self.driver.shell.auth_manager.tenants.create(tenant_name, tenant_name)
187             tenant = self.driver.shell.auth_manager.tenants.find(name=tenant_name)
188         else:
189             tenant = tenants[0]
190         return tenant
191             
192
193     def create_instance_key(self, slice_hrn, user):
194         slice_name = Xrn(slice_hrn).leaf
195         user_name = Xrn(user['urn']).leaf
196         key_name = "%s_%s" % (slice_name, user_name)
197         pubkey = user['keys'][0]
198         key_found = False
199         existing_keys = self.driver.shell.nova_manager.keypairs.findall(name=key_name)
200         for existing_key in existing_keys:
201             if existing_key.public_key != pubkey:
202                 self.driver.shell.nova_manager.keypairs.delete(existing_key)
203             elif existing_key.public_key == pubkey:
204                 key_found = True
205
206         if not key_found:
207             self.driver.shell.nova_manager.keypairs.create(key_name, pubkey)
208         return key_name       
209         
210
211     def create_security_group(self, slicename, fw_rules=[]):
212         # use default group by default
213         group_name = 'default' 
214         if isinstance(fw_rules, list) and fw_rules:
215             # Each sliver get's its own security group.
216             # Keep security group names unique by appending some random
217             # characters on end.
218             random_name = "".join([random.choice(string.letters+string.digits)
219                                            for i in xrange(6)])
220             group_name = slicename + random_name 
221             security_group = SecurityGroup(self.driver)
222             security_group.create_security_group(group_name)
223             for rule in fw_rules:
224                 security_group.add_rule_to_group(group_name, 
225                                              protocol = rule.get('protocol'), 
226                                              cidr_ip = rule.get('cidr_ip'), 
227                                              port_range = rule.get('port_range'), 
228                                              icmp_type_code = rule.get('icmp_type_code'))
229         return group_name
230
231     def add_rule_to_security_group(self, group_name, **kwds):
232         security_group = SecurityGroup(self.driver)
233         security_group.add_rule_to_group(group_name=group_name, 
234                                          protocol=kwds.get('protocol'), 
235                                          cidr_ip =kwds.get('cidr_ip'), 
236                                          icmp_type_code = kwds.get('icmp_type_code'))
237
238  
239
240     def run_instances(self, instance_name, tenant_name, rspec, key_name, pubkeys):
241         #logger.debug('Reserving an instance: image: %s, flavor: ' \
242         #            '%s, key: %s, name: %s' % \
243         #            (image_id, flavor_id, key_name, slicename))
244
245         # make sure a tenant exists for this slice
246         tenant = self.create_tenant(tenant_name)  
247
248         # add the sfa admin user to this tenant and update our nova client connection
249         # to use these credentials for the rest of this session. This emsures that the instances
250         # we create will be assigned to the correct tenant.
251         sfa_admin_user = self.driver.shell.auth_manager.users.find(name=self.driver.shell.auth_manager.opts['OS_USERNAME'])
252         user_role = self.driver.shell.auth_manager.roles.find(name='user')
253         admin_role = self.driver.shell.auth_manager.roles.find(name='admin')
254         self.driver.shell.auth_manager.roles.add_user_role(sfa_admin_user, admin_role, tenant)
255         self.driver.shell.auth_manager.roles.add_user_role(sfa_admin_user, user_role, tenant)
256         self.driver.shell.nova_manager.connect(tenant=tenant.name)  
257
258         authorized_keys = "\n".join(pubkeys)
259         files = {'/root/.ssh/authorized_keys': authorized_keys}
260         rspec = RSpec(rspec)
261         requested_instances = defaultdict(list)
262         # iterate over clouds/zones/nodes
263         for node in rspec.version.get_nodes_with_slivers():
264             instances = node.get('slivers', [])
265             if not instances:
266                 continue
267             for instance in instances:
268                 try: 
269                     metadata = {}
270                     flavor_id = self.driver.shell.nova_manager.flavors.find(name=instance['name'])
271                     image = instance.get('disk_image')
272                     if image and isinstance(image, list):
273                         image = image[0]
274                     image_id = self.driver.shell.nova_manager.images.find(name=image['name'])
275                     fw_rules = instance.get('fw_rules', [])
276                     group_name = self.create_security_group(instance_name, fw_rules)
277                     metadata['security_groups'] = group_name
278                     if node.get('component_id'):
279                         metadata['component_id'] = node['component_id']
280                     if node.get('client_id'):
281                         metadata['client_id'] = node['client_id']
282                     self.driver.shell.nova_manager.servers.create(flavor=flavor_id,
283                                                             image=image_id,
284                                                             key_name = key_name,
285                                                             security_groups = [group_name],
286                                                             files=files,
287                                                             meta=metadata, 
288                                                             name=instance_name)
289                 except Exception, err:    
290                     logger.log_exc(err)                                
291                            
292
293
294     def delete_instances(self, instance_name, tenant_name):
295
296         def _delete_security_group(instance):
297             security_group = instance.metadata.get('security_groups', '')
298             if security_group:
299                 manager = SecurityGroup(self.driver)
300                 timeout = 10.0 # wait a maximum of 10 seconds before forcing the security group delete
301                 start_time = time.time()
302                 instance_deleted = False
303                 while instance_deleted == False and (time.time() - start_time) < timeout:
304                     inst = self.driver.shell.nova_manager.servers.findall(id=instance.id)
305                     if not inst:
306                         instance_deleted = True
307                     time.sleep(.5)
308                 manager.delete_security_group(security_group)
309
310         thread_manager = ThreadManager()
311         self.driver.shell.nova_manager.connect(tenant=tenant_name)
312         instances = self.driver.shell.nova_manager.servers.findall(name=instance_name)
313         for instance in instances:
314             # destroy instance
315             self.driver.shell.nova_manager.servers.delete(instance)
316             # deleate this instance's security groups
317             thread_manager.run(_delete_security_group, instance)
318         return 1
319
320
321     def stop_instances(self, instance_name, tenant_name):
322         self.driver.shell.nova_manager.connect(tenant=tenant_name)
323         instances = self.driver.shell.nova_manager.servers.findall(name=instance_name)
324         for instance in instances:
325             self.driver.shell.nova_manager.servers.pause(instance)
326         return 1
327
328     def update_instances(self, project_name):
329         pass