Setting tag nodemanager-1.8-39
[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' : 10546875, #Kbyte
38     'net_thresh_kbyte': 9492187, #Kbyte
39     'net_i2_max_kbyte': 31640625,
40     'net_i2_thresh_kbyte': 28476562,
41     # disk space limit
42     'disk_max': 10000000, # 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, config = None, plc=None, 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['tagname']] = attr['value']
95         rec.setdefault("attributes", attr_dict)
96
97         # squash keys
98         keys = rec.pop('keys')
99         rec.setdefault('keys', '\n'.join([key_struct['key'] for key_struct in keys]))
100
101         ## 'Type' isn't returned by GetSlivers() for whatever reason.  We're overloading
102         ## instantiation here, but i suppose its the same thing when you think about it. -FA
103         # Handle nm controller here
104         if rec['instantiation'].lower() == 'nm-controller':
105             rec.setdefault('type', attr_dict.get('type', 'controller.Controller'))
106         else:
107             rec.setdefault('type', attr_dict.get('type', 'sliver.VServer'))
108
109         # set the vserver reference.  If none, set to default.
110         rec.setdefault('vref', attr_dict.get('vref', 'default'))
111
112         # set initscripts.  first check if exists, if not, leave empty.
113         is_name = attr_dict.get('initscript')
114         if is_name is not None and is_name in initscripts:
115             rec['initscript'] = initscripts[is_name]
116         else:
117             rec['initscript'] = ''
118
119         # set delegations, if none, set empty
120         rec.setdefault('delegations', attr_dict.get("delegations", []))
121
122         # extract the implied rspec
123         rspec = {}
124         rec['rspec'] = rspec
125         for resname, default_amt in DEFAULT_ALLOCATION.iteritems():
126             try:
127                 t = type(default_amt)
128                 amt = t.__new__(t, attr_dict[resname])
129             except (KeyError, ValueError): amt = default_amt
130             rspec[resname] = amt
131
132         # add in sysctl attributes into the rspec
133         for key in attr_dict.keys():
134             if key.find("sysctl.") == 0:
135                 rspec[key] = attr_dict[key]
136
137         database.db.deliver_record(rec)
138     if fullupdate: database.db.set_min_timestamp(data['timestamp'])
139     # slivers are created here.
140     database.db.sync()
141     accounts.Startingup = False
142
143 def deliver_ticket(data): return GetSlivers(data, fullupdate=False)
144
145
146 def start(options, config):
147     for resname, default_amt in sliver_vs.DEFAULT_ALLOCATION.iteritems():
148         DEFAULT_ALLOCATION[resname]=default_amt
149         
150     accounts.register_class(sliver_vs.Sliver_VS)
151     accounts.register_class(controller.Controller)
152     accounts.Startingup = options.startup
153     database.start()
154     api_calls.deliver_ticket = deliver_ticket
155     api.start()