Simple module for toggling network namespaces based on slice attributes
[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 delegate
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         # Handle nm controller here
101         rec.setdefault('type', attr_dict.get('type', 'sliver.VServer'))
102         if rec['instantiation'] == 'nm-controller':
103         # type isn't returned by GetSlivers() for whatever reason.  We're overloading
104         # instantiation here, but i suppose its the ssame thing when you think about it. -FA
105             rec['type'] = 'delegate'
106
107         # set the vserver reference.  If none, set to default.
108         rec.setdefault('vref', attr_dict.get('vref', 'default'))
109
110         # set initscripts.  first check if exists, if not, leave empty.
111         is_name = attr_dict.get('initscript')
112         if is_name is not None and is_name in initscripts:
113             rec['initscript'] = initscripts[is_name]
114         else:
115             rec['initscript'] = ''
116
117         # set delegations, if none, set empty
118         rec.setdefault('delegations', attr_dict.get("delegations", []))
119
120         # extract the implied rspec
121         rspec = {}
122         rec['rspec'] = rspec
123         for resname, default_amt in DEFAULT_ALLOCATION.iteritems():
124             try:
125                 t = type(default_amt)
126                 amt = t.__new__(t, attr_dict[resname])
127             except (KeyError, ValueError): amt = default_amt
128             rspec[resname] = amt
129
130         database.db.deliver_record(rec)
131     if fullupdate: database.db.set_min_timestamp(data['timestamp'])
132     database.db.sync()
133     accounts.Startingup = False
134
135 def deliver_ticket(data): return GetSlivers(data, fullupdate=False)
136
137
138 def start(options, config):
139     for resname, default_amt in sliver_vs.DEFAULT_ALLOCATION.iteritems():
140         DEFAULT_ALLOCATION[resname]=default_amt
141         
142     accounts.register_class(sliver_vs.Sliver_VS)
143     accounts.register_class(delegate.Delegate)
144     accounts.Startingup = options.startup
145     database.start()
146     api_calls.deliver_ticket = deliver_ticket
147     api.start()