service stop/start instead of restart in postinstall
[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 database
17 import delegate
18 import logger
19 import sliver_vs
20 import string,re
21
22
23 DEFAULT_ALLOCATION = {
24     'enabled': 1,
25     'whitelist': 1,
26     # CPU parameters
27     'cpu_min': 0, # ms/s
28     'cpu_share': 32, # 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
46     # NOTE: this table is further populated with resource names and
47     # default amounts via the start() function below.  This probably
48     # should be changeg and these values should be obtained via the
49     # API to myplc.
50     }
51
52 start_requested = False  # set to True in order to request that all slivers be started
53
54
55 def whitelistfilter():
56     """creates a regex (re) object based on the slice definitions
57        in /etc/planetlab/whitelist"""
58
59     whitelist = []
60     whitelist_re = re.compile("([a-zA-Z0-9\*]+)_([a-zA-Z0-9\*]+)")
61     linecount = 0
62     try:
63         f = open('/etc/planetlab/whitelist')
64         for line in f.readlines():
65             linecount = linecount+1
66             line = line.strip()
67             # skip comments
68             if len(line)>0 and line[0]=='#':
69                 continue
70             m = whitelist_re.search(line)
71             if m == None:
72                 logger.log("skipping line #%d in /etc/planetlab/whitelist" % linecount)
73                 continue
74             else:
75                 whitelist.append(m.group())
76         f.close()
77     except IOError,e:
78         logger.log("IOError -> %s" % e)
79         logger.log("No whitelist file found; setting slice white list to *_*")
80         whitelist = ["*_*"]
81
82     white_re_list = None
83     for w in whitelist:
84         w = string.replace(w,'*','([a-zA-Z0-9]+)')
85         if white_re_list == None:
86             white_re_list = w
87         else:
88             white_re_list = "(%s)|(%s)" % (white_re_list,w)
89
90     if white_re_list == None:
91         white_re_list = "([a-zA-Z0-9]+)_([a-zA-Z0-9]+)"
92
93     logger.log("whitelist regex = %s" % white_re_list)
94     whitelist_re = re.compile(white_re_list)
95     return whitelist_re
96
97 @database.synchronized
98 def GetSlivers(data, fullupdate=True):
99     """This function has two purposes.  One, convert GetSlivers() data
100     into a more convenient format.  Two, even if no updates are coming
101     in, use the GetSlivers() heartbeat as a cue to scan for expired
102     slivers."""
103
104     node_id = None
105     try:
106         f = open('/etc/planetlab/node_id')
107         try: node_id = int(f.read())
108         finally: f.close()
109     except: logger.log_exc()
110
111     if data.has_key('node_id') and data['node_id'] != node_id: return
112
113     if data.has_key('networks'):
114         for network in data['networks']:
115             if network['is_primary'] and network['bwlimit'] is not None:
116                 DEFAULT_ALLOCATION['net_max_rate'] = network['bwlimit'] / 1000
117
118 ### Emulab-specific hack begins here
119 #    emulabdelegate = {
120 #        'instantiation': 'plc-instantiated',
121 #        'keys': '''ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA5Rimz6osRvlAUcaxe0YNfGsLL4XYBN6H30V3l/0alZOSXbGOgWNdEEdohwbh9E8oYgnpdEs41215UFHpj7EiRudu8Nm9mBI51ARHA6qF6RN+hQxMCB/Pxy08jDDBOGPefINq3VI2DRzxL1QyiTX0jESovrJzHGLxFTB3Zs+Y6CgmXcnI9i9t/zVq6XUAeUWeeXA9ADrKJdav0SxcWSg+B6F1uUcfUd5AHg7RoaccTldy146iF8xvnZw0CfGRCq2+95AU9rbMYS6Vid8Sm+NS+VLaAyJaslzfW+CAVBcywCOlQNbLuvNmL82exzgtl6fVzutRFYLlFDwEM2D2yvg4BQ== root@boss.emulab.net''',
122  #       'name': 'utah_elab_delegate',
123  #       'timestamp': data['timestamp'],
124  #       'type': 'delegate',
125  #       'vref': None
126  #       }
127  #   database.db.deliver_record(emulabdelegate)
128 ### Emulab-specific hack ends here
129
130
131     initscripts_by_id = {}
132     for is_rec in data['initscripts']:
133         initscripts_by_id[str(is_rec['initscript_id'])] = is_rec['script']
134
135     # remove slivers not on the whitelist
136     whitelist_regex = whitelistfilter()
137     
138     for sliver in data['slivers']:
139         rec = sliver.copy()
140         rec.setdefault('timestamp', data['timestamp'])
141
142         # convert attributes field to a proper dict
143         attr_dict = {}
144         for attr in rec.pop('attributes'): attr_dict[attr['name']] = attr['value']
145
146         # squash keys
147         keys = rec.pop('keys')
148         rec.setdefault('keys', '\n'.join([key_struct['key'] for key_struct in keys]))
149
150         # Handle nm controller here
151         rec.setdefault('type', attr_dict.get('type', 'sliver.VServer'))
152         if rec['instantiation'] == 'nm-controller':
153         # type isn't returned by GetSlivers() for whatever reason.  We're overloading
154         # instantiation here, but i suppose its the ssame thing when you think about it. -FA
155             rec['type'] = 'delegate'
156
157         rec.setdefault('vref', attr_dict.get('vref', 'default'))
158         is_id = attr_dict.get('plc_initscript_id')
159         if is_id is not None and is_id in initscripts_by_id:
160             rec['initscript'] = initscripts_by_id[is_id]
161         else:
162             rec['initscript'] = ''
163         rec.setdefault('delegations', attr_dict.get("delegations", []))
164
165         # extract the implied rspec
166         rspec = {}
167         rec['rspec'] = rspec
168         for resname, default_amt in DEFAULT_ALLOCATION.iteritems():
169             try: amt = int(attr_dict[resname])
170             except KeyError: amt = default_amt
171             except ValueError:
172                 if type(default_amt) is type('str'):
173                     amt = attr_dict[resname]
174                 else:
175                     amt = default_amt
176             rspec[resname] = amt
177
178         # disable sliver
179         m = whitelist_regex.search(sliver['name'])
180         if m == None:
181             rspec['whitelist'] = 0
182             rspec['enabled'] = 0
183
184         database.db.deliver_record(rec)
185     if fullupdate: database.db.set_min_timestamp(data['timestamp'])
186     database.db.sync()
187     accounts.Startingup = False
188
189 def deliver_ticket(data): return GetSlivers(data, fullupdate=False)
190
191
192 def start(options, config):
193     for resname, default_amt in sliver_vs.DEFAULT_ALLOCATION.iteritems():
194         DEFAULT_ALLOCATION[resname]=default_amt
195         
196     accounts.register_class(sliver_vs.Sliver_VS)
197     accounts.register_class(delegate.Delegate)
198     accounts.Startingup = options.startup
199     database.start()
200     api.deliver_ticket = deliver_ticket
201     api.start()