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