If the included files fail, make db-config fail.
[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$
11 # $HeadURL$
12
13 from plc_config import PLCConfiguration
14 import sys
15 import resource
16
17 def main():
18     cfg = PLCConfiguration()
19     cfg.load()
20     variables = cfg.variables()
21
22     # Load variables into dictionaries
23     for category_id, (category, variablelist) in variables.iteritems():
24         globals()[category_id] = dict(zip(variablelist.keys(),
25                                        [variable['value'] for variable in variablelist.values()]))
26
27     # Create/update the default administrator account (should be
28     # person_id 2).
29     admin = { 'person_id': 2,
30               'first_name': "Default",
31               'last_name': "Administrator",
32               'email': plc['root_user'],
33               'password': plc['root_password'] }
34     persons = GetPersons([admin['person_id']])
35     if not persons:
36         person_id = AddPerson(admin)
37         if person_id != admin['person_id']:
38             # Huh? Someone deleted the account manually from the database.
39             DeletePerson(person_id)
40             raise Exception, "Someone deleted the \"%s %s\" account from the database!" % \
41                   (admin['first_name'], admin['last_name'])
42         UpdatePerson(person_id, { 'enabled': True })
43     else:
44         person_id = persons[0]['person_id']
45         UpdatePerson(person_id, admin)
46
47     # Create/update the default site (should be site_id 1)
48     if plc_www['port'] == '80':
49         url = "http://" + plc_www['host'] + "/"
50     elif plc_www['port'] == '443':
51         url = "https://" + plc_www['host'] + "/"
52     else:
53         url = "http://" + plc_www['host'] + ":" + plc_www['port'] + "/"
54     site = { 'site_id': 1,
55              'name': plc['name'] + " Central",
56              'abbreviated_name': plc['name'],
57              'login_base': plc['slice_prefix'],
58              'is_public': False,
59              'url': url,
60              'max_slices': 100 }
61
62     sites = GetSites([site['site_id']])
63     if not sites:
64         site_id = AddSite(site['name'], site['abbreviated_name'], site['login_base'], site)
65         if site_id != site['site_id']:
66             DeleteSite(site_id)
67             raise Exception, "Someone deleted the \"%s\" site from the database!" % \
68                   site['name']
69         sites = [site]
70
71     # Must call UpdateSite() even after AddSite() to update max_slices
72     site_id = sites[0]['site_id']
73     UpdateSite(site_id, site)
74
75     # The default administrator account must be associated with a site
76     # in order to login.
77     AddPersonToSite(admin['person_id'], site['site_id'])
78     SetPersonPrimarySite(admin['person_id'], site['site_id'])
79
80     # Grant admin and PI roles to the default administrator account
81     AddRoleToPerson(10, admin['person_id'])
82     AddRoleToPerson(20, admin['person_id'])
83
84     #################### node tags
85     default_node_types = [
86         { 'tagname' : 'arch',
87           'description' : 'architecture name',
88           'category' : 'node/config', 
89           'min_role_id' : 40} ,
90         { 'tagname' : 'pldistro',
91           'description' : 'PlanetLab distribution',
92           'category' : 'node/config', 
93           'min_role_id' : 10} ,
94         { 'tagname' : 'deployment',
95           'description' : 'typically "alpha", "beta", or "production"',
96           'category' : 'node/operation', 
97           'min_role_id' : 10} ,
98         ]
99
100     #################### interface settings
101
102     # Setup default slice attribute types
103     default_setting_types = [
104         {'category' : "interface/general",
105          'tagname' : "ifname",
106          'description': "Set interface name, instead of eth0 or the like",
107          'min_role_id' : 40},
108         {'category' : "interface/multihome",
109          'tagname' : "alias",
110          'description': "Specifies that the network is used for multihoming",
111          'min_role_id' : 40},
112
113         {'category' : "interface/hidden",
114          'tagname' : "backdoor",
115          'description': "For testing new settings",
116          'min_role_id' : 10},
117         ] + [
118         { 'category' : "interface/wifi",
119           'tagname' : x,
120           'description' : "802.11 %s -- see %s"%(y,z),
121           'min_role_id' : 40 } for (x,y,z) in [
122             ("mode","Mode","iwconfig"),
123             ("essid","ESSID","iwconfig"),
124             ("nw","Network Id","iwconfig"),
125             ("freq","Frequency","iwconfig"),
126             ("channel","Channel","iwconfig"),
127             ("sens","sensitivity threshold","iwconfig"),
128             ("rate","Rate","iwconfig"),
129             ("key","key","iwconfig key"),
130             ("key1","key1","iwconfig key [1]"),
131             ("key2","key2","iwconfig key [2]"),
132             ("key3","key3","iwconfig key [3]"),
133             ("key4","key4","iwconfig key [4]"),
134             ("securitymode","Security mode","iwconfig enc"),
135             ("iwconfig","Additional parameters to iwconfig","ifup-wireless"),
136             ("iwpriv","Additional parameters to iwpriv","ifup-wireless"),
137             ]
138         ]
139
140     #################### slice attributes
141
142     # Setup default slice attribute types
143     default_attribute_types = [
144         # Slice type (only vserver is supported)
145         {'tagname': "type",
146          'description': "Type of slice (e.g. vserver)",
147          'category' : 'slice/general',
148          'min_role_id': 20},
149
150         # System slice
151         {'tagname': "system",
152          'description': "Is a default system slice (1) or not (0 or unset)",
153          'category' : 'slice/general',
154          'min_role_id': 10},
155
156         # Slice enabled (1) or suspended (0)
157         {'tagname': "enabled",
158          'description': "Slice enabled (1 or unset) or suspended (0)",
159          'category' : 'slice/general',
160          'min_role_id': 10},
161
162         # Slice reference image
163         {'tagname': "vref",
164          'description': "Reference image",
165          'category' : 'slice/config',
166          'min_role_id': 30},
167
168         # Slice initialization script
169         {'tagname': "initscript",
170          'description': "Slice initialization script",
171          'category' : 'slice/config',
172          'min_role_id': 10},
173
174         # CPU share
175         {'tagname': "cpu_pct",
176          'description': "Reserved CPU percent",
177          'category' : 'slice/rspec',
178          'min_role_id': 10},
179         {'tagname': "cpu_share",
180          'description': "Number of CPU shares",
181          'category' : 'slice/rspec',
182          'min_role_id': 10},
183
184         # Bandwidth limits
185         {'tagname': "net_min_rate",
186          'description': "Minimum bandwidth (kbps)",
187          'category' : 'slice/rspec',
188          'min_role_id': 10},
189         {'tagname': "net_max_rate",
190          'description': "Maximum bandwidth (kbps)",
191          'category' : 'slice/rspec',
192          'min_role_id': 10},
193         {'tagname': "net_i2_min_rate",
194          'description': "Minimum bandwidth over I2 routes (kbps)",
195          'category' : 'slice/rspec',
196          'min_role_id': 10},
197         {'tagname': "net_i2_max_rate",
198          'description': "Maximum bandwidth over I2 routes (kbps)",
199          'category' : 'slice/rspec',
200          'min_role_id': 10},
201         {'tagname': "net_max_kbyte",
202          'description': "Maximum daily network Tx KByte limit.",
203          'category' : 'slice/rspec',
204          'min_role_id': 10},
205         {'tagname': "net_thresh_kbyte",
206          'description': "KByte limit before warning and throttling.",
207          'category' : 'slice/rspec',
208          'min_role_id': 10},
209         {'tagname': "net_i2_max_kbyte",
210          'description': "Maximum daily network Tx KByte limit to I2 hosts.",
211          'category' : 'slice/rspec',
212          'min_role_id': 10},
213         {'tagname': "net_i2_thresh_kbyte",
214          'description': "KByte limit to I2 hosts before warning and throttling.",
215          'category' : 'slice/rspec',
216          'min_role_id': 10},
217         {'tagname': "net_share",
218          'description': "Number of bandwidth shares",
219          'category' : 'slice/rspec',
220          'min_role_id': 10},
221         {'tagname': "net_i2_share",
222          'description': "Number of bandwidth shares over I2 routes",
223          'category' : 'slice/rspec',
224          'min_role_id': 10},
225  
226         # Disk quota
227         {'tagname': "disk_max",
228          'description': "Disk quota (1k disk blocks)",
229          'category' : 'slice/rspec',
230          'min_role_id': 10},
231
232         # Proper operations
233         {'tagname': "proper_op",
234          'description': "Proper operation (e.g. bind_socket)",
235          'category' : 'slice/rspec',
236          'min_role_id': 10},
237
238         # VServer capabilities 
239         {'tagname': "capabilities",
240          'description': "VServer bcapabilities (separate by commas)",
241          'category' : 'slice/rspec',
242          'min_role_id': 10},
243
244         # Vsys
245         {'tagname': "vsys",
246          'description': "Bind vsys script fd's to a slice's vsys directory.",
247          'category' : 'slice/rspec',
248          'min_role_id': 10},
249
250         # CoDemux
251         {'tagname': "codemux",
252          'description': "Demux HTTP between slices using localhost ports. Value in the form 'host, localhost port'.",
253          'category' : 'slice/rspec',
254          'min_role_id': 10},
255
256         # Delegation
257         {'tagname': "delegations",
258          'description': "Coma seperated list of slices to give delegation authority to.",
259          'category' : 'slice/rspec',
260          'min_role_id': 10}
261
262         ]
263
264     # add in the platform supported rlimits to the default_attribute_types
265     for entry in resource.__dict__.keys():
266         if entry.find("RLIMIT_")==0:
267             rlim = entry[len("RLIMIT_"):]
268             rlim = rlim.lower()
269             for ty in ("min","soft","hard"):
270                 attribute = {
271                     'tagname': "%s_%s"%(rlim,ty),
272                     'description': "Per sliver RLIMIT %s_%s."%(rlim,ty),
273                     'category': 'slice/limit',
274                     'min_role_id': 40 #admin
275                     }
276                 default_attribute_types.append(attribute)
277
278     # Get list of existing tag types
279     known_tag_types = [tag_type['tagname'] for tag_type in GetTagTypes()]
280
281     all_default_types = default_node_types + default_setting_types + default_attribute_types
282     # Create/update default slice tag types
283     for default_tag_type in all_default_types:
284         if default_tag_type['tagname'] not in known_tag_types:
285             AddTagType(default_tag_type)
286         else:
287             UpdateTagType(default_tag_type['tagname'], default_tag_type)
288
289     #################### conf files
290
291     # Setup default PlanetLabConf entries
292     default_conf_files = [
293         # NTP configuration
294         {'enabled': True,
295          'source': 'PlanetLabConf/ntp.conf.php',
296          'dest': '/etc/ntp.conf',
297          'file_permissions': '644',
298          'file_owner': 'root',
299          'file_group': 'root',
300          'preinstall_cmd': '',
301          'postinstall_cmd': '/etc/rc.d/init.d/ntpd restart',
302          'error_cmd': '',
303          'ignore_cmd_errors': False,
304          'always_update': False},
305         {'enabled': True,
306          'source': 'PlanetLabConf/ntp/step-tickers.php',
307          'dest': '/etc/ntp/step-tickers',
308          'file_permissions': '644',
309          'file_owner': 'root',
310          'file_group': 'root',
311          'preinstall_cmd': '',
312          'postinstall_cmd': '/etc/rc.d/init.d/ntpd restart',
313          'error_cmd': '',
314          'ignore_cmd_errors': False,
315          'always_update': False},
316
317         # SSH server configuration
318         {'enabled': True,
319          'source': 'PlanetLabConf/sshd_config',
320          'dest': '/etc/ssh/sshd_config',
321          'file_permissions': '600',
322          'file_owner': 'root',
323          'file_group': 'root',
324          'preinstall_cmd': '',
325          'postinstall_cmd': '/etc/init.d/sshd restart',
326          'error_cmd': '',
327          'ignore_cmd_errors': False,
328          'always_update': False},
329
330         # Administrative SSH keys
331         {'enabled': True,
332          'source': 'PlanetLabConf/keys.php?root',
333          'dest': '/root/.ssh/authorized_keys',
334          'file_permissions': '644',
335          'file_owner': 'root',
336          'file_group': 'root',
337          'preinstall_cmd': '',
338          'postinstall_cmd': '/bin/chmod 700 /root/.ssh',
339          'error_cmd': '',
340          'ignore_cmd_errors': False,
341          'always_update': False},
342         {'enabled': True,
343          'source': 'PlanetLabConf/keys.php?site_admin',
344          'dest': '/home/site_admin/.ssh/authorized_keys',
345          'file_permissions': '644',
346          'file_owner': 'site_admin',
347          'file_group': 'site_admin',
348          'preinstall_cmd': 'grep -q site_admin /etc/passwd',
349          'postinstall_cmd': '/bin/chmod 700 /home/site_admin/.ssh',
350          'error_cmd': '',
351          'ignore_cmd_errors': False,
352          'always_update': False},
353         # Log rotation configuration
354         {'enabled': True,
355          'source': 'PlanetLabConf/logrotate.conf',
356          'dest': '/etc/logrotate.conf',
357          'file_permissions': '644',
358          'file_owner': 'root',
359          'file_group': 'root',
360          'preinstall_cmd': '',
361          'postinstall_cmd': '',
362          'error_cmd': '',
363          'ignore_cmd_errors': False,
364          'always_update': False},
365
366         # updatedb/locate nightly cron job
367         {'enabled': True,
368          'source': 'PlanetLabConf/slocate.cron',
369          'dest': '/etc/cron.daily/slocate.cron',
370          'file_permissions': '755',
371          'file_owner': 'root',
372          'file_group': 'root',
373          'preinstall_cmd': '',
374          'postinstall_cmd': '',
375          'error_cmd': '',
376          'ignore_cmd_errors': False,
377          'always_update': False},
378
379         # YUM configuration
380         {'enabled': True,
381          'source': 'yum/myplc.repo.php?gpgcheck=1',
382          'dest': '/etc/yum.myplc.d/myplc.repo',
383          'file_permissions': '644', 'file_owner': 'root', 'file_group': 'root',
384          'preinstall_cmd': '', 'postinstall_cmd': '', 'error_cmd': '',
385          'ignore_cmd_errors': False,
386          'always_update': False},
387         {'enabled': True,
388          'source': 'yum/yum.conf',
389          'dest': '/etc/yum.conf',
390          'file_permissions': '644', 'file_owner': 'root', 'file_group': 'root',
391          'preinstall_cmd': '', 'postinstall_cmd': '', 'error_cmd': '',
392          'ignore_cmd_errors': False,
393          'always_update': False},
394         {'enabled': True,
395          'source': 'yum/stock.repo',
396          'dest': '/etc/yum.myplc.d/stock.repo',
397          'file_permissions': '644', 'file_owner': 'root', 'file_group': 'root',
398          'preinstall_cmd': '', 'postinstall_cmd': '', 'error_cmd': '',
399          'ignore_cmd_errors': False,
400          'always_update': False},
401
402         {'enabled': True,
403          'source': 'PlanetLabConf/delete-rpm-list-production',
404          'dest': '/etc/planetlab/delete-rpm-list',
405          'file_permissions': '644',
406          'file_owner': 'root',
407          'file_group': 'root',
408          'preinstall_cmd': '',
409          'postinstall_cmd': '',
410          'error_cmd': '',
411          'ignore_cmd_errors': False,
412          'always_update': False},
413
414         # PLC configuration
415         {'enabled': True,
416          'source': 'PlanetLabConf/get_plc_config.php',
417          'dest': '/etc/planetlab/plc_config',
418          'file_permissions': '644',
419          'file_owner': 'root',
420          'file_group': 'root',
421          'preinstall_cmd': '',
422          'postinstall_cmd': '',
423          'error_cmd': '',
424          'ignore_cmd_errors': False,
425          'always_update': False},
426         {'enabled': True,
427          'source': 'PlanetLabConf/get_plc_config.php?python',
428          'dest': '/etc/planetlab/plc_config.py',
429          'file_permissions': '644',
430          'file_owner': 'root',
431          'file_group': 'root',
432          'preinstall_cmd': '',
433          'postinstall_cmd': '',
434          'error_cmd': '',
435          'ignore_cmd_errors': False,
436          'always_update': False},
437         {'enabled': True,
438          'source': 'PlanetLabConf/get_plc_config.php?perl',
439          'dest': '/etc/planetlab/plc_config.pl',
440          'file_permissions': '644',
441          'file_owner': 'root',
442          'file_group': 'root',
443          'preinstall_cmd': '',
444          'postinstall_cmd': '',
445          'error_cmd': '',
446          'ignore_cmd_errors': False,
447          'always_update': False},
448         {'enabled': True,
449          'source': 'PlanetLabConf/get_plc_config.php?php',
450          'dest': '/etc/planetlab/php/plc_config.php',
451          'file_permissions': '644',
452          'file_owner': 'root',
453          'file_group': 'root',
454          'preinstall_cmd': '',
455          'postinstall_cmd': '',
456          'error_cmd': '',
457          'ignore_cmd_errors': False,
458          'always_update': False},
459
460         # XXX Required for old Node Manager
461         # Proper configuration
462         {'enabled': True,
463          'source': 'PlanetLabConf/propd.conf',
464          'dest': '/etc/proper/propd.conf',
465          'file_permissions': '644',
466          'file_owner': 'root',
467          'file_group': 'root',
468          'preinstall_cmd': '',
469          'postinstall_cmd': '/etc/init.d/proper restart',
470          'error_cmd': '',
471          'ignore_cmd_errors': True,
472          'always_update': False},
473
474         # XXX Required for old Node Manager
475         # Bandwidth cap
476         {'enabled': True,
477          'source': 'PlanetLabConf/bwlimit.php',
478          'dest': '/etc/planetlab/bwcap',
479          'file_permissions': '644',
480          'file_owner': 'root',
481          'file_group': 'root',
482          'preinstall_cmd': '',
483          'postinstall_cmd': '',
484          'error_cmd': '',
485          'ignore_cmd_errors': True,
486          'always_update': False},
487
488         # Proxy ARP setup
489         {'enabled': True,
490          'source': 'PlanetLabConf/proxies.php',
491          'dest': '/etc/planetlab/proxies',
492          'file_permissions': '644',
493          'file_owner': 'root',
494          'file_group': 'root',
495          'preinstall_cmd': '',
496          'postinstall_cmd': '',
497          'error_cmd': '',
498          'ignore_cmd_errors': False,
499          'always_update': False},
500
501         # Firewall configuration
502         {'enabled': True,
503          'source': 'PlanetLabConf/blacklist.php',
504          'dest': '/etc/planetlab/blacklist',
505          'file_permissions': '600',
506          'file_owner': 'root',
507          'file_group': 'root',
508          'preinstall_cmd': '',
509          'postinstall_cmd': '/sbin/iptables-restore --noflush < /etc/planetlab/blacklist',
510          'error_cmd': '',
511          'ignore_cmd_errors': True,
512          'always_update': False},
513
514         # /etc/issue
515         {'enabled': True,
516          'source': 'PlanetLabConf/issue.php',
517          'dest': '/etc/issue',
518          'file_permissions': '644',
519          'file_owner': 'root',
520          'file_group': 'root',
521          'preinstall_cmd': '',
522          'postinstall_cmd': '',
523          'error_cmd': '',
524          'ignore_cmd_errors': False,
525          'always_update': False},
526
527         # Kernel parameters
528         {'enabled': True,
529          'source': 'PlanetLabConf/sysctl.php',
530          'dest': '/etc/sysctl.conf',
531          'file_permissions': '644',
532          'file_owner': 'root',
533          'file_group': 'root',
534          'preinstall_cmd': '',
535          'postinstall_cmd': '/sbin/sysctl -e -p /etc/sysctl.conf',
536          'error_cmd': '',
537          'ignore_cmd_errors': False,
538          'always_update': False},
539
540         # Sendmail configuration
541         {'enabled': True,
542          'source': 'PlanetLabConf/sendmail.mc',
543          'dest': '/etc/mail/sendmail.mc',
544          'file_permissions': '644',
545          'file_owner': 'root',
546          'file_group': 'root',
547          'preinstall_cmd': '',
548          'postinstall_cmd': '',
549          'error_cmd': '',
550          'ignore_cmd_errors': False,
551          'always_update': False},
552         {'enabled': True,
553          'source': 'PlanetLabConf/sendmail.cf',
554          'dest': '/etc/mail/sendmail.cf',
555          'file_permissions': '644',
556          'file_owner': 'root',
557          'file_group': 'root',
558          'preinstall_cmd': '',
559          'postinstall_cmd': 'service sendmail restart',
560          'error_cmd': '',
561          'ignore_cmd_errors': False,
562          'always_update': False},
563
564         # GPG signing keys
565         {'enabled': True,
566          'source': 'PlanetLabConf/RPM-GPG-KEY-fedora',
567          'dest': '/etc/pki/rpm-gpg/RPM-GPG-KEY-fedora',
568          'file_permissions': '644',
569          'file_owner': 'root',
570          'file_group': 'root',
571          'preinstall_cmd': '',
572          'postinstall_cmd': 'rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-fedora',
573          'error_cmd': '',
574          'ignore_cmd_errors': False,
575          'always_update': False},
576         {'enabled': True,
577          'source': 'PlanetLabConf/get_gpg_key.php',
578          'dest': '/etc/pki/rpm-gpg/RPM-GPG-KEY-planetlab',
579          'file_permissions': '644',
580          'file_owner': 'root',
581          'file_group': 'root',
582          'preinstall_cmd': '',
583          'postinstall_cmd': 'rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-planetlab',
584          'error_cmd': '',
585          'ignore_cmd_errors': False,
586          'always_update': False},
587
588         # Ping of death configuration
589         # the 'restart' postcommand doesn't work, b/c the pod script doesn't support it.
590         {'enabled': True,
591          'source': 'PlanetLabConf/ipod.conf.php',
592          'dest': '/etc/ipod.conf',
593          'file_permissions': '644',
594          'file_owner': 'root',
595          'file_group': 'root',
596          'preinstall_cmd': '',
597          'postinstall_cmd': '/etc/init.d/pod start',
598          'error_cmd': '',
599          'ignore_cmd_errors': False,
600          'always_update': False},
601
602         # sudo configuration
603         {'enabled': True,
604          'source': 'PlanetLabConf/sudoers.php',
605          'dest': '/etc/sudoers',
606          'file_permissions': '440',
607          'file_owner': 'root',
608          'file_group': 'root',
609          'preinstall_cmd': '',
610          'postinstall_cmd': '/usr/sbin/visudo -c',
611          'error_cmd': '',
612          'ignore_cmd_errors': False,
613          'always_update': False}
614         ]
615
616     # Get list of existing (enabled, global) files
617     conf_files = GetConfFiles()
618     conf_files = filter(lambda conf_file: conf_file['enabled'] and \
619                                           not conf_file['node_ids'] and \
620                                           not conf_file['nodegroup_ids'],
621                         conf_files)
622     dests = [conf_file['dest'] for conf_file in conf_files]
623     conf_files = dict(zip(dests, conf_files))
624
625     # Create/update default PlanetLabConf entries
626     for default_conf_file in default_conf_files:
627         if default_conf_file['dest'] not in dests:
628             AddConfFile(default_conf_file)
629         else:
630             conf_file = conf_files[default_conf_file['dest']]
631             UpdateConfFile(conf_file['conf_file_id'], default_conf_file)
632
633
634     #################### initscripts
635
636     # Default Initscripts
637     default_initscripts = []
638
639     # Find initscripts and add them to the db
640     for (root, dirs, files) in os.walk("/etc/plc_sliceinitscripts"):
641         for f in files:
642             # Read the file
643             file = open(root + "/" + f, "ro")
644             default_initscripts.append({"name": plc['slice_prefix'] + "_" + f,
645                                         "enabled": True,
646                                         "script": file.read().replace("@SITE@", url).replace("@PREFIX@", plc['slice_prefix'])})
647             file.close()
648
649     # Get list of existing initscripts
650     oldinitscripts = GetInitScripts()
651     oldinitscripts = [script['name'] for script in oldinitscripts]
652
653     for initscript in default_initscripts:
654         if initscript['name'] not in oldinitscripts:  AddInitScript(initscript)
655
656     # Create/update system slices
657     default_slices = [
658          # PlanetFlow
659         {'name': plc['slice_prefix'] + "_netflow",
660          'description': "PlanetFlow Traffic Auditing Service.  Logs, captured in the root context using fprobe-ulogd, are stored in a directory in the root context which is bind mounted to the planetflow slice.  The Planetflow Central service then periodically rsyncs these logs from the planetflow slice for aggregation.",
661          'url': url,
662          'instantiation': "plc-instantiated",
663          # Renew forever (minus one day, work around date conversion weirdness)
664          'expires': 0x7fffffff - (60 * 60 * 24),
665          'attributes': [('system', "1"),
666                         ('vref', "planetflow"),
667                         ('vsys', "pfmount")]},
668           # Sirius
669         {'name': plc['slice_prefix'] + "_sirius",
670          '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',
671          'url': url + "db/sirius/index.php",
672          'instantiation': "plc-instantiated",
673          # Renew forever (minus one day, work around date conversion weirdness)
674          'expires': 0x7fffffff - (60 * 60 * 24),
675          'attributes': [('system', "1"),
676                         ('net_min_rate', "2000"),
677                         ('cpu_pct', "25"),
678                         ('initscript', plc['slice_prefix'] + "_sirius")]}
679         ]
680     
681     for default_slice in default_slices:
682         slices = GetSlices([default_slice['name']])
683         if slices:
684             slice = slices[0]
685             UpdateSlice(slice['slice_id'], default_slice)
686         else:
687             AddSlice(default_slice)
688             slice = GetSlices([default_slice['name']])[0]
689
690         # Create/update all attributes
691         slice_attributes = []
692         if slice['slice_attribute_ids']:
693             # Delete unknown attributes
694             for slice_attribute in GetSliceAttributes(slice['slice_attribute_ids']):
695                 if (slice_attribute['tagname'], slice_attribute['value']) \
696                    not in default_slice['attributes']:
697                     DeleteSliceAttribute(slice_attribute['slice_attribute_id'])
698                 else:
699                     slice_attributes.append((slice_attribute['tagname'], slice_attribute['value']))
700
701         for (name, value) in default_slice['attributes']:
702             if (name, value) not in slice_attributes:
703                 AddSliceAttribute(slice['name'], name, value)
704
705     
706     #################### body for messages
707
708     installfailed = """
709 Once the node meets these requirements, please reinitiate the install
710 by visiting:
711
712 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/nodes/?id=%(node_id)d
713
714 Update the BootState to 'Reinstall', then reboot the node.
715
716 If you have already performed this step and are still receiving this
717 message, please reply so that we may investigate the problem.
718 """
719
720     # Load default message templates
721     message_templates = [
722         {'message_id': 'Verify account',
723          'subject': "Verify account registration",
724          'template': """
725 Please verify that you registered for a %(PLC_NAME)s account with the
726 username %(email)s by visiting:
727
728 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/persons/register.php?id=%(person_id)d&key=%(verification_key)s
729
730 You must wait for this account to be approved before you can begin using it, please be patient.
731
732 If you did not register for a %(PLC_NAME)s account, please ignore this
733 message, or contact %(PLC_NAME)s Support <%(PLC_MAIL_SUPPORT_ADDRESS)s>.
734 """
735          },
736
737         {'message_id': 'New PI account',
738          'subject': "New PI account registration from %(first_name)s %(last_name)s <%(email)s> at %(site_name)s",
739          'template': """
740 %(first_name)s %(last_name)s <%(email)s> has signed up for a new
741 %(PLC_NAME)s account at %(site_name)s and has requested a PI role. PIs
742 are responsible for enabling user accounts, creating slices, and
743 ensuring that all users abide by the %(PLC_NAME)s Acceptable Use
744 Policy.
745
746 Only %(PLC_NAME)s administrators may enable new PI accounts. If you
747 are a PI at %(site_name)s, please respond and indicate whether this
748 registration is acceptable.
749
750 To view the request, visit:
751
752 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/persons/index.php?id=%(person_id)d
753 """
754          },
755
756         {'message_id': 'New account',
757          'subject': "New account registration from %(first_name)s %(last_name)s <%(email)s> at %(site_name)s",
758          'template': """
759 %(first_name)s %(last_name)s <%(email)s> has signed up for a new
760 %(PLC_NAME)s account at %(site_name)s and has requested the following
761 roles: %(roles)s.
762
763 To deny the request or enable the account, visit:
764
765 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/persons/index.php?id=%(person_id)d
766 """
767          },
768
769         {'message_id': 'Password reset requested',
770          'subject': "Password reset requested",
771          'template': """
772 Someone has requested that the password of your %(PLC_NAME)s account
773 %(email)s be reset. If this person was you, you may continue with the
774 reset by visiting:
775
776 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/persons/reset_password.php?id=%(person_id)d&key=%(verification_key)s
777
778 If you did not request that your password be reset, please contact
779 %(PLC_NAME)s Support <%(PLC_MAIL_SUPPORT_ADDRESS)s>. Do not quote or
780 otherwise include any of this text in any correspondence.
781 """
782          },
783
784         {'message_id': 'Password reset',
785          'subject': "Password reset",
786          'template': """
787 The password of your %(PLC_NAME)s account %(email)s has been
788 temporarily reset to:
789
790 %(password)s
791
792 Please change it at as soon as possible by visiting:
793
794 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/persons/index.php?id=%(person_id)d
795
796 If you did not request that your password be reset, please contact
797 %(PLC_NAME)s Support <%(PLC_MAIL_SUPPORT_ADDRESS)s>. Do not quote or
798 otherwise include any of this text in any correspondence.
799 """
800          },
801
802         # Boot Manager messages
803         {'message_id': "installfinished",
804          'subject': "%(hostname)s completed installation",
805          'template': """
806 %(hostname)s just completed installation.
807
808 The node should be usable in a couple of minutes if installation was
809 successful.
810 """
811          },
812
813         {'message_id': "insufficientdisk",
814          'subject': "%(hostname)s does not have sufficient disk space",
815          'template': """
816 %(hostname)s failed to boot because it does not have sufficent disk
817 space, or because its disk controller was not recognized.
818
819 Please replace the current disk or disk controller or install
820 additional disks to meet the current hardware requirements.
821 """ + installfailed
822          },
823
824         {'message_id': "insufficientmemory",
825          'subject': "%(hostname)s does not have sufficient memory",
826          'template': """
827 %(hostname)s failed to boot because it does not have sufficent
828 memory.
829
830 Please install additional memory to meet the current hardware
831 requirements.
832 """ + installfailed
833          },
834
835         {'message_id': "authfail",
836          'subject': "%(hostname)s failed to authenticate",
837          'template':
838 """
839 %(hostname)s failed to authenticate for the following reason:
840
841 %(fault)s
842
843 The most common reason for authentication failure is that the
844 authentication key stored in the node configuration file, does not
845 match the key on record. 
846
847 There are two possible steps to resolve the problem.
848
849 1. If you have used an All-in-one BootCD that includes the plnode.txt file,
850     then please check your machine for any old boot media, either in the
851     floppy drive, or on a USB stick.  It is likely that an old configuration
852     is being used instead of the new configuration stored on the BootCD.
853 Or, 
854 2. If you are using Generic BootCD image, then regenerate the node 
855     configuration file by visiting:
856
857     https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/nodes/?id=%(node_id)d
858
859     Under 'Download', follow the 'Download plnode.txt file for %(hostname)s'
860     option, and save the downloaded file as plnode.txt on either a floppy 
861     disk or a USB flash drive.  Be sure the 'Boot State' is set to 'Boot', 
862     and, then reboot the node.
863
864 If you have already performed this step and are still receiving this
865 message, please reply so that we can help investigate the problem.
866 """
867          },
868
869         {'message_id': "notinstalled",
870          'subject': "%(hostname)s is not installed",
871          'template':
872 """
873 %(hostname)s failed to boot because it has either never been
874 installed, or the installation is corrupt.
875
876 Please check if the hard drive has failed, and replace it if so. After
877 doing so, visit:
878
879 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/nodes/?id=%(node_id)d
880
881 Change the 'Boot State' to 'Reinstall', and then reboot the node.
882
883 If you have already performed this step and are still receiving this
884 message, please reply so that we may investigate the problem.
885 """
886          },
887
888         {'message_id': "hostnamenotresolve",
889          'subject': "%(hostname)s does not resolve",
890          'template':
891 """
892 %(hostname)s failed to boot because its hostname does not resolve, or
893 does resolve but does not match its configured IP address.
894
895 Please check the network settings for the node, especially its
896 hostname, IP address, and DNS servers, by visiting:
897
898 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/nodes/?id=%(node_id)d
899
900 Correct any errors, and change the 'Boot State' to 'Reinstall', and then
901 reboot the node.
902
903 If you have already performed this step and are still receiving this
904 message, please reply so that we may investigate the problem.
905 """
906          },
907
908         # XXX N.B. I don't think these are necessary, since there's no
909         # way that the Boot Manager would even be able to contact the
910         # API to send these messages.
911
912         {'message_id': "noconfig",
913          'subject': "%(hostname)s does not have a configuration file",
914          'template': """
915 %(hostname)s failed to boot because it could not find a PlanetLab
916 configuration file. To create this file, visit:
917
918 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/nodes/?id=%(node_id)d
919
920 Click the Configuration File link, and save the downloaded file as
921 plnode.txt on either a floppy disk or a USB flash drive.  Change the 
922 'Boot State' to 'Reinstall', and then reboot the node.
923
924 If you have already performed this step and are still receiving this
925 message, please reply so that we may investigate the problem.
926 """
927          },
928
929         {'message_id': "nodetectednetwork",
930          'subject': "%(hostname)s has unsupported network hardware",
931          'template':
932 """
933
934 %(hostname)s failed to boot because it has network hardware that is
935 unsupported by the current production kernel. If it has booted
936 successfully in the past, please try re-installing it by visiting:
937
938 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/nodes/?id=%(node_id)d
939
940 Change the 'Boot State' to 'Reinstall', and then reboot the node.
941
942 If you have already performed this step and are still receiving this
943 message, please reply so that we may investigate the problem.
944 """
945          },
946         ]
947
948     for template in message_templates:
949         messages = GetMessages([template['message_id']])
950         if not messages:
951             AddMessage(template)
952
953     #################### PCUs
954     
955     ### Setup Initial PCU information
956     pcu_types = [{'model': 'AP79xx',
957           'name': 'APC AP79xx',
958           'pcu_protocol_types': [{ 'port': 80,
959                                   'protocol': 'APC79xxHttp',
960                                   'supported': False},
961                                  { 'port': 23,
962                                   'protocol': 'APC79xx',
963                                   'supported': True},
964                                  { 'port': 22,
965                                   'protocol': 'APC79xx',
966                                   'supported': True}],
967           },
968          {'model': 'Masterswitch',
969           'name': 'APC Masterswitch',
970           'pcu_protocol_types': [{ 'port': 80,
971                                   'protocol': 'APCMasterHttp',
972                                   'supported': False},
973                                  { 'port': 23,
974                                   'protocol': 'APCMaster',
975                                   'supported': True},
976                                  { 'port': 22,
977                                   'protocol': 'APCMaster',
978                                   'supported': True}],
979           },
980          {'model': 'DS4-RPC',
981           'name': 'BayTech DS4-RPC',
982           'pcu_protocol_types': [{ 'port': 80,
983                                   'protocol': 'BayTechHttp',
984                                   'supported': False},
985                                  { 'port': 23,
986                                   'protocol': 'BayTech',
987                                   'supported': True},
988                                  { 'port': 22,
989                                   'protocol': 'BayTech',
990                                   'supported': True}],
991           },
992          {'model': 'IP-41x_IP-81x',
993           'name': 'Dataprobe IP-41x & IP-81x',
994           'pcu_protocol_types': [ { 'port': 23,
995                                   'protocol': 'IPALTelnet',
996                                   'supported': True},
997                                   { 'port': 80,
998                                   'protocol': 'IPALHttp',
999                                   'supported': False}],
1000           },
1001          {'model': 'DRAC3',
1002           'name': 'Dell RAC Version 3',
1003           'pcu_protocol_types': [],
1004           },
1005          {'model': 'DRAC4',
1006           'name': 'Dell RAC Version 4',
1007           'pcu_protocol_types': [{ 'port': 443,
1008                                   'protocol': 'DRACRacAdm',
1009                                   'supported': True},
1010                                  { 'port': 80,
1011                                   'protocol': 'DRACRacAdm',
1012                                   'supported': False},
1013                                  { 'port': 22,
1014                                   'protocol': 'DRAC',
1015                                   'supported': True}],
1016           },
1017          {'model': 'ePowerSwitch',
1018           'name': 'ePowerSwitch 1/4/8x',
1019           'pcu_protocol_types': [{ 'port': 80,
1020                                   'protocol': 'ePowerSwitch',
1021                                   'supported': True}],
1022           },
1023          {'model': 'ilo2',
1024           'name': 'HP iLO2 (Integrated Lights-Out)',
1025           'pcu_protocol_types': [{ 'port': 443,
1026                                   'protocol': 'HPiLOHttps',
1027                                   'supported': True},
1028                                  { 'port': 22,
1029                                   'protocol': 'HPiLO',
1030                                   'supported': True}],
1031           },
1032          {'model': 'ilo1',
1033           'name': 'HP iLO version 1',
1034           'pcu_protocol_types': [],
1035           },
1036          {'model': 'PM211-MIP',
1037           'name': 'Infratec PM221-MIP',
1038           'pcu_protocol_types': [],
1039           },
1040          {'model': 'AMT2.5',
1041           'name': 'Intel AMT v2.5 (Active Management Technology)',
1042           'pcu_protocol_types': [],
1043           },
1044          {'model': 'AMT3.0',
1045           'name': 'Intel AMT v3.0 (Active Management Technology)',
1046           'pcu_protocol_types': [],
1047           },
1048          {'model': 'WTI_IPS-4',
1049           'name': 'Western Telematic (WTI IPS-4)',
1050           'pcu_protocol_types': [],
1051           },
1052          {'model': 'unknown',
1053           'name': 'Unknown Vendor or Model',
1054           'pcu_protocol_types': [{ 'port': 443,
1055                                   'protocol': 'UnknownPCU',
1056                                   'supported': False},
1057                                  { 'port': 80,
1058                                   'protocol': 'UnknownPCU',
1059                                   'supported': False},
1060                                  { 'port': 23,
1061                                   'protocol': 'UnknownPCU',
1062                                   'supported': False},
1063                                  { 'port': 22,
1064                                   'protocol': 'UnknownPCU',
1065                                   'supported': False}],
1066           }]
1067
1068     # Get all model names
1069     pcu_models = [type['model'] for type in GetPCUTypes()]
1070     for type in pcu_types:
1071         protocol_types = type['pcu_protocol_types']
1072         # Take this value out of the struct.
1073         del type['pcu_protocol_types']
1074         if type['model'] not in pcu_models:
1075             # Add the name/model info into DB
1076             id = AddPCUType(type)
1077             # for each protocol, also add this.
1078             for ptype in protocol_types:
1079                 AddPCUProtocolType(id, ptype)
1080
1081     default_boot_states = [
1082         'boot',
1083         'failboot',
1084         'safeboot',
1085         'install',
1086         'reinstall',
1087         'disabled',
1088     ]
1089     current_boot_states = GetBootStates()
1090     for state in default_boot_states:
1091         if state not in current_boot_states:
1092             AddBootState(state)
1093
1094     # TODO: Delete old boot states. 
1095     # NOTE: Only do this if all federating peers have the new default boot states above.
1096     #for state in current_boot_states:
1097     #    if state not in default_boot_states:
1098     #        DeleteBootState(state)
1099
1100     # Run local db-config snippets
1101     files = []
1102     dir = "/etc/planetlab/db-config.d"
1103     try:
1104         files = os.listdir(dir)
1105     except:
1106         pass
1107
1108     for file in files:
1109         if (file.endswith(".bak") or file.endswith("~") or
1110             file.endswith(".rpmsave") or file.endswith(".rpmnew") or
1111             file.endswith(".orig")):
1112             continue
1113         execfile(os.path.join(dir, file))
1114
1115
1116 if __name__ == '__main__':
1117     main()
1118
1119 # Local variables:
1120 # tab-width: 4
1121 # mode: python
1122 # End: