Added 'capabilities' slice attr to default set of slice attrs.
[myplc.git] / db-config
1 #!/usr/bin/env /usr/bin/plcsh
2 #
3 # Bootstraps the PLC database with a default administrator account and
4 # a default site, defines default slice attribute types, and
5 # creates/updates default system slices.
6 #
7 # Mark Huang <mlhuang@cs.princeton.edu>
8 # Copyright (C) 2006 The Trustees of Princeton University
9 #
10 # $Id: db-config 7454 2007-12-11 18:55:00Z faiyaza $
11 # $HeadURL$
12
13 from plc_config import PLCConfiguration
14 import sys
15
16 def main():
17     cfg = PLCConfiguration()
18     cfg.load()
19     variables = cfg.variables()
20
21     # Load variables into dictionaries
22     for category_id, (category, variablelist) in variables.iteritems():
23         globals()[category_id] = dict(zip(variablelist.keys(),
24                                        [variable['value'] for variable in variablelist.values()]))
25
26     # Create/update the default administrator account (should be
27     # person_id 2).
28     admin = { 'person_id': 2,
29               'first_name': "Default",
30               'last_name': "Administrator",
31               'email': plc['root_user'],
32               'password': plc['root_password'] }
33     persons = GetPersons([admin['person_id']])
34     if not persons:
35         person_id = AddPerson(admin)
36         if person_id != admin['person_id']:
37             # Huh? Someone deleted the account manually from the database.
38             DeletePerson(person_id)
39             raise Exception, "Someone deleted the \"%s %s\" account from the database!" % \
40                   (admin['first_name'], admin['last_name'])
41         UpdatePerson(person_id, { 'enabled': True })
42     else:
43         person_id = persons[0]['person_id']
44         UpdatePerson(person_id, admin)
45
46     # Create/update the default site (should be site_id 1)
47     if plc_www['port'] == '80':
48         url = "http://" + plc_www['host'] + "/"
49     elif plc_www['port'] == '443':
50         url = "https://" + plc_www['host'] + "/"
51     else:
52         url = "http://" + plc_www['host'] + ":" + plc_www['port'] + "/"
53     site = { 'site_id': 1,
54              'name': plc['name'] + " Central",
55              'abbreviated_name': plc['name'],
56              'login_base': plc['slice_prefix'],
57              'is_public': False,
58              'url': url,
59              'max_slices': 100 }
60
61     sites = GetSites([site['site_id']])
62     if not sites:
63         site_id = AddSite(site['name'], site['abbreviated_name'], site['login_base'], site)
64         if site_id != site['site_id']:
65             DeleteSite(site_id)
66             raise Exception, "Someone deleted the \"%s\" site from the database!" % \
67                   site['name']
68         sites = [site]
69
70     # Must call UpdateSite() even after AddSite() to update max_slices
71     site_id = sites[0]['site_id']
72     UpdateSite(site_id, site)
73
74     # The default administrator account must be associated with a site
75     # in order to login.
76     AddPersonToSite(admin['person_id'], site['site_id'])
77     SetPersonPrimarySite(admin['person_id'], site['site_id'])
78
79     # Grant admin and PI roles to the default administrator account
80     AddRoleToPerson(10, admin['person_id'])
81     AddRoleToPerson(20, admin['person_id'])
82
83     # Setup default PlanetLabConf entries
84     default_conf_files = [
85         # NTP configuration
86         {'enabled': True,
87          'source': 'PlanetLabConf/ntp.conf.php',
88          'dest': '/etc/ntp.conf',
89          'file_permissions': '644',
90          'file_owner': 'root',
91          'file_group': 'root',
92          'preinstall_cmd': '',
93          'postinstall_cmd': '/etc/rc.d/init.d/ntpd restart',
94          'error_cmd': '',
95          'ignore_cmd_errors': False,
96          'always_update': False},
97         {'enabled': True,
98          'source': 'PlanetLabConf/ntp/step-tickers.php',
99          'dest': '/etc/ntp/step-tickers',
100          'file_permissions': '644',
101          'file_owner': 'root',
102          'file_group': 'root',
103          'preinstall_cmd': '',
104          'postinstall_cmd': '/etc/rc.d/init.d/ntpd restart',
105          'error_cmd': '',
106          'ignore_cmd_errors': False,
107          'always_update': False},
108
109         # SSH server configuration
110         {'enabled': True,
111          'source': 'PlanetLabConf/sshd_config',
112          'dest': '/etc/ssh/sshd_config',
113          'file_permissions': '600',
114          'file_owner': 'root',
115          'file_group': 'root',
116          'preinstall_cmd': '',
117          'postinstall_cmd': '/etc/init.d/sshd restart',
118          'error_cmd': '',
119          'ignore_cmd_errors': False,
120          'always_update': False},
121
122         # Administrative SSH keys
123         {'enabled': True,
124          'source': 'PlanetLabConf/keys.php?root',
125          'dest': '/root/.ssh/authorized_keys',
126          'file_permissions': '644',
127          'file_owner': 'root',
128          'file_group': 'root',
129          'preinstall_cmd': '',
130          'postinstall_cmd': '/bin/chmod 700 /root/.ssh',
131          'error_cmd': '',
132          'ignore_cmd_errors': False,
133          'always_update': False},
134         {'enabled': True,
135          'source': 'PlanetLabConf/keys.php?site_admin',
136          'dest': '/home/site_admin/.ssh/authorized_keys',
137          'file_permissions': '644',
138          'file_owner': 'site_admin',
139          'file_group': 'site_admin',
140          'preinstall_cmd': 'grep -q site_admin /etc/passwd',
141          'postinstall_cmd': '/bin/chmod 700 /home/site_admin/.ssh',
142          'error_cmd': '',
143          'ignore_cmd_errors': False,
144          'always_update': False},
145         # Log rotation configuration
146         {'enabled': True,
147          'source': 'PlanetLabConf/logrotate.conf',
148          'dest': '/etc/logrotate.conf',
149          'file_permissions': '644',
150          'file_owner': 'root',
151          'file_group': 'root',
152          'preinstall_cmd': '',
153          'postinstall_cmd': '',
154          'error_cmd': '',
155          'ignore_cmd_errors': False,
156          'always_update': False},
157
158         # updatedb/locate nightly cron job
159         {'enabled': True,
160          'source': 'PlanetLabConf/slocate.cron',
161          'dest': '/etc/cron.daily/slocate.cron',
162          'file_permissions': '755',
163          'file_owner': 'root',
164          'file_group': 'root',
165          'preinstall_cmd': '',
166          'postinstall_cmd': '',
167          'error_cmd': '',
168          'ignore_cmd_errors': False,
169          'always_update': False},
170
171         # YUM configuration
172         {'enabled': True,
173          'source': 'PlanetLabConf/yum.conf.php?gpgcheck=1',
174          'dest': '/etc/yum.conf',
175          'file_permissions': '644',
176          'file_owner': 'root',
177          'file_group': 'root',
178          'preinstall_cmd': '',
179          'postinstall_cmd': '',
180          'error_cmd': '',
181          'ignore_cmd_errors': False,
182          'always_update': False},
183         {'enabled': True,
184          'source': 'PlanetLabConf/delete-rpm-list-production',
185          'dest': '/etc/planetlab/delete-rpm-list',
186          'file_permissions': '644',
187          'file_owner': 'root',
188          'file_group': 'root',
189          'preinstall_cmd': '',
190          'postinstall_cmd': '',
191          'error_cmd': '',
192          'ignore_cmd_errors': False,
193          'always_update': False},
194
195         # PLC configuration
196         {'enabled': True,
197          'source': 'PlanetLabConf/get_plc_config.php',
198          'dest': '/etc/planetlab/plc_config',
199          'file_permissions': '644',
200          'file_owner': 'root',
201          'file_group': 'root',
202          'preinstall_cmd': '',
203          'postinstall_cmd': '',
204          'error_cmd': '',
205          'ignore_cmd_errors': False,
206          'always_update': False},
207         {'enabled': True,
208          'source': 'PlanetLabConf/get_plc_config.php?python',
209          'dest': '/etc/planetlab/plc_config.py',
210          'file_permissions': '644',
211          'file_owner': 'root',
212          'file_group': 'root',
213          'preinstall_cmd': '',
214          'postinstall_cmd': '',
215          'error_cmd': '',
216          'ignore_cmd_errors': False,
217          'always_update': False},
218         {'enabled': True,
219          'source': 'PlanetLabConf/get_plc_config.php?perl',
220          'dest': '/etc/planetlab/plc_config.pl',
221          'file_permissions': '644',
222          'file_owner': 'root',
223          'file_group': 'root',
224          'preinstall_cmd': '',
225          'postinstall_cmd': '',
226          'error_cmd': '',
227          'ignore_cmd_errors': False,
228          'always_update': False},
229         {'enabled': True,
230          'source': 'PlanetLabConf/get_plc_config.php?php',
231          'dest': '/etc/planetlab/php/plc_config.php',
232          'file_permissions': '644',
233          'file_owner': 'root',
234          'file_group': 'root',
235          'preinstall_cmd': '',
236          'postinstall_cmd': '',
237          'error_cmd': '',
238          'ignore_cmd_errors': False,
239          'always_update': False},
240
241         # XXX Required for old Node Manager
242         # Proper configuration
243         {'enabled': True,
244          'source': 'PlanetLabConf/propd.conf',
245          'dest': '/etc/proper/propd.conf',
246          'file_permissions': '644',
247          'file_owner': 'root',
248          'file_group': 'root',
249          'preinstall_cmd': '',
250          'postinstall_cmd': '/etc/init.d/proper restart',
251          'error_cmd': '',
252          'ignore_cmd_errors': True,
253          'always_update': False},
254
255         # XXX Required for old Node Manager
256         # Bandwidth cap
257         {'enabled': True,
258          'source': 'PlanetLabConf/bwlimit.php',
259          'dest': '/etc/planetlab/bwcap',
260          'file_permissions': '644',
261          'file_owner': 'root',
262          'file_group': 'root',
263          'preinstall_cmd': '',
264          'postinstall_cmd': '',
265          'error_cmd': '',
266          'ignore_cmd_errors': True,
267          'always_update': False},
268
269         # Proxy ARP setup
270         {'enabled': True,
271          'source': 'PlanetLabConf/proxies.php',
272          'dest': '/etc/planetlab/proxies',
273          'file_permissions': '644',
274          'file_owner': 'root',
275          'file_group': 'root',
276          'preinstall_cmd': '',
277          'postinstall_cmd': '',
278          'error_cmd': '',
279          'ignore_cmd_errors': False,
280          'always_update': False},
281
282         # Firewall configuration
283         {'enabled': True,
284          'source': 'PlanetLabConf/iptables',
285          'dest': '/etc/sysconfig/iptables',
286          'file_permissions': '600',
287          'file_owner': 'root',
288          'file_group': 'root',
289          'preinstall_cmd': '',
290          'postinstall_cmd': '',
291          'error_cmd': '',
292          'ignore_cmd_errors': False,
293          'always_update': False},
294         {'enabled': True,
295          'source': 'PlanetLabConf/blacklist.php',
296          'dest': '/etc/planetlab/blacklist',
297          'file_permissions': '600',
298          'file_owner': 'root',
299          'file_group': 'root',
300          'preinstall_cmd': '',
301          'postinstall_cmd': '/sbin/iptables-restore --noflush < /etc/planetlab/blacklist',
302          'error_cmd': '',
303          'ignore_cmd_errors': True,
304          'always_update': False},
305
306         # /etc/issue
307         {'enabled': True,
308          'source': 'PlanetLabConf/issue.php',
309          'dest': '/etc/issue',
310          'file_permissions': '644',
311          'file_owner': 'root',
312          'file_group': 'root',
313          'preinstall_cmd': '',
314          'postinstall_cmd': '',
315          'error_cmd': '',
316          'ignore_cmd_errors': False,
317          'always_update': False},
318
319         # Kernel parameters
320         {'enabled': True,
321          'source': 'PlanetLabConf/sysctl.php',
322          'dest': '/etc/sysctl.conf',
323          'file_permissions': '644',
324          'file_owner': 'root',
325          'file_group': 'root',
326          'preinstall_cmd': '',
327          'postinstall_cmd': '/sbin/sysctl -e -p /etc/sysctl.conf',
328          'error_cmd': '',
329          'ignore_cmd_errors': False,
330          'always_update': False},
331
332         # Sendmail configuration
333         {'enabled': True,
334          'source': 'PlanetLabConf/sendmail.mc',
335          'dest': '/etc/mail/sendmail.mc',
336          'file_permissions': '644',
337          'file_owner': 'root',
338          'file_group': 'root',
339          'preinstall_cmd': '',
340          'postinstall_cmd': '',
341          'error_cmd': '',
342          'ignore_cmd_errors': False,
343          'always_update': False},
344         {'enabled': True,
345          'source': 'PlanetLabConf/sendmail.cf',
346          'dest': '/etc/mail/sendmail.cf',
347          'file_permissions': '644',
348          'file_owner': 'root',
349          'file_group': 'root',
350          'preinstall_cmd': '',
351          'postinstall_cmd': 'service sendmail restart',
352          'error_cmd': '',
353          'ignore_cmd_errors': False,
354          'always_update': False},
355
356         # GPG signing keys
357         {'enabled': True,
358          'source': 'PlanetLabConf/RPM-GPG-KEY-fedora',
359          'dest': '/etc/pki/rpm-gpg/RPM-GPG-KEY-fedora',
360          'file_permissions': '644',
361          'file_owner': 'root',
362          'file_group': 'root',
363          'preinstall_cmd': '',
364          'postinstall_cmd': 'rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-fedora',
365          'error_cmd': '',
366          'ignore_cmd_errors': False,
367          'always_update': False},
368         {'enabled': True,
369          'source': 'PlanetLabConf/get_gpg_key.php',
370          'dest': '/etc/pki/rpm-gpg/RPM-GPG-KEY-planetlab',
371          'file_permissions': '644',
372          'file_owner': 'root',
373          'file_group': 'root',
374          'preinstall_cmd': '',
375          'postinstall_cmd': 'rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-planetlab',
376          'error_cmd': '',
377          'ignore_cmd_errors': False,
378          'always_update': False},
379
380         # Ping of death configuration
381         # the 'restart' postcommand doesn't work, b/c the pod script doesn't support it.
382         {'enabled': True,
383          'source': 'PlanetLabConf/ipod.conf.php',
384          'dest': '/etc/ipod.conf',
385          'file_permissions': '644',
386          'file_owner': 'root',
387          'file_group': 'root',
388          'preinstall_cmd': '',
389          'postinstall_cmd': '/etc/init.d/pod start',
390          'error_cmd': '',
391          'ignore_cmd_errors': False,
392          'always_update': False},
393
394         # sudo configuration
395         {'enabled': True,
396          'source': 'PlanetLabConf/sudoers',
397          'dest': '/etc/sudoers',
398          'file_permissions': '440',
399          'file_owner': 'root',
400          'file_group': 'root',
401          'preinstall_cmd': '',
402          'postinstall_cmd': '/usr/sbin/visudo -c',
403          'error_cmd': '',
404          'ignore_cmd_errors': False,
405          'always_update': False}
406         ]
407
408     # Get list of existing (enabled, global) files
409     conf_files = GetConfFiles()
410     conf_files = filter(lambda conf_file: conf_file['enabled'] and \
411                                           not conf_file['node_ids'] and \
412                                           not conf_file['nodegroup_ids'],
413                         conf_files)
414     dests = [conf_file['dest'] for conf_file in conf_files]
415     conf_files = dict(zip(dests, conf_files))
416
417     # Create/update default PlanetLabConf entries
418     for default_conf_file in default_conf_files:
419         if default_conf_file['dest'] not in dests:
420             AddConfFile(default_conf_file)
421         else:
422             conf_file = conf_files[default_conf_file['dest']]
423             UpdateConfFile(conf_file['conf_file_id'], default_conf_file)
424
425     # Setup default slice attribute types
426     default_attribute_types = [
427         # Slice type (only vserver is supported)
428         {'name': "type",
429          'description': "Type of slice (e.g. vserver)",
430          'min_role_id': 20},
431
432         # System slice
433         {'name': "system",
434          'description': "Is a default system slice (1) or not (0 or unset)",
435          'min_role_id': 10},
436
437         # Slice enabled (1) or suspended (0)
438         {'name': "enabled",
439          'description': "Slice enabled (1 or unset) or suspended (0)",
440          'min_role_id': 10},
441
442         # Slice reference image
443         {'name': "vref",
444          'description': "Reference image",
445          'min_role_id': 30},
446
447         # Slice initialization script
448         {'name': "initscript",
449          'description': "Slice initialization script",
450          'min_role_id': 10},
451
452         # CPU share
453         {'name': "cpu_pct",
454          'description': "Reserved CPU percent",
455          'min_role_id': 10},
456         {'name': "cpu_share",
457          'description': "Number of CPU shares",
458          'min_role_id': 10},
459
460         # Bandwidth limits
461         {'name': "net_min_rate",
462          'description': "Minimum bandwidth (kbps)",
463          'min_role_id': 10},
464         {'name': "net_max_rate",
465          'description': "Maximum bandwidth (kbps)",
466          'min_role_id': 10},
467         {'name': "net_i2_min_rate",
468          'description': "Minimum bandwidth over I2 routes (kbps)",
469          'min_role_id': 10},
470         {'name': "net_i2_max_rate",
471          'description': "Maximum bandwidth over I2 routes (kbps)",
472          'min_role_id': 10},
473         {'name': "net_max_kbyte",
474          'description': "Maximum daily network Tx KByte limit.",
475          'min_role_id': 10},
476         {'name': "net_thresh_kbyte",
477          'description': "KByte limit before warning and throttling.",
478          'min_role_id': 10},
479         {'name': "net_i2_max_kbyte",
480          'description': "Maximum daily network Tx KByte limit to I2 hosts.",
481          'min_role_id': 10},
482         {'name': "net_i2_thresh_kbyte",
483          'description': "KByte limit to I2 hosts before warning and throttling.",
484          'min_role_id': 10},
485         {'name': "net_share",
486          'description': "Number of bandwidth shares",
487          'min_role_id': 10},
488         {'name': "net_i2_share",
489          'description': "Number of bandwidth shares over I2 routes",
490          'min_role_id': 10},
491  
492         # Disk quota
493         {'name': "disk_max",
494          'description': "Disk quota (1k disk blocks)",
495          'min_role_id': 10},
496
497         # Proper operations
498         {'name': "proper_op",
499          'description': "Proper operation (e.g. bind_socket)",
500          'min_role_id': 10},
501
502         # VServer capabilities 
503         {'name': "capabilities",
504          'description': "VServer bcapabilities (separate by commas)",
505          'min_role_id': 10},
506
507                 # Vsys
508         {'name': "vsys",
509          'description': "Bind vsys script fd's to a slice's vsys directory.",
510          'min_role_id': 10}
511  
512         ]
513
514     # Get list of existing attribute types
515     attribute_types = GetSliceAttributeTypes()
516     attribute_types = [attribute_type['name'] for attribute_type in attribute_types]
517
518     # Create/update default slice attribute types
519     for default_attribute_type in default_attribute_types:
520         if default_attribute_type['name'] not in attribute_types:
521             AddSliceAttributeType(default_attribute_type)
522         else:
523             UpdateSliceAttributeType(default_attribute_type['name'], default_attribute_type)
524
525     # Default Initscripts
526     default_initscripts = [
527         # Sirius 
528         {'enabled': True, 
529          'name': plc['slice_prefix'] + "_sirius", 
530          'script': '#!/usr/bin/python\n\n"""The Sirius Calendar Service.\n\nThis Python program runs on each node.  It periodically downloads the schedule file and uses NodeManager\'s XML-RPC interface to adjust the priority increase.\n\nAuthor: David Eisenstat (deisenst@cs.princeton.edu)\n\nOriginal Sirius implementation by David Lowenthal.\n"""\n\nimport fcntl\nimport os\nimport random\nimport signal\nimport socket\nimport sys\nimport threading\nimport time\nimport traceback\nimport urllib\nfrom xmlrpclib import ServerProxy\n\n\n# 0 means normal operation\n# 1 means turn on the short time scales and read the schedule from a file\n# 2 means additionally don\'t contact NodeManager\n\nDEBUGLEVEL = 0\n\n########################################\n\nif DEBUGLEVEL < 2:\n    LOGFILE = \'/var/log/sirius\'\nelse:\n    LOGFILE = \'log.txt\'\n\nloglock = threading.Lock()\n\n\ndef log(msg):\n    """Append <msg> and a timestamp to <LOGFILE>."""\n    try:\n        if not msg.endswith(\'\\n\'):\n            msg += \'\\n\'\n        loglock.acquire()\n        try:\n            logfile = open(LOGFILE, \'a\')\n            t = time.time()\n            print >>logfile, t\n            print >>logfile, time.asctime(time.gmtime(t))\n            print >>logfile, msg\n        finally:\n            loglock.release()\n    except:\n        if DEBUGLEVEL > 0:\n            traceback.print_exc()\n\n\ndef logexception():\n    """Log an exception."""\n    log(traceback.format_exc())\n\n########################################\n\nif DEBUGLEVEL > 0:\n    # smaller time units so we can test faster\n    ONEMINUTE = 1\n    ONEHOUR = 10 * ONEMINUTE\nelse:\n    ONEMINUTE = 60\n    ONEHOUR = 60 * ONEMINUTE\n\n\nclass Periodic:\n    """Periodically make a function call."""\n\n    def __init__(self, target, interval, mindelta, maxdelta):\n        self._target = target\n        self._interval = interval\n        self._deltarange = mindelta, maxdelta+1\n        thr = threading.Thread(target=self.run, args=[target])\n        thr.setDaemon(True)\n        thr.start()\n\n    def run(self, target):\n        nextintervalstart = int(time.time() / self._interval) * self._interval\n        while True:\n            try:\n                self._target()\n            except:\n                logexception()\n            nextintervalstart += self._interval\n            nextfiring = nextintervalstart + random.randrange(*self._deltarange)\n            while True:\n                t = time.time()\n                if t < nextfiring:\n                    try:\n                        time.sleep(nextfiring - t)\n                    except:\n                        logexception()\n                else:\n                    break\n\n########################################\n\nSLOTDURATION = ONEHOUR\n\nSCHEDULEURL = \'' + site['url'] + '/planetlab/sirius/schedule.txt\'\n\nschedulelock = threading.Lock()\n\nschedule = {}\n\n\ndef currentslot():\n    return int(time.time() / SLOTDURATION) * SLOTDURATION\n\n\ndef updateschedule():\n    """Make one attempt at downloading and updating the schedule."""\n    log(\'Contacting PLC...\')\n    newschedule = {}\n    # Format is:\n    # timestamp\n    # slicename - starttime - -\n    # ...\n    if DEBUGLEVEL > 0:\n        f = open(\'/tmp/schedule.txt\')\n    else:\n        f = urllib.urlopen(SCHEDULEURL)\n    for line in f:\n        fields = line.split()\n        if len(fields) >= 3:\n            newschedule[fields[2]] = fields[0]\n    log(\'Current schedule is %s\' % newschedule)\n\n    schedulelock.acquire()\n    try:\n        schedule.clear()\n        schedule.update(newschedule)\n    finally:\n        schedulelock.release()\n    log(\'Updated schedule successfully\')\n\n########################################\n\nnodemanager = ServerProxy(\'http://127.0.0.1:812/\')\n\nrecipientcond = threading.Condition()\n\nrecipient = \'\'\nversionnumber = 0\n\ndef updateloans():\n    log(\'Contacting NodeManager...\')\n    schedulelock.acquire()\n    try:\n        newrecipient = schedule.get(str(currentslot()), \'\')\n    finally:\n        schedulelock.release()\n    if newrecipient:\n        loans = [(newrecipient, \'cpu_pct\', 25), (newrecipient, \'net_min_rate\', 2000)]\n    else:\n        loans = []\n    log(\'Current loans are %s\' % loans)\n\n    if DEBUGLEVEL < 2:\n        nodemanager.SetLoans(\'' + plc['slice_prefix'] + '_sirius\', loans)\n    log(\'Updated loans successfully\')\n\n    recipientcond.acquire()\n    try:\n        global recipient, versionnumber\n        if recipient != newrecipient:\n            recipient = newrecipient\n            versionnumber += 1\n            recipientcond.notifyAll()\n    finally:\n        recipientcond.release()\n\n########################################\n\nbackoff = 1\n\ndef success():\n    global backoff\n    backoff = 1\n\ndef failure():\n    global backoff\n    try:\n        time.sleep(backoff)\n    except:\n        logexception()\n    backoff = min(backoff*2, 5*ONEMINUTE)\n\n\ndef handleclient(clientsock, clientaddress):\n    try:\n        log(\'Connection from %s:%d\' % clientaddress)\n        clientsock.shutdown(socket.SHUT_RD)\n        recipientcond.acquire()\n        while True:\n            recip, vn = recipient, versionnumber\n            recipientcond.release()\n            clientsock.send(recip + \'\\n\')\n\n            recipientcond.acquire()\n            while versionnumber == vn:\n                recipientcond.wait()\n    except:\n        logexception()\n\n\ndef server():\n    while True:\n        try:\n            sock = socket.socket()\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n            sock.bind((\'\', 8124))\n            sock.listen(5)\n            success()\n            break\n        except:\n            logexception()\n            failure()\n    log(\'Bound server socket\')\n\n    while True:\n        try:\n            client = sock.accept()\n            threading.Thread(target=handleclient, args=client).start()\n            success()\n        except:\n            logexception()\n            failure()\n\n########################################\n\nif DEBUGLEVEL < 2:\n    PIDFILE = \'/tmp/sirius.pid\'\nelse:\n    PIDFILE = \'sirius.pid\'\n\ntry:\n    if os.fork():\n        sys.exit(0)\n    f = open(PIDFILE, \'w\')\n    fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)\nexcept:\n    logexception()\n    sys.exit(1)\n\nPeriodic(updateschedule, SLOTDURATION, -5*ONEMINUTE, -1*ONEMINUTE)\nPeriodic(updateloans, 5*ONEMINUTE, 0, 0)\nserver()\n'}]
531     
532     # Get list of existing initscripts
533     oldinitscripts = GetInitScripts()
534     oldinitscripts = [script['name'] for script in oldinitscripts]
535
536     for initscript in default_initscripts:
537         if initscript['name'] not in oldinitscripts:  AddInitScript(initscript)
538
539     # Setup default slice attribute types
540     default_setting_types = [
541
542         {'category' : "general",
543          'name' : "ifname",
544          'description': "Set interface name, instead of eth0 or the like",
545          'min_role_id' : 40},
546         {'category' : "general",
547          'name' : "driver",
548          'description': "Use this to specify an alternate driver",
549          'min_role_id' : 40 },
550         {'category' : "general",
551          'name' : "alias",
552          'description': "Allows to reuse an interface as eth0:alias",
553          'min_role_id' : 40},
554
555         {'category' : "hidden",
556          'name' : "backdoor",
557          'description': "For testing new settings",
558          'min_role_id' : 10},
559         ] + [
560         { "category" : "WiFi",
561           "name" : x,
562           "description" : "802.11 %s -- see %s"%(y,z),
563           "min_role_id" : 40 } for (x,y,z) in [
564             ("mode","Mode","iwconfig"),
565             ("essid","ESSID","iwconfig"),
566             ("nw","Network Id","iwconfig"),
567             ("freq","Frequency","iwconfig"),
568             ("channel","Channel","iwconfig"),
569             ("sens","sensitivity threshold","iwconfig"),
570             ("rate","Rate","iwconfig"),
571             ("key","key","iwconfig key"),
572             ("key1","key1","iwconfig key [1]"),
573             ("key2","key2","iwconfig key [2]"),
574             ("key3","key3","iwconfig key [3]"),
575             ("key4","key4","iwconfig key [4]"),
576             ("securitymode","Security mode","iwconfig enc"),
577             ("iwconfig","Additional parameters to iwconfig","ifup-wireless"),
578             ("iwpriv","Additional parameters to iwpriv","ifup-wireless"),
579             ]
580         ]
581
582
583     # Get list of existing attribute types
584     setting_types = GetNodeNetworkSettingTypes()
585     setting_types = [setting_type['name'] for setting_type in setting_types]
586
587     # Create/update default slice setting types
588     for default_setting_type in default_setting_types:
589         if default_setting_type['name'] not in setting_types:
590             AddNodeNetworkSettingType(default_setting_type)
591         else:
592             UpdateNodeNetworkSettingType(default_setting_type['name'], default_setting_type)
593
594     # Create/update system slices
595     default_slices = [
596          # PlanetFlow
597         {'name': plc['slice_prefix'] + "_netflow",
598          'description': "PlanetFlow Traffic Auditing Service",
599          'url': url,
600          'instantiation': "plc-instantiated",
601          # Renew forever (minus one day, work around date conversion weirdness)
602          'expires': sys.maxint - (60 * 60 * 24),
603          'attributes': [('system', "1"),
604                         ('vref', "planetflow"),
605                         ('proper_op', "open file=/etc/passwd, flags=r"),
606                         ('proper_op', "create_socket"),
607                         ('proper_op', "bind_socket")]},
608           # Sirius
609         {'name': plc['slice_prefix'] + "_sirius",
610          'description': 'The Sirius Calendar Service.\n\nSirius provides system-wide reservations of 25% CPU and 2Mb/s outgoing\nbandwidth.  Sign up for hour-long slots using the Web GUI at the\nPlanetLab website.\n\nThis slice should not generate traffic external to PlanetLab.\n',
611          'url': url,
612          'instantiation': "plc-instantiated",
613          # Renew forever (minus one day, work around date conversion weirdness)
614          'expires': sys.maxint - (60 * 60 * 24),
615          'attributes': [('system', "1"),
616                         ('net_min_rate', "2000"),
617                         ('cpu_pct', "25"),
618                         ('initscript', plc['slice_prefix'] + "_sirius")]}
619         ]
620     
621     for default_slice in default_slices:
622         slices = GetSlices([default_slice['name']])
623         if slices:
624             slice = slices[0]
625             UpdateSlice(slice['slice_id'], default_slice)
626         else:
627             AddSlice(default_slice)
628             slice = GetSlices([default_slice['name']])[0]
629
630         # Create/update all attributes
631         slice_attributes = []
632         if slice['slice_attribute_ids']:
633             # Delete unknown attributes
634             for slice_attribute in GetSliceAttributes(slice['slice_attribute_ids']):
635                 if (slice_attribute['name'], slice_attribute['value']) \
636                    not in default_slice['attributes']:
637                     DeleteSliceAttribute(slice_attribute['slice_attribute_id'])
638                 else:
639                     slice_attributes.append((slice_attribute['name'], slice_attribute['value']))
640
641         for (name, value) in default_slice['attributes']:
642             if (name, value) not in slice_attributes:
643                 AddSliceAttribute(slice['name'], name, value)
644
645     installfailed = """
646 Once the node meets these requirements, please reinitiate the install
647 by visiting:
648
649 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/nodes/?id=%(node_id)d
650
651 Update the BootState to 'Reinstall', then reboot the node.
652
653 If you have already performed this step and are still receiving this
654 message, please reply so that we may investigate the problem.
655 """
656
657     # Load default message templates
658     message_templates = [
659         {'message_id': 'Verify account',
660          'subject': "Verify account registration",
661          'template': """
662 Please verify that you registered for a %(PLC_NAME)s account with the
663 username %(email)s by visiting:
664
665 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/persons/register.php?id=%(person_id)d&key=%(verification_key)s
666
667 If you did not register for a %(PLC_NAME)s account, please ignore this
668 message, or contact %(PLC_NAME)s Support <%(PLC_MAIL_SUPPORT_ADDRESS)s>.
669 """
670          },
671
672         {'message_id': 'New PI account',
673          'subject': "New PI account registration from %(first_name)s %(last_name)s <%(email)s> at %(site_name)s",
674          'template': """
675 %(first_name)s %(last_name)s <%(email)s> has signed up for a new
676 %(PLC_NAME)s account at %(site_name)s and has requested a PI role. PIs
677 are responsible for enabling user accounts, creating slices, and
678 ensuring that all users abide by the %(PLC_NAME)s Acceptable Use
679 Policy.
680
681 Only %(PLC_NAME)s administrators may enable new PI accounts. If you
682 are a PI at %(site_name)s, please respond and indicate whether this
683 registration is acceptable.
684
685 To view the request, visit:
686
687 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/persons/index.php?id=%(person_id)d
688 """
689          },
690
691         {'message_id': 'New account',
692          'subject': "New account registration from %(first_name)s %(last_name)s <%(email)s> at %(site_name)s",
693          'template': """
694 %(first_name)s %(last_name)s <%(email)s> has signed up for a new
695 %(PLC_NAME)s account at %(site_name)s and has requested the following
696 roles: %(roles)s.
697
698 To deny the request or enable the account, visit:
699
700 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/persons/index.php?id=%(person_id)d
701 """
702          },
703
704         {'message_id': 'Password reset requested',
705          'subject': "Password reset requested",
706          'template': """
707 Someone has requested that the password of your %(PLC_NAME)s account
708 %(email)s be reset. If this person was you, you may continue with the
709 reset by visiting:
710
711 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/persons/reset_password.php?id=%(person_id)d&key=%(verification_key)s
712
713 If you did not request that your password be reset, please contact
714 %(PLC_NAME)s Support <%(PLC_MAIL_SUPPORT_ADDRESS)s>. Do not quote or
715 otherwise include any of this text in any correspondence.
716 """
717          },
718
719         {'message_id': 'Password reset',
720          'subject': "Password reset",
721          'template': """
722 The password of your %(PLC_NAME)s account %(email)s has been
723 temporarily reset to:
724
725 %(password)s
726
727 Please change it at as soon as possible by visiting:
728
729 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/persons/index.php?id=%(person_id)d
730
731 If you did not request that your password be reset, please contact
732 %(PLC_NAME)s Support <%(PLC_MAIL_SUPPORT_ADDRESS)s>. Do not quote or
733 otherwise include any of this text in any correspondence.
734 """
735          },
736
737         # Boot Manager messages
738         {'message_id': "installfinished",
739          'subject': "%(hostname)s completed installation",
740          'template': """
741 %(hostname)s just completed installation.
742
743 The node should be usable in a couple of minutes if installation was
744 successful.
745 """
746          },
747
748         {'message_id': "insufficientdisk",
749          'subject': "%(hostname)s does not have sufficient disk space",
750          'template': """
751 %(hostname)s failed to boot because it does not have sufficent disk
752 space, or because its disk controller was not recognized.
753
754 Please replace the current disk or disk controller or install
755 additional disks to meet the current hardware requirements.
756 """ + installfailed
757          },
758
759         {'message_id': "insufficientmemory",
760          'subject': "%(hostname)s does not have sufficient memory",
761          'template': """
762 %(hostname)s failed to boot because it does not have sufficent
763 memory.
764
765 Please install additional memory to meet the current hardware
766 requirements.
767 """ + installfailed
768          },
769
770         {'message_id': "authfail",
771          'subject': "%(hostname)s failed to authenticate",
772          'template':
773 """
774 %(hostname)s failed to authenticate for the following reason:
775
776 %(fault)s
777
778 The most common reason for authentication failure is that the
779 authentication key stored in the node configuration file, does not
780 match the key on record. 
781
782 There are two possible steps to resolve the problem.
783
784 1. If you have used an All-in-one BootCD that includes the plnode.txt file,
785     then please check your machine for any old boot media, either in the
786     floppy drive, or on a USB stick.  It is likely that an old configuration
787     is being used instead of the new configuration stored on the BootCD.
788 Or, 
789 2. If you are using Generic BootCD image, then regenerate the node 
790     configuration file by visiting:
791
792     https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/nodes/?id=%(node_id)d
793
794     Under 'Download', follow the 'Download plnode.txt file for %(hostname)s'
795     option, and save the downloaded file as plnode.txt on either a floppy 
796     disk or a USB flash drive.  Be sure the 'Boot State' is set to 'Boot', 
797     and, then reboot the node.
798
799 If you have already performed this step and are still receiving this
800 message, please reply so that we can help investigate the problem.
801 """
802          },
803
804         {'message_id': "notinstalled",
805          'subject': "%(hostname)s is not installed",
806          'template':
807 """
808 %(hostname)s failed to boot because it has either never been
809 installed, or the installation is corrupt.
810
811 Please check if the hard drive has failed, and replace it if so. After
812 doing so, visit:
813
814 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/nodes/?id=%(node_id)d
815
816 Change the 'Boot State' to 'Reinstall', and then reboot the node.
817
818 If you have already performed this step and are still receiving this
819 message, please reply so that we may investigate the problem.
820 """
821          },
822
823         {'message_id': "hostnamenotresolve",
824          'subject': "%(hostname)s does not resolve",
825          'template':
826 """
827 %(hostname)s failed to boot because its hostname does not resolve, or
828 does resolve but does not match its configured IP address.
829
830 Please check the network settings for the node, especially its
831 hostname, IP address, and DNS servers, by visiting:
832
833 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/nodes/?id=%(node_id)d
834
835 Correct any errors, and change the 'Boot State' to 'Reinstall', and then
836 reboot the node.
837
838 If you have already performed this step and are still receiving this
839 message, please reply so that we may investigate the problem.
840 """
841          },
842
843         # XXX N.B. I don't think these are necessary, since there's no
844         # way that the Boot Manager would even be able to contact the
845         # API to send these messages.
846
847         {'message_id': "noconfig",
848          'subject': "%(hostname)s does not have a configuration file",
849          'template': """
850 %(hostname)s failed to boot because it could not find a PlanetLab
851 configuration file. To create this file, visit:
852
853 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/nodes/?id=%(node_id)d
854
855 Click the Configuration File link, and save the downloaded file as
856 plnode.txt on either a floppy disk or a USB flash drive.  Change the 
857 'Boot State' to 'Reinstall', and then reboot the node.
858
859 If you have already performed this step and are still receiving this
860 message, please reply so that we may investigate the problem.
861 """
862          },
863
864         {'message_id': "nodetectednetwork",
865          'subject': "%(hostname)s has unsupported network hardware",
866          'template':
867 """
868
869 %(hostname)s failed to boot because it has network hardware that is
870 unsupported by the current production kernel. If it has booted
871 successfully in the past, please try re-installing it by visiting:
872
873 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/nodes/?id=%(node_id)d
874
875 Change the 'Boot State' to 'Reinstall', and then reboot the node.
876
877 If you have already performed this step and are still receiving this
878 message, please reply so that we may investigate the problem.
879 """
880          },
881         ]
882
883     for template in message_templates:
884         messages = GetMessages([template['message_id']])
885         if not messages:
886             AddMessage(template)
887
888     
889     ### Setup Initial PCU information
890     pcu_types = [{'model': 'AP79xx',
891           'name': 'APC AP79xx',
892           'pcu_protocol_types': [{ 'port': 80,
893                                   'protocol': 'APC79xxHttp',
894                                   'supported': False},
895                                  { 'port': 23,
896                                   'protocol': 'APC79xx',
897                                   'supported': True},
898                                  { 'port': 22,
899                                   'protocol': 'APC79xx',
900                                   'supported': True}],
901           },
902          {'model': 'Masterswitch',
903           'name': 'APC Masterswitch',
904           'pcu_protocol_types': [{ 'port': 80,
905                                   'protocol': 'APCMasterHttp',
906                                   'supported': False},
907                                  { 'port': 23,
908                                   'protocol': 'APCMaster',
909                                   'supported': True},
910                                  { 'port': 22,
911                                   'protocol': 'APCMaster',
912                                   'supported': True}],
913           },
914          {'model': 'DS4-RPC',
915           'name': 'BayTech DS4-RPC',
916           'pcu_protocol_types': [{ 'port': 80,
917                                   'protocol': 'BayTechHttp',
918                                   'supported': False},
919                                  { 'port': 23,
920                                   'protocol': 'BayTech',
921                                   'supported': True},
922                                  { 'port': 22,
923                                   'protocol': 'BayTech',
924                                   'supported': True}],
925           },
926          {'model': 'IP-41x_IP-81x',
927           'name': 'Dataprobe IP-41x & IP-81x',
928           'pcu_protocol_types': [ { 'port': 23,
929                                   'protocol': 'IPALTelnet',
930                                   'supported': True},
931                                   { 'port': 80,
932                                   'protocol': 'IPALHttp',
933                                   'supported': False}],
934           },
935          {'model': 'DRAC3',
936           'name': 'Dell RAC Version 3',
937           'pcu_protocol_types': [],
938           },
939          {'model': 'DRAC4',
940           'name': 'Dell RAC Version 4',
941           'pcu_protocol_types': [{ 'port': 443,
942                                   'protocol': 'DRACRacAdm',
943                                   'supported': True},
944                                  { 'port': 80,
945                                   'protocol': 'DRACRacAdm',
946                                   'supported': False},
947                                  { 'port': 22,
948                                   'protocol': 'DRAC',
949                                   'supported': True}],
950           },
951          {'model': 'ePowerSwitch',
952           'name': 'ePowerSwitch 1/4/8x',
953           'pcu_protocol_types': [{ 'port': 80,
954                                   'protocol': 'ePowerSwitch',
955                                   'supported': True}],
956           },
957          {'model': 'ilo2',
958           'name': 'HP iLO2 (Integrated Lights-Out)',
959           'pcu_protocol_types': [{ 'port': 443,
960                                   'protocol': 'HPiLOHttps',
961                                   'supported': True},
962                                  { 'port': 22,
963                                   'protocol': 'HPiLO',
964                                   'supported': True}],
965           },
966          {'model': 'ilo1',
967           'name': 'HP iLO version 1',
968           'pcu_protocol_types': [],
969           },
970          {'model': 'PM211-MIP',
971           'name': 'Infratec PM221-MIP',
972           'pcu_protocol_types': [],
973           },
974          {'model': 'AMT2.5',
975           'name': 'Intel AMT v2.5 (Active Management Technology)',
976           'pcu_protocol_types': [],
977           },
978          {'model': 'AMT3.0',
979           'name': 'Intel AMT v3.0 (Active Management Technology)',
980           'pcu_protocol_types': [],
981           },
982          {'model': 'WTI_IPS-4',
983           'name': 'Western Telematic (WTI IPS-4)',
984           'pcu_protocol_types': [],
985           },
986          {'model': 'unknown',
987           'name': 'Unknown Vendor or Model',
988           'pcu_protocol_types': [{ 'port': 443,
989                                   'protocol': 'UnknownPCU',
990                                   'supported': False},
991                                  { 'port': 80,
992                                   'protocol': 'UnknownPCU',
993                                   'supported': False},
994                                  { 'port': 23,
995                                   'protocol': 'UnknownPCU',
996                                   'supported': False},
997                                  { 'port': 22,
998                                   'protocol': 'UnknownPCU',
999                                   'supported': False}],
1000           }]
1001
1002     # Get all model names
1003     pcu_models = [type['model'] for type in GetPCUTypes()]
1004     for type in pcu_types:
1005         protocol_types = type['pcu_protocol_types']
1006         # Take this value out of the struct.
1007         del type['pcu_protocol_types']
1008         if type['model'] not in pcu_models:
1009             # Add the name/model info into DB
1010             id = AddPCUType(type)
1011             # for each protocol, also add this.
1012             for ptype in protocol_types:
1013                 AddPCUProtocolType(id, ptype)
1014
1015
1016 if __name__ == '__main__':
1017     main()
1018
1019 # Local variables:
1020 # tab-width: 4
1021 # mode: python
1022 # End: