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