053fd717599756926f397932b43da53966b83770
[sfa.git] / sfa / openstack / nova_shell.py
1 import sys
2 import xmlrpclib
3 import socket
4 from urlparse import urlparse
5 from sfa.util.sfalogging import logger
6 try:
7     from nova import db
8     from nova import flags
9     from nova import context
10     from nova.auth.manager import AuthManager
11     from nova.compute.manager import ComputeManager
12     from nova.network.manager import NetworkManager
13     from nova.scheduler.manager import SchedulerManager
14     has_nova = True
15 except:
16     has_nova = False
17
18
19 class NovaDB:
20     """
21     Wraps the nova.db library and injects the context when executing methods 
22     """     
23     def __init__(self, db, context):
24         self.db = db
25         self.context = context
26     
27     def __getattr__(self, name):
28         def func(*args, **kwds):
29             result=getattr(self.db, name)(self.context, *args, **kwds)
30             return result
31         return func
32  
33 class NovaShell:
34     """
35     A simple xmlrpc shell to a myplc instance
36     This class can receive all Openstack calls to the underlying testbed
37     """
38     
39     # dont care about limiting calls yet 
40     direct_calls = []
41     alias_calls = {}
42
43
44     # use the 'capability' auth mechanism for higher performance when the PLC db is local    
45     def __init__ ( self, config ) :
46         url = config.SFA_PLC_URL
47         # try to figure if the url is local
48         is_local=False    
49         hostname=urlparse(url).hostname
50         if hostname == 'localhost': is_local=True
51         # otherwise compare IP addresses; 
52         # this might fail for any number of reasons, so let's harden that
53         try:
54             # xxx todo this seems to result in a DNS request for each incoming request to the AM
55             # should be cached or improved
56             url_ip=socket.gethostbyname(hostname)
57             local_ip=socket.gethostbyname(socket.gethostname())
58             if url_ip==local_ip: is_local=True
59         except:
60             pass
61
62
63         if is_local and has_nova:
64             logger.debug('nova access - native')
65             # load the config
66             flags.FLAGS(['foo', '--flagfile=/etc/nova/nova.conf', 'foo', 'foo'])
67             # instantiate managers 
68             self.auth_manager = AuthManager()
69             self.compute_manager = ComputeManager()
70             self.network_manager = NetworkManager()
71             self.scheduler_manager = SchedulerManager()
72             self.db = NovaDB(db, context.get_admin_context())
73         else:
74             self.auth = None
75             self.proxy = None
76             logger.debug('nova access - REST')
77             raise SfaNotImplemented('nova access - Rest')