adbd08b7c0455ba0c3434b9a3f0de817bdf7b0f7
[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 g_url = ""
18 def GetMyPLCURL(): return g_url
19 def SetMyPLCURL(url):
20     global g_url
21     g_url = url
22
23 # Get list of existing tag types
24 g_known_tag_types = [tag_type['tagname'] for tag_type in GetTagTypes()]
25 g_known_tag_types.sort()
26
27 def SetTagType(tag_type):
28     global g_known_tag_types
29     # Create/update default slice tag types
30     if tag_type['tagname'] not in g_known_tag_types:
31         AddTagType(tag_type)
32         g_known_tag_types.append(tag_type['tagname'])
33         g_known_tag_types.sort()
34     else:
35         UpdateTagType(tag_type['tagname'], tag_type)
36
37 # Get list of existing (enabled, global) files
38 g_conf_files = GetConfFiles()
39 g_conf_files = filter(lambda conf_file: conf_file['enabled'] and \
40                     not conf_file['node_ids'] and \
41                     not conf_file['nodegroup_ids'],
42                     g_conf_files)
43 g_dests = [conf_file['dest'] for conf_file in g_conf_files]
44 g_conf_files = dict(zip(g_dests, g_conf_files))
45
46 # Get list of existing initscripts
47 g_oldinitscripts = GetInitScripts()
48 g_oldinitscript_names = [script['name'] for script in g_oldinitscripts]
49 g_oldinitscripts = dict(zip(g_oldinitscript_names, g_oldinitscripts))
50
51 def SetInitScript(initscript):
52     global g_oldinitscripts, g_oldinitscript_names
53     if initscript['name'] not in g_oldinitscript_names:
54         initscript_id = AddInitScript(initscript)
55         g_oldinitscript_names.append(initscript['name'])
56         initscript['initscript_id']=initscript_id
57         g_oldinitscripts[initscript['name']]=initscript
58     else:
59         orig_initscript = g_oldinitscripts[initscript['name']]
60         initscript_id = orig_initscript['initscript_id']
61         UpdateConfFile(initscript_id, initscript)
62         
63 def SetConfFile(conf_file):
64     global g_conf_files, g_dests
65     if conf_file['dest'] not in g_dests:
66         AddConfFile(conf_file)
67     else:
68         orig_conf_file = g_conf_files[conf_file['dest']]
69         conf_file_id = orig_conf_file['conf_file_id']
70         UpdateConfFile(conf_file_id, conf_file)
71
72 def SetSlice(slice, tags):
73     # Create or Update slice
74     slices = GetSlices([slice['name']])
75     if len(slices)==1:
76         slice_id = slices[0]['slice_id']
77         UpdateSlice(slice_id, slice)
78     else:
79         AddSlice(slice)
80
81     # Get slice structure with all fields
82     slice = GetSlices([slice['name']])[0]
83
84     # Create/update all tags
85     slice_tags = {}
86     if slice['slice_tag_ids']:
87         # Delete unknown attributes
88         for slice_tag in GetSliceTags(slice['slice_tag_ids']):
89             if (slice_tag['tagname'], slice_tag['value']) not in tags:
90                 DeleteSliceTag(slice_tag['slice_tag_id'])
91             else:
92                 slice_tags[slice_tag['tagname']]=slice_tag['value']
93
94     # only update slice tags that have changed
95     for (name, value) in tags:
96         if name not in slice_tags:
97             AddSliceTag(slice['name'], name, value)            
98         elif value <> slice_tags[name]:
99             UpdateSliceTag(slice['name'],value)
100
101 def SetMessage(message):
102     messages = GetMessages([message['message_id']])
103     if len(messages)==0:
104         AddMessage(message)
105     else:
106         UpdateMessage(message['message_id'],message)
107
108 # Get all model names
109 g_pcu_models = [type['model'] for type in GetPCUTypes()]
110
111 def SetPCUType(pcu_type):
112     global g_pcu_models
113     if 'pcu_protocol_types' in pcu_type:
114         protocol_types = pcu_type['pcu_protocol_types']
115         # Take this value out of the struct.
116         del pcu_type['pcu_protocol_types']
117     else:
118         protocol_types = []
119
120     if pcu_type['model'] not in g_pcu_models:
121         # Add the name/model info into DB
122         id = AddPCUType(pcu_type)
123         # for each protocol, also add this.
124         for ptype in protocol_types:
125             AddPCUProtocolType(id, ptype)
126
127 def GetSnippets(directory):
128     filenames = []
129     if os.path.exists(directory):
130         try:
131             filenames = os.listdir(directory)
132         except OSError, e:
133             raise Exception, "Error when opening %s (%s)" % \
134                   (os.path.join(dir, file), e)
135             
136     ignored = (".bak","~",".rpmsave",".rpmnew",".orig")
137     numberedfiles = {}
138     for filename in filenames:
139         shouldIgnore = False
140         for ignore in ignored:
141             if filename.endswith(ignore):
142                 shouldIgnore = True
143                 break
144
145         if not shouldIgnore:
146             parts = filename.split('-')
147             if len(parts)>=2:
148                 name = '-'.join(parts)
149                 try:
150                     number = int(parts[0])
151                     entry = numberedfiles.get(number,[])
152                     entry.append(name)
153                     numberedfiles[number]=entry
154                 except ValueError:
155                     shouldIgnore = True
156             else:
157                 shouldIgnore = True
158
159         if shouldIgnore:
160             print "db-config: ignoring %s snippet" % filename
161
162     filenames = []
163     keys = numberedfiles.keys()
164     keys.sort()
165     for k in keys:
166         for filename in numberedfiles[k]:
167             filenames.append(filename)
168     return filenames
169
170 def main():
171     cfg = PLCConfiguration()
172     cfg.load()
173     variables = cfg.variables()
174
175     # Load variables into dictionaries
176     for category_id, (category, variablelist) in variables.iteritems():
177         globals()[category_id] = dict(zip(variablelist.keys(),
178                                           [variable['value'] for variable in variablelist.values()]))
179
180     directory="/etc/planetlab/db-config.d"
181     snippets = GetSnippets(directory)
182     for snippet in snippets:
183         fullpath = os.path.join(directory, snippet)
184         execfile(fullpath)
185
186 if __name__ == '__main__':
187     main()
188
189 # Local variables:
190 # tab-width: 4
191 # mode: python
192 # End: