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