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