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