6192ba1cc08cccd35613dce692d71b55c774d530
[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("sm: Entering GetSlivers with fullupdate=%r"%fullupdate)
67     for key in data.keys():
68         logger.verbose('sm: 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("sm: GetSlivers failed to read /etc/planetlab/node_id")
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     if 'initscripts' not in data:
86         logger.log_missing_data("sm.GetSlivers",'initscripts')
87         return
88     initscripts = {}
89     for is_rec in data['initscripts']:
90         logger.verbose("sm: initscript: %s" % is_rec['name'])
91         initscripts[str(is_rec['name'])] = is_rec['script']
92
93     for sliver in data['slivers']:
94         logger.verbose("sm: %s: sm:GetSlivers in slivers loop"%sliver['name'])
95         rec = sliver.copy()
96         rec.setdefault('timestamp', data['timestamp'])
97
98         # convert attributes field to a proper dict
99         attr_dict = {}
100         for attr in rec.pop('attributes'): attr_dict[attr['tagname']] = attr['value']
101         rec.setdefault("attributes", attr_dict)
102
103         # squash keys
104         keys = rec.pop('keys')
105         rec.setdefault('keys', '\n'.join([key_struct['key'] for key_struct in keys]))
106
107         ## 'Type' isn't returned by GetSlivers() for whatever reason.  We're overloading
108         ## instantiation here, but i suppose its the same thing when you think about it. -FA
109         # Handle nm controller here
110         if rec['instantiation'].lower() == 'nm-controller':
111             rec.setdefault('type', attr_dict.get('type', 'controller.Controller'))
112         else:
113             rec.setdefault('type', attr_dict.get('type', 'sliver.VServer'))
114
115         # set the vserver reference.  If none, set to default.
116         rec.setdefault('vref', attr_dict.get('vref', 'default'))
117
118         # set initscripts.  first check if exists, if not, leave empty.
119         is_name = attr_dict.get('initscript')
120         if is_name is not None and is_name in initscripts:
121             rec['initscript'] = initscripts[is_name]
122         else:
123             rec['initscript'] = ''
124
125         # set delegations, if none, set empty
126         rec.setdefault('delegations', attr_dict.get("delegations", []))
127
128         # extract the implied rspec
129         rspec = {}
130         rec['rspec'] = rspec
131         for resname, default_amt in DEFAULT_ALLOCATION.iteritems():
132             try:
133                 t = type(default_amt)
134                 amt = t.__new__(t, attr_dict[resname])
135             except (KeyError, ValueError): amt = default_amt
136             rspec[resname] = amt
137
138         # add in sysctl attributes into the rspec
139         for key in attr_dict.keys():
140             if key.find("sysctl.") == 0:
141                 rspec[key] = attr_dict[key]
142
143         database.db.deliver_record(rec)
144     if fullupdate: database.db.set_min_timestamp(data['timestamp'])
145     # slivers are created here.
146     database.db.sync()
147     accounts.Startingup = False
148
149 def deliver_ticket(data): return GetSlivers(data, fullupdate=False)
150
151
152 def start(options, config):
153     for resname, default_amt in sliver_vs.DEFAULT_ALLOCATION.iteritems():
154         DEFAULT_ALLOCATION[resname]=default_amt
155         
156     accounts.register_class(sliver_vs.Sliver_VS)
157     accounts.register_class(controller.Controller)
158     accounts.Startingup = options.startup
159     database.start()
160     api_calls.deliver_ticket = deliver_ticket
161     api.start()