(*) basically no operational change
[nodemanager.git] / sm.py
1 """Sliver manager.
2
3 The sliver manager has several functions.  It is responsible for
4 creating, resource limiting, starting, stopping, and destroying
5 slivers.  It provides an API for users to access these functions and
6 also to make inter-sliver resource loans.  The sliver manager is also
7 responsible for handling delegation accounts.
8 """
9
10 # $Id: sm.py,v 1.28 2007/07/27 18:02:36 dhozac Exp $
11
12 try: from bwlimit import bwmin, bwmax
13 except ImportError: bwmin, bwmax = 8, 1000*1000*1000
14 import accounts
15 import api
16 import database
17 import delegate
18 import logger
19 import sliver_vs
20 import string,re
21
22
23 DEFAULT_ALLOCATION = {
24     'enabled': 1,
25     # CPU parameters
26     'cpu_min': 0, # ms/s
27     'cpu_share': 32, # proportional share
28     # bandwidth parameters
29     'net_min_rate': bwmin / 1000, # kbps
30     'net_max_rate': bwmax / 1000, # kbps
31     'net_share': 1, # proportional share
32     # bandwidth parameters over routes exempt from node bandwidth limits
33     'net_i2_min_rate': bwmin / 1000, # kbps
34     'net_i2_max_rate': bwmax / 1000, # kbps
35     'net_i2_share': 1, # proportional share
36     'net_max_kbyte' : 5662310, #Kbyte
37     'net_thresh_kbyte': 4529848, #Kbyte
38     'net_i2_max_kbyte': 17196646,
39     'net_i2_thresh_kbyte': 13757316,
40     # disk space limit
41     'disk_max': 5000000, # bytes
42     # capabilities
43     'capabilities': '',
44     # IP addresses
45     'ip_addresses': '0.0.0.0',
46
47     # NOTE: this table is further populated with resource names and
48     # default amounts via the start() function below.  This probably
49     # should be changeg and these values should be obtained via the
50     # API to myplc.
51     }
52
53 start_requested = False  # set to True in order to request that all slivers be started
54
55 @database.synchronized
56 def GetSlivers(data, fullupdate=True):
57     """This function has two purposes.  One, convert GetSlivers() data
58     into a more convenient format.  Two, even if no updates are coming
59     in, use the GetSlivers() heartbeat as a cue to scan for expired
60     slivers."""
61
62     logger.verbose("Entering sm:GetSlivers with fullupdate=%r"%fullupdate)
63     for key in data.keys():
64         logger.verbose('GetSlivers key : ' + key)
65
66     node_id = None
67     try:
68         f = open('/etc/planetlab/node_id')
69         try: node_id = int(f.read())
70         finally: f.close()
71     except: logger.log_exc()
72
73     if data.has_key('node_id') and data['node_id'] != node_id: return
74
75     if data.has_key('networks'):
76         for network in data['networks']:
77             if network['is_primary'] and network['bwlimit'] is not None:
78                 DEFAULT_ALLOCATION['net_max_rate'] = network['bwlimit'] / 1000
79
80 ### Emulab-specific hack begins here
81 #    emulabdelegate = {
82 #        'instantiation': 'plc-instantiated',
83 #        'keys': '''ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA5Rimz6osRvlAUcaxe0YNfGsLL4XYBN6H30V3l/0alZOSXbGOgWNdEEdohwbh9E8oYgnpdEs41215UFHpj7EiRudu8Nm9mBI51ARHA6qF6RN+hQxMCB/Pxy08jDDBOGPefINq3VI2DRzxL1QyiTX0jESovrJzHGLxFTB3Zs+Y6CgmXcnI9i9t/zVq6XUAeUWeeXA9ADrKJdav0SxcWSg+B6F1uUcfUd5AHg7RoaccTldy146iF8xvnZw0CfGRCq2+95AU9rbMYS6Vid8Sm+NS+VLaAyJaslzfW+CAVBcywCOlQNbLuvNmL82exzgtl6fVzutRFYLlFDwEM2D2yvg4BQ== root@boss.emulab.net''',
84  #       'name': 'utah_elab_delegate',
85  #       'timestamp': data['timestamp'],
86  #       'type': 'delegate',
87  #       'vref': None
88  #       }
89  #   database.db.deliver_record(emulabdelegate)
90 ### Emulab-specific hack ends here
91
92
93     logger.verbose ('dealing with initscripts')
94     initscripts_by_id = {}
95     for is_rec in data['initscripts']:
96         initscripts_by_id[str(is_rec['initscript_id'])] = is_rec['script']
97
98     for sliver in data['slivers']:
99         logger.verbose("sm:GetSlivers in slivers loop")
100         rec = sliver.copy()
101         rec.setdefault('timestamp', data['timestamp'])
102
103         # convert attributes field to a proper dict
104         attr_dict = {}
105         for attr in rec.pop('attributes'): attr_dict[attr['name']] = attr['value']
106
107         # squash keys
108         keys = rec.pop('keys')
109         rec.setdefault('keys', '\n'.join([key_struct['key'] for key_struct in keys]))
110
111         # Handle nm controller here
112         rec.setdefault('type', attr_dict.get('type', 'sliver.VServer'))
113         if rec['instantiation'] == 'nm-controller':
114         # type isn't returned by GetSlivers() for whatever reason.  We're overloading
115         # instantiation here, but i suppose its the ssame thing when you think about it. -FA
116             rec['type'] = 'delegate'
117
118         rec.setdefault('vref', attr_dict.get('vref', 'default'))
119         is_id = attr_dict.get('plc_initscript_id')
120         if is_id is not None and is_id in initscripts_by_id:
121             rec['initscript'] = initscripts_by_id[is_id]
122         else:
123             rec['initscript'] = ''
124         rec.setdefault('delegations', attr_dict.get("delegations", []))
125
126         # extract the implied rspec
127         rspec = {}
128         rec['rspec'] = rspec
129         for resname, default_amt in DEFAULT_ALLOCATION.iteritems():
130             try:
131                 t = type(default_amt)
132                 amt = t.__new__(t, attr_dict[resname])
133             except (KeyError, ValueError): amt = default_amt
134             rspec[resname] = amt
135
136         database.db.deliver_record(rec)
137     if fullupdate: database.db.set_min_timestamp(data['timestamp'])
138     database.db.sync()
139     accounts.Startingup = False
140
141 def deliver_ticket(data): return GetSlivers(data, fullupdate=False)
142
143
144 def start(options, config):
145     for resname, default_amt in sliver_vs.DEFAULT_ALLOCATION.iteritems():
146         DEFAULT_ALLOCATION[resname]=default_amt
147         
148     accounts.register_class(sliver_vs.Sliver_VS)
149     accounts.register_class(delegate.Delegate)
150     accounts.Startingup = options.startup
151     database.start()
152     api.deliver_ticket = deliver_ticket
153     api.start()