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