Merge branch 'master' of ssh://git.planet-lab.org/git/sfa
[sfa.git] / sfa / managers / aggregate_manager_eucalyptus.py
1 from __future__ import with_statement 
2
3 import sys
4 import os
5
6 import boto
7 from boto.ec2.regioninfo import RegionInfo
8 from boto.exception import EC2ResponseError
9 from ConfigParser import ConfigParser
10 from xmlbuilder import XMLBuilder
11 from lxml import etree as ET
12 from sqlobject import *
13
14 from sfa.util.faults import *
15 from sfa.util.xrn import urn_to_hrn
16 from sfa.util.rspec import RSpec
17 from sfa.server.registry import Registries
18 from sfa.trust.credential import Credential
19 from sfa.plc.api import SfaAPI
20 from sfa.util.plxrn import hrn_to_pl_slicename, slicename_to_hrn
21
22 ##
23 # The data structure used to represent a cloud.
24 # It contains the cloud name, its ip address, image information,
25 # key pairs, and clusters information.
26 #
27 cloud = {}
28
29 ##
30 # The location of the RelaxNG schema.
31 #
32 EUCALYPTUS_RSPEC_SCHEMA='/etc/sfa/eucalyptus.rng'
33
34 # Quick hack
35 sys.stderr = file('/var/log/euca_agg.log', 'a+')
36 api = SfaAPI()
37
38 ##
39 # A representation of an Eucalyptus instance. This is a support class
40 # for instance <-> slice mapping.
41 #
42 class EucaInstance(SQLObject):
43     instance_id = StringCol(unique=True, default=None)
44     kernel_id   = StringCol()
45     image_id    = StringCol()
46     ramdisk_id  = StringCol()
47     inst_type   = StringCol()
48     key_pair    = StringCol()
49     slice = ForeignKey('Slice')
50
51     ##
52     # Contacts Eucalyptus and tries to reserve this instance.
53     # 
54     # @param botoConn A connection to Eucalyptus.
55     # @param pubKeys A list of public keys for the instance.
56     #
57     def reserveInstance(self, botoConn, pubKeys):
58         print >>sys.stderr, 'Reserving an instance: image: %s, kernel: ' \
59                             '%s, ramdisk: %s, type: %s, key: %s' % \
60                             (self.image_id, self.kernel_id, self.ramdisk_id, 
61                              self.inst_type, self.key_pair)
62
63         # XXX The return statement is for testing. REMOVE in production
64         #return
65
66         try:
67             reservation = botoConn.run_instances(self.image_id,
68                                                  kernel_id = self.kernel_id,
69                                                  ramdisk_id = self.ramdisk_id,
70                                                  instance_type = self.inst_type,
71                                                  key_name  = self.key_pair,
72                                                  user_data = pubKeys)
73             for instance in reservation.instances:
74                 self.instance_id = instance.id
75
76         # If there is an error, destroy itself.
77         except EC2ResponseError, ec2RespErr:
78             errTree = ET.fromstring(ec2RespErr.body)
79             msg = errTree.find('.//Message')
80             print >>sys.stderr, msg.text
81             self.destroySelf()
82
83 ##
84 # A representation of a PlanetLab slice. This is a support class
85 # for instance <-> slice mapping.
86 #
87 class Slice(SQLObject):
88     slice_hrn = StringCol()
89     #slice_index = DatabaseIndex('slice_hrn')
90     instances = MultipleJoin('EucaInstance')
91
92 ##
93 # Initialize the aggregate manager by reading a configuration file.
94 #
95 def init_server():
96     configParser = ConfigParser()
97     configParser.read(['/etc/sfa/eucalyptus_aggregate.conf', 'eucalyptus_aggregate.conf'])
98     if len(configParser.sections()) < 1:
99         print >>sys.stderr, 'No cloud defined in the config file'
100         raise Exception('Cannot find cloud definition in configuration file.')
101
102     # Only read the first section.
103     cloudSec = configParser.sections()[0]
104     cloud['name'] = cloudSec
105     cloud['access_key'] = configParser.get(cloudSec, 'access_key')
106     cloud['secret_key'] = configParser.get(cloudSec, 'secret_key')
107     cloud['cloud_url']  = configParser.get(cloudSec, 'cloud_url')
108     cloudURL = cloud['cloud_url']
109     if cloudURL.find('https://') >= 0:
110         cloudURL = cloudURL.replace('https://', '')
111     elif cloudURL.find('http://') >= 0:
112         cloudURL = cloudURL.replace('http://', '')
113     (cloud['ip'], parts) = cloudURL.split(':')
114
115     # Initialize sqlite3 database.
116     dbPath = '/etc/sfa/db'
117     dbName = 'euca_aggregate.db'
118
119     if not os.path.isdir(dbPath):
120         print >>sys.stderr, '%s not found. Creating directory ...' % dbPath
121         os.mkdir(dbPath)
122
123     conn = connectionForURI('sqlite://%s/%s' % (dbPath, dbName))
124     sqlhub.processConnection = conn
125     Slice.createTable(ifNotExists=True)
126     EucaInstance.createTable(ifNotExists=True)
127
128     # Make sure the schema exists.
129     if not os.path.exists(EUCALYPTUS_RSPEC_SCHEMA):
130         err = 'Cannot location schema at %s' % EUCALYPTUS_RSPEC_SCHEMA
131         print >>sys.stderr, err
132         raise Exception(err)
133
134 ##
135 # Creates a connection to Eucalytpus. This function is inspired by 
136 # the make_connection() in Euca2ools.
137 #
138 # @return A connection object or None
139 #
140 def getEucaConnection():
141     global cloud
142     accessKey = cloud['access_key']
143     secretKey = cloud['secret_key']
144     eucaURL   = cloud['cloud_url']
145     useSSL    = False
146     srvPath   = '/'
147     eucaPort  = 8773
148
149     if not accessKey or not secretKey or not eucaURL:
150         print >>sys.stderr, 'Please set ALL of the required environment ' \
151                             'variables by sourcing the eucarc file.'
152         return None
153     
154     # Split the url into parts
155     if eucaURL.find('https://') >= 0:
156         useSSL  = True
157         eucaURL = eucaURL.replace('https://', '')
158     elif eucaURL.find('http://') >= 0:
159         useSSL  = False
160         eucaURL = eucaURL.replace('http://', '')
161     (eucaHost, parts) = eucaURL.split(':')
162     if len(parts) > 1:
163         parts = parts.split('/')
164         eucaPort = int(parts[0])
165         parts = parts[1:]
166         srvPath = '/'.join(parts)
167
168     return boto.connect_ec2(aws_access_key_id=accessKey,
169                             aws_secret_access_key=secretKey,
170                             is_secure=useSSL,
171                             region=RegionInfo(None, 'eucalyptus', eucaHost), 
172                             port=eucaPort,
173                             path=srvPath)
174
175 ##
176 # Returns a string of keys that belong to the users of the given slice.
177 # @param sliceHRN The hunman readable name of the slice.
178 # @return sting()
179 #
180 def getKeysForSlice(sliceHRN):
181     try:
182         # convert hrn to slice name
183         plSliceName = hrn_to_pl_slicename(sliceHRN)
184     except IndexError, e:
185         print >>sys.stderr, 'Invalid slice name (%s)' % sliceHRN
186         return []
187
188     # Get the slice's information
189     sliceData = api.plshell.GetSlices(api.plauth, {'name':plSliceName})
190     if not sliceData:
191         print >>sys.stderr, 'Cannot get any data for slice %s' % plSliceName
192         return []
193
194     # It should only return a list with len = 1
195     sliceData = sliceData[0]
196
197     keys = []
198     person_ids = sliceData['person_ids']
199     if not person_ids: 
200         print >>sys.stderr, 'No users in slice %s' % sliceHRN
201         return []
202
203     persons = api.plshell.GetPersons(api.plauth, person_ids)
204     for person in persons:
205         pkeys = api.plshell.GetKeys(api.plauth, person['key_ids'])
206         for key in pkeys:
207             keys.append(key['key'])
208  
209     return ''.join(keys)
210
211 ##
212 # A class that builds the RSpec for Eucalyptus.
213 #
214 class EucaRSpecBuilder(object):
215     ##
216     # Initizes a RSpec builder
217     #
218     # @param cloud A dictionary containing data about a 
219     #              cloud (ex. clusters, ip)
220     def __init__(self, cloud):
221         self.eucaRSpec = XMLBuilder(format = True, tab_step = "  ")
222         self.cloudInfo = cloud
223
224     ##
225     # Creates a request stanza.
226     # 
227     # @param num The number of instances to create.
228     # @param image The disk image id.
229     # @param kernel The kernel image id.
230     # @param keypair Key pair to embed.
231     # @param ramdisk Ramdisk id (optional).
232     #
233     def __requestXML(self, num, image, kernel, keypair, ramdisk = ''):
234         xml = self.eucaRSpec
235         with xml.request:
236             with xml.instances:
237                 xml << str(num)
238             with xml.kernel_image(id=kernel):
239                 xml << ''
240             if ramdisk == '':
241                 with xml.ramdisk:
242                     xml << ''
243             else:
244                 with xml.ramdisk(id=ramdisk):
245                     xml << ''
246             with xml.disk_image(id=image):
247                 xml << ''
248             with xml.keypair:
249                 xml << keypair
250
251     ##
252     # Creates the cluster stanza.
253     #
254     # @param clusters Clusters information.
255     #
256     def __clustersXML(self, clusters):
257         cloud = self.cloudInfo
258         xml = self.eucaRSpec
259
260         for cluster in clusters:
261             instances = cluster['instances']
262             with xml.cluster(id=cluster['name']):
263                 with xml.ipv4:
264                     xml << cluster['ip']
265                 with xml.vm_types:
266                     for inst in instances:
267                         with xml.vm_type(name=inst[0]):
268                             with xml.free_slots:
269                                 xml << str(inst[1])
270                             with xml.max_instances:
271                                 xml << str(inst[2])
272                             with xml.cores:
273                                 xml << str(inst[3])
274                             with xml.memory(unit='MB'):
275                                 xml << str(inst[4])
276                             with xml.disk_space(unit='GB'):
277                                 xml << str(inst[5])
278                             if inst[0] == 'm1.small':
279                                 self.__requestXML(1, 'emi-88760F45', 'eki-F26610C6', 'cortex')
280                             if 'instances' in cloud and inst[0] in cloud['instances']:
281                                 existingEucaInstances = cloud['instances'][inst[0]]
282                                 with xml.euca_instances:
283                                     for eucaInst in existingEucaInstances:
284                                         with xml.euca_instance(id=eucaInst['id']):
285                                             with xml.state:
286                                                 xml << eucaInst['state']
287                                             with xml.public_dns:
288                                                 xml << eucaInst['public_dns']
289                                             with xml.keypair:
290                                                 xml << eucaInst['key']
291
292     ##
293     # Creates the Images stanza.
294     #
295     # @param images A list of images in Eucalyptus.
296     #
297     def __imagesXML(self, images):
298         xml = self.eucaRSpec
299         with xml.images:
300             for image in images:
301                 with xml.image(id=image.id):
302                     with xml.type:
303                         xml << image.type
304                     with xml.arch:
305                         xml << image.architecture
306                     with xml.state:
307                         xml << image.state
308                     with xml.location:
309                         xml << image.location
310
311     ##
312     # Creates the KeyPairs stanza.
313     #
314     # @param keypairs A list of key pairs in Eucalyptus.
315     #
316     def __keyPairsXML(self, keypairs):
317         xml = self.eucaRSpec
318         with xml.keypairs:
319             for key in keypairs:
320                 with xml.keypair:
321                     xml << key.name
322
323     ##
324     # Generates the RSpec.
325     #
326     def toXML(self):
327         if not self.cloudInfo:
328             print >>sys.stderr, 'No cloud information'
329             return ''
330
331         xml = self.eucaRSpec
332         cloud = self.cloudInfo
333         with xml.RSpec(type='eucalyptus'):
334             with xml.cloud(id=cloud['name']):
335                 with xml.ipv4:
336                     xml << cloud['ip']
337                 self.__keyPairsXML(cloud['keypairs'])
338                 self.__imagesXML(cloud['images'])
339                 self.__clustersXML(cloud['clusters'])
340         return str(xml)
341
342 ##
343 # A parser to parse the output of availability-zones.
344 #
345 # Note: Only one cluster is supported. If more than one, this will
346 #       not work.
347 #
348 class ZoneResultParser(object):
349     def __init__(self, zones):
350         self.zones = zones
351
352     def parse(self):
353         if len(self.zones) < 3:
354             return
355         clusterList = []
356         cluster = {} 
357         instList = []
358
359         cluster['name'] = self.zones[0].name
360         cluster['ip']   = self.zones[0].state
361
362         for i in range(2, len(self.zones)):
363             currZone = self.zones[i]
364             instType = currZone.name.split()[1]
365
366             stateString = currZone.state.split('/')
367             rscString   = stateString[1].split()
368
369             instFree      = int(stateString[0])
370             instMax       = int(rscString[0])
371             instNumCpu    = int(rscString[1])
372             instRam       = int(rscString[2])
373             instDiskSpace = int(rscString[3])
374
375             instTuple = (instType, instFree, instMax, instNumCpu, instRam, instDiskSpace)
376             instList.append(instTuple)
377         cluster['instances'] = instList
378         clusterList.append(cluster)
379
380         return clusterList
381
382 def get_rspec(api, creds, options): 
383     global cloud
384     # get slice's hrn from options
385     xrn = options.get('geni_slice_urn', '')
386     hrn, type = urn_to_hrn(xrn)
387
388     # get hrn of the original caller
389     origin_hrn = options.get('origin_hrn', None)
390     if not origin_hrn:
391         origin_hrn = Credential(string=creds[0]).get_gid_caller().get_hrn()
392
393     conn = getEucaConnection()
394
395     if not conn:
396         print >>sys.stderr, 'Error: Cannot create a connection to Eucalyptus'
397         return 'Cannot create a connection to Eucalyptus'
398
399     try:
400         # Zones
401         zones = conn.get_all_zones(['verbose'])
402         p = ZoneResultParser(zones)
403         clusters = p.parse()
404         cloud['clusters'] = clusters
405         
406         # Images
407         images = conn.get_all_images()
408         cloud['images'] = images
409
410         # Key Pairs
411         keyPairs = conn.get_all_key_pairs()
412         cloud['keypairs'] = keyPairs
413
414         if hrn:
415             instanceId = []
416             instances  = []
417
418             # Get the instances that belong to the given slice from sqlite3
419             # XXX use getOne() in production because the slice's hrn is supposed
420             # to be unique. For testing, uniqueness is turned off in the db.
421             # If the slice isn't found in the database, create a record for the 
422             # slice.
423             matchedSlices = list(Slice.select(Slice.q.slice_hrn == hrn))
424             if matchedSlices:
425                 theSlice = matchedSlices[-1]
426             else:
427                 theSlice = Slice(slice_hrn = hrn)
428             for instance in theSlice.instances:
429                 instanceId.append(instance.instance_id)
430
431             # Get the information about those instances using their ids.
432             if len(instanceId) > 0:
433                 reservations = conn.get_all_instances(instanceId)
434             else:
435                 reservations = []
436             for reservation in reservations:
437                 for instance in reservation.instances:
438                     instances.append(instance)
439
440             # Construct a dictory for the EucaRSpecBuilder
441             instancesDict = {}
442             for instance in instances:
443                 instList = instancesDict.setdefault(instance.instance_type, [])
444                 instInfoDict = {} 
445
446                 instInfoDict['id'] = instance.id
447                 instInfoDict['public_dns'] = instance.public_dns_name
448                 instInfoDict['state'] = instance.state
449                 instInfoDict['key'] = instance.key_name
450
451                 instList.append(instInfoDict)
452             cloud['instances'] = instancesDict
453
454     except EC2ResponseError, ec2RespErr:
455         errTree = ET.fromstring(ec2RespErr.body)
456         errMsgE = errTree.find('.//Message')
457         print >>sys.stderr, errMsgE.text
458
459     rspec = EucaRSpecBuilder(cloud).toXML()
460
461     # Remove the instances records so next time they won't 
462     # show up.
463     if 'instances' in cloud:
464         del cloud['instances']
465
466     return rspec
467
468 """
469 Hook called via 'sfi.py create'
470 """
471 def create_slice(api, xrn, creds, xml, users):
472     global cloud
473     hrn = urn_to_hrn(xrn)[0]
474
475     conn = getEucaConnection()
476     if not conn:
477         print >>sys.stderr, 'Error: Cannot create a connection to Eucalyptus'
478         return False
479
480     # Validate RSpec
481     schemaXML = ET.parse(EUCALYPTUS_RSPEC_SCHEMA)
482     rspecValidator = ET.RelaxNG(schemaXML)
483     rspecXML = ET.XML(xml)
484     if not rspecValidator(rspecXML):
485         error = rspecValidator.error_log.last_error
486         message = '%s (line %s)' % (error.message, error.line) 
487         # XXX: InvalidRSpec is new. Currently, I am not working with Trunk code.
488         #raise InvalidRSpec(message)
489         raise Exception(message)
490
491     # Get the slice from db or create one.
492     s = Slice.select(Slice.q.slice_hrn == hrn).getOne(None)
493     if s is None:
494         s = Slice(slice_hrn = hrn)
495
496     # Process any changes in existing instance allocation
497     pendingRmInst = []
498     for sliceInst in s.instances:
499         pendingRmInst.append(sliceInst.instance_id)
500     existingInstGroup = rspecXML.findall('.//euca_instances')
501     for instGroup in existingInstGroup:
502         for existingInst in instGroup:
503             if existingInst.get('id') in pendingRmInst:
504                 pendingRmInst.remove(existingInst.get('id'))
505     for inst in pendingRmInst:
506         print >>sys.stderr, 'Instance %s will be terminated' % inst
507         dbInst = EucaInstance.select(EucaInstance.q.instance_id == inst).getOne(None)
508         dbInst.destroySelf()
509     conn.terminate_instances(pendingRmInst)
510
511     # Process new instance requests
512     requests = rspecXML.findall('.//request')
513     if requests:
514         # Get all the public keys associate with slice.
515         pubKeys = getKeysForSlice(s.slice_hrn)
516         print sys.stderr, "Passing the following keys to the instance:\n%s" % pubKeys
517     for req in requests:
518         vmTypeElement = req.getparent()
519         instType = vmTypeElement.get('name')
520         numInst  = int(req.find('instances').text)
521         instKernel  = req.find('kernel_image').get('id')
522         instDiskImg = req.find('disk_image').get('id')
523         instKey     = req.find('keypair').text
524         
525         ramDiskElement = req.find('ramdisk')
526         ramDiskAttr    = ramDiskElement.attrib
527         if 'id' in ramDiskAttr:
528             instRamDisk = ramDiskAttr['id']
529         else:
530             instRamDisk = None
531
532         # Create the instances
533         for i in range(0, numInst):
534             eucaInst = EucaInstance(slice = s, 
535                                     kernel_id = instKernel,
536                                     image_id = instDiskImg,
537                                     ramdisk_id = instRamDisk,
538                                     key_pair = instKey,
539                                     inst_type = instType)
540             eucaInst.reserveInstance(conn, pubKeys)
541
542     return True
543
544 def main():
545     init_server()
546
547     #theRSpec = None
548     #with open(sys.argv[1]) as xml:
549     #    theRSpec = xml.read()
550     #create_slice(None, 'planetcloud.pc.test', theRSpec)
551
552     #rspec = get_rspec('euca', 'planetcloud.pc.test', 'planetcloud.pc.marcoy')
553     #print rspec
554     print getKeysForSlice('gc.gc.test1')
555
556 if __name__ == "__main__":
557     main()
558