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