4f95439e389591ce70919741e6ae8eede636c3a3
[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         ]
526
527     # add in the platform supported rlimits to the default_attribute_types
528     for entry in resource.__dict__.keys():
529         if entry.find("RLIMIT_")==0:
530             rlim = entry[len("RLIMIT_"):]
531             rlim = rlim.lower()
532             for ty in ("min","soft","hard"):
533                 attribute = {
534                     'name': "%s_%s'%(rlim,ty)",
535                     'description': "Per sliver RLIMIT %s_%s."%(rlim,ty),
536                     'min_role_id': 40 #admin
537                     }
538                 default_attribute_types.append(attribute)
539
540     # Get list of existing attribute types
541     attribute_types = GetSliceAttributeTypes()
542     attribute_types = [attribute_type['name'] for attribute_type in attribute_types]
543
544     # Create/update default slice attribute types
545     for default_attribute_type in default_attribute_types:
546         if default_attribute_type['name'] not in attribute_types:
547             AddSliceAttributeType(default_attribute_type)
548         else:
549             UpdateSliceAttributeType(default_attribute_type['name'], default_attribute_type)
550
551     # Default Initscripts
552     default_initscripts = []
553
554     # Find initscripts and add them to the db
555     for (root, dirs, files) in os.walk("/etc/plc_sliceinitscripts"):
556         for f in files:
557             # Read the file
558             file = open(root + "/" + f, "ro")
559             default_initscripts.append({"name": plc['slice_prefix'] + "_" + f,
560                                         "enabled": True,
561                                         "script": file.read().replace("@SITE@", url).replace("@PREFIX@", plc['slice_prefix'])})
562             file.close()
563
564     # Get list of existing initscripts
565     oldinitscripts = GetInitScripts()
566     oldinitscripts = [script['name'] for script in oldinitscripts]
567
568     for initscript in default_initscripts:
569         if initscript['name'] not in oldinitscripts:  AddInitScript(initscript)
570
571     # Setup default slice attribute types
572     default_setting_types = [
573
574         {'category' : "general",
575          'name' : "ifname",
576          'description': "Set interface name, instead of eth0 or the like",
577          'min_role_id' : 40},
578         {'category' : "Multihome",
579          'name' : "alias",
580          'description': "Specifies that the network is used for multihoming",
581          'min_role_id' : 40},
582
583         {'category' : "hidden",
584          'name' : "backdoor",
585          'description': "For testing new settings",
586          'min_role_id' : 10},
587         ] + [
588         { "category" : "WiFi",
589           "name" : x,
590           "description" : "802.11 %s -- see %s"%(y,z),
591           "min_role_id" : 40 } for (x,y,z) in [
592             ("mode","Mode","iwconfig"),
593             ("essid","ESSID","iwconfig"),
594             ("nw","Network Id","iwconfig"),
595             ("freq","Frequency","iwconfig"),
596             ("channel","Channel","iwconfig"),
597             ("sens","sensitivity threshold","iwconfig"),
598             ("rate","Rate","iwconfig"),
599             ("key","key","iwconfig key"),
600             ("key1","key1","iwconfig key [1]"),
601             ("key2","key2","iwconfig key [2]"),
602             ("key3","key3","iwconfig key [3]"),
603             ("key4","key4","iwconfig key [4]"),
604             ("securitymode","Security mode","iwconfig enc"),
605             ("iwconfig","Additional parameters to iwconfig","ifup-wireless"),
606             ("iwpriv","Additional parameters to iwpriv","ifup-wireless"),
607             ]
608         ]
609
610
611     # Get list of existing attribute types
612     setting_types = GetNodeNetworkSettingTypes()
613     setting_types = [setting_type['name'] for setting_type in setting_types]
614
615     # Create/update default slice setting types
616     for default_setting_type in default_setting_types:
617         if default_setting_type['name'] not in setting_types:
618             AddNodeNetworkSettingType(default_setting_type)
619         else:
620             UpdateNodeNetworkSettingType(default_setting_type['name'], default_setting_type)
621
622     # Create/update system slices
623     default_slices = [
624          # PlanetFlow
625         {'name': plc['slice_prefix'] + "_netflow",
626          '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.",
627          'url': url,
628          'instantiation': "plc-instantiated",
629          # Renew forever (minus one day, work around date conversion weirdness)
630          'expires': 0x7fffffff - (60 * 60 * 24),
631          'attributes': [('system', "1"),
632                         ('vref', "planetflow"),
633                                                 ('vsys', "pfmount")]},
634           # Sirius
635         {'name': plc['slice_prefix'] + "_sirius",
636          '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',
637          'url': url + "db/sirius/index.php",
638          'instantiation': "plc-instantiated",
639          # Renew forever (minus one day, work around date conversion weirdness)
640          'expires': 0x7fffffff - (60 * 60 * 24),
641          'attributes': [('system', "1"),
642                         ('net_min_rate', "2000"),
643                         ('cpu_pct', "25"),
644                         ('initscript', plc['slice_prefix'] + "_sirius")]}
645         ]
646     
647     for default_slice in default_slices:
648         slices = GetSlices([default_slice['name']])
649         if slices:
650             slice = slices[0]
651             UpdateSlice(slice['slice_id'], default_slice)
652         else:
653             AddSlice(default_slice)
654             slice = GetSlices([default_slice['name']])[0]
655
656         # Create/update all attributes
657         slice_attributes = []
658         if slice['slice_attribute_ids']:
659             # Delete unknown attributes
660             for slice_attribute in GetSliceAttributes(slice['slice_attribute_ids']):
661                 if (slice_attribute['name'], slice_attribute['value']) \
662                    not in default_slice['attributes']:
663                     DeleteSliceAttribute(slice_attribute['slice_attribute_id'])
664                 else:
665                     slice_attributes.append((slice_attribute['name'], slice_attribute['value']))
666
667         for (name, value) in default_slice['attributes']:
668             if (name, value) not in slice_attributes:
669                 AddSliceAttribute(slice['name'], name, value)
670
671     installfailed = """
672 Once the node meets these requirements, please reinitiate the install
673 by visiting:
674
675 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/nodes/?id=%(node_id)d
676
677 Update the BootState to 'Reinstall', then reboot the node.
678
679 If you have already performed this step and are still receiving this
680 message, please reply so that we may investigate the problem.
681 """
682
683     # Load default message templates
684     message_templates = [
685         {'message_id': 'Verify account',
686          'subject': "Verify account registration",
687          'template': """
688 Please verify that you registered for a %(PLC_NAME)s account with the
689 username %(email)s by visiting:
690
691 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/persons/register.php?id=%(person_id)d&key=%(verification_key)s
692
693 If you did not register for a %(PLC_NAME)s account, please ignore this
694 message, or contact %(PLC_NAME)s Support <%(PLC_MAIL_SUPPORT_ADDRESS)s>.
695 """
696          },
697
698         {'message_id': 'New PI account',
699          'subject': "New PI account registration from %(first_name)s %(last_name)s <%(email)s> at %(site_name)s",
700          'template': """
701 %(first_name)s %(last_name)s <%(email)s> has signed up for a new
702 %(PLC_NAME)s account at %(site_name)s and has requested a PI role. PIs
703 are responsible for enabling user accounts, creating slices, and
704 ensuring that all users abide by the %(PLC_NAME)s Acceptable Use
705 Policy.
706
707 Only %(PLC_NAME)s administrators may enable new PI accounts. If you
708 are a PI at %(site_name)s, please respond and indicate whether this
709 registration is acceptable.
710
711 To view the request, visit:
712
713 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/persons/index.php?id=%(person_id)d
714 """
715          },
716
717         {'message_id': 'New account',
718          'subject': "New account registration from %(first_name)s %(last_name)s <%(email)s> at %(site_name)s",
719          'template': """
720 %(first_name)s %(last_name)s <%(email)s> has signed up for a new
721 %(PLC_NAME)s account at %(site_name)s and has requested the following
722 roles: %(roles)s.
723
724 To deny the request or enable the account, visit:
725
726 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/persons/index.php?id=%(person_id)d
727 """
728          },
729
730         {'message_id': 'Password reset requested',
731          'subject': "Password reset requested",
732          'template': """
733 Someone has requested that the password of your %(PLC_NAME)s account
734 %(email)s be reset. If this person was you, you may continue with the
735 reset by visiting:
736
737 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/persons/reset_password.php?id=%(person_id)d&key=%(verification_key)s
738
739 If you did not request that your password be reset, please contact
740 %(PLC_NAME)s Support <%(PLC_MAIL_SUPPORT_ADDRESS)s>. Do not quote or
741 otherwise include any of this text in any correspondence.
742 """
743          },
744
745         {'message_id': 'Password reset',
746          'subject': "Password reset",
747          'template': """
748 The password of your %(PLC_NAME)s account %(email)s has been
749 temporarily reset to:
750
751 %(password)s
752
753 Please change it at as soon as possible by visiting:
754
755 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/persons/index.php?id=%(person_id)d
756
757 If you did not request that your password be reset, please contact
758 %(PLC_NAME)s Support <%(PLC_MAIL_SUPPORT_ADDRESS)s>. Do not quote or
759 otherwise include any of this text in any correspondence.
760 """
761          },
762
763         # Boot Manager messages
764         {'message_id': "installfinished",
765          'subject': "%(hostname)s completed installation",
766          'template': """
767 %(hostname)s just completed installation.
768
769 The node should be usable in a couple of minutes if installation was
770 successful.
771 """
772          },
773
774         {'message_id': "insufficientdisk",
775          'subject': "%(hostname)s does not have sufficient disk space",
776          'template': """
777 %(hostname)s failed to boot because it does not have sufficent disk
778 space, or because its disk controller was not recognized.
779
780 Please replace the current disk or disk controller or install
781 additional disks to meet the current hardware requirements.
782 """ + installfailed
783          },
784
785         {'message_id': "insufficientmemory",
786          'subject': "%(hostname)s does not have sufficient memory",
787          'template': """
788 %(hostname)s failed to boot because it does not have sufficent
789 memory.
790
791 Please install additional memory to meet the current hardware
792 requirements.
793 """ + installfailed
794          },
795
796         {'message_id': "authfail",
797          'subject': "%(hostname)s failed to authenticate",
798          'template':
799 """
800 %(hostname)s failed to authenticate for the following reason:
801
802 %(fault)s
803
804 The most common reason for authentication failure is that the
805 authentication key stored in the node configuration file, does not
806 match the key stored in our database.  These keys must match in order to
807 authenticate the node successfully.
808
809 Each time the configuration file is downloaded, either as part of an All-in-One
810 BootImage or by downloading the plnode.txt file, the authentication key is
811 RECREATED.  So, which ever file was downloaded most recently is the one we
812 have in our database.  Often, users will download both the All-in-One image as
813 well as the plnode.txt file, and inadvertently break the boot image.
814
815 To repair this problem, simply download your All-in-One BootImage again, and
816 copy it to the appropriate read-only boot media (write-protected USB or
817 CD-ROM).  
818
819 If you have already performed this step and are still receiving this
820 message, please reply so that we can help investigate the problem.
821 """
822          },
823
824         {'message_id': "notinstalled",
825          'subject': "%(hostname)s is not installed",
826          'template':
827 """
828 %(hostname)s failed to boot because it has either never been
829 installed, or the installation is corrupt.
830
831 Please check if the hard drive has failed, and replace it if so. After
832 doing so, visit:
833
834 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/nodes/?id=%(node_id)d
835
836 Change the 'Boot State' to 'Reinstall', and then 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         {'message_id': "hostnamenotresolve",
844          'subject': "%(hostname)s does not resolve",
845          'template':
846 """
847 %(hostname)s failed to boot because its hostname does not resolve, or
848 does resolve but does not match its configured IP address.
849
850 Please check the network settings for the node, especially its
851 hostname, IP address, and DNS servers, by visiting:
852
853 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/nodes/?id=%(node_id)d
854
855 Correct any errors, and change the 'Boot State' to 'Reinstall', and then
856 reboot the node.
857
858 If you have already performed this step and are still receiving this
859 message, please reply so that we may investigate the problem.
860 """
861          },
862
863         # XXX N.B. I don't think these are necessary, since there's no
864         # way that the Boot Manager would even be able to contact the
865         # API to send these messages.
866
867         {'message_id': "noconfig",
868          'subject': "%(hostname)s does not have a configuration file",
869          'template': """
870 %(hostname)s failed to boot because it could not find a PlanetLab
871 configuration file. To create this file, visit:
872
873 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/nodes/?id=%(node_id)d
874
875 Click the Configuration File link, and save the downloaded file as
876 plnode.txt on either a floppy disk or a USB flash drive.  Change the 
877 'Boot State' to 'Reinstall', and then reboot the node.
878
879 If you have already performed this step and are still receiving this
880 message, please reply so that we may investigate the problem.
881 """
882          },
883
884         {'message_id': "nodetectednetwork",
885          'subject': "%(hostname)s has unsupported network hardware",
886          'template':
887 """
888
889 %(hostname)s failed to boot because it has network hardware that is
890 unsupported by the current production kernel. If it has booted
891 successfully in the past, please try re-installing it by visiting:
892
893 https://%(PLC_WWW_HOST)s:%(PLC_WWW_SSL_PORT)d/db/nodes/?id=%(node_id)d
894
895 Change the 'Boot State' to 'Reinstall', and then reboot the node.
896
897 If you have already performed this step and are still receiving this
898 message, please reply so that we may investigate the problem.
899 """
900          },
901         ]
902
903     for template in message_templates:
904         messages = GetMessages([template['message_id']])
905         if not messages:
906             AddMessage(template)
907
908     
909     ### Setup Initial PCU information
910     pcu_types = [{'model': 'AP79xx',
911           'name': 'APC AP79xx',
912           'pcu_protocol_types': [{ 'port': 80,
913                                   'protocol': 'APC79xxHttp',
914                                   'supported': False},
915                                  { 'port': 23,
916                                   'protocol': 'APC79xx',
917                                   'supported': True},
918                                  { 'port': 22,
919                                   'protocol': 'APC79xx',
920                                   'supported': True}],
921           },
922          {'model': 'Masterswitch',
923           'name': 'APC Masterswitch',
924           'pcu_protocol_types': [{ 'port': 80,
925                                   'protocol': 'APCMasterHttp',
926                                   'supported': False},
927                                  { 'port': 23,
928                                   'protocol': 'APCMaster',
929                                   'supported': True},
930                                  { 'port': 22,
931                                   'protocol': 'APCMaster',
932                                   'supported': True}],
933           },
934          {'model': 'DS4-RPC',
935           'name': 'BayTech DS4-RPC',
936           'pcu_protocol_types': [{ 'port': 80,
937                                   'protocol': 'BayTechHttp',
938                                   'supported': False},
939                                  { 'port': 23,
940                                   'protocol': 'BayTech',
941                                   'supported': True},
942                                  { 'port': 22,
943                                   'protocol': 'BayTech',
944                                   'supported': True}],
945           },
946          {'model': 'IP-41x_IP-81x',
947           'name': 'Dataprobe IP-41x & IP-81x',
948           'pcu_protocol_types': [ { 'port': 23,
949                                   'protocol': 'IPALTelnet',
950                                   'supported': True},
951                                   { 'port': 80,
952                                   'protocol': 'IPALHttp',
953                                   'supported': False}],
954           },
955          {'model': 'DRAC3',
956           'name': 'Dell RAC Version 3',
957           'pcu_protocol_types': [],
958           },
959          {'model': 'DRAC4',
960           'name': 'Dell RAC Version 4',
961           'pcu_protocol_types': [{ 'port': 443,
962                                   'protocol': 'DRACRacAdm',
963                                   'supported': True},
964                                  { 'port': 80,
965                                   'protocol': 'DRACRacAdm',
966                                   'supported': False},
967                                  { 'port': 22,
968                                   'protocol': 'DRAC',
969                                   'supported': True}],
970           },
971          {'model': 'ePowerSwitch',
972           'name': 'ePowerSwitch 1/4/8x',
973           'pcu_protocol_types': [{ 'port': 80,
974                                   'protocol': 'ePowerSwitch',
975                                   'supported': True}],
976           },
977          {'model': 'ilo2',
978           'name': 'HP iLO2 (Integrated Lights-Out)',
979           'pcu_protocol_types': [{ 'port': 443,
980                                   'protocol': 'HPiLOHttps',
981                                   'supported': True},
982                                  { 'port': 22,
983                                   'protocol': 'HPiLO',
984                                   'supported': True}],
985           },
986          {'model': 'ilo1',
987           'name': 'HP iLO version 1',
988           'pcu_protocol_types': [],
989           },
990          {'model': 'PM211-MIP',
991           'name': 'Infratec PM221-MIP',
992           'pcu_protocol_types': [],
993           },
994          {'model': 'AMT2.5',
995           'name': 'Intel AMT v2.5 (Active Management Technology)',
996           'pcu_protocol_types': [],
997           },
998          {'model': 'AMT3.0',
999           'name': 'Intel AMT v3.0 (Active Management Technology)',
1000           'pcu_protocol_types': [],
1001           },
1002          {'model': 'WTI_IPS-4',
1003           'name': 'Western Telematic (WTI IPS-4)',
1004           'pcu_protocol_types': [],
1005           },
1006          {'model': 'unknown',
1007           'name': 'Unknown Vendor or Model',
1008           'pcu_protocol_types': [{ 'port': 443,
1009                                   'protocol': 'UnknownPCU',
1010                                   'supported': False},
1011                                  { 'port': 80,
1012                                   'protocol': 'UnknownPCU',
1013                                   'supported': False},
1014                                  { 'port': 23,
1015                                   'protocol': 'UnknownPCU',
1016                                   'supported': False},
1017                                  { 'port': 22,
1018                                   'protocol': 'UnknownPCU',
1019                                   'supported': False}],
1020           }]
1021
1022     # Get all model names
1023     pcu_models = [type['model'] for type in GetPCUTypes()]
1024     for type in pcu_types:
1025         protocol_types = type['pcu_protocol_types']
1026         # Take this value out of the struct.
1027         del type['pcu_protocol_types']
1028         if type['model'] not in pcu_models:
1029             # Add the name/model info into DB
1030             id = AddPCUType(type)
1031             # for each protocol, also add this.
1032             for ptype in protocol_types:
1033                 AddPCUProtocolType(id, ptype)
1034
1035
1036 if __name__ == '__main__':
1037     main()
1038
1039 # Local variables:
1040 # tab-width: 4
1041 # mode: python
1042 # End: