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