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