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