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