forj 0.0.36 → 0.0.37

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,293 +0,0 @@
1
- #!/bin/env python
2
- #
3
- # (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
4
- #
5
- # Licensed under the Apache License, Version 2.0 (the "License");
6
- # you may not use this file except in compliance with the License.
7
- # You may obtain a copy of the License at
8
- #
9
- # http://www.apache.org/licenses/LICENSE-2.0
10
- #
11
- # Unless required by applicable law or agreed to in writing, software
12
- # distributed under the License is distributed on an "AS IS" BASIS,
13
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- # See the License for the specific language governing permissions and
15
- # limitations under the License.
16
-
17
- # This script is used to create a env file used by build.sh.
18
- # It is based on Maestro/templates/infra/maestro.box.GITBRANCH.env.tmpl
19
-
20
- # This script detects few tags, and ask to enter the appropriate vallue,
21
- # then save the result to a directory given by the user.
22
-
23
- # As this script is very early in the boot process, we are running on end user worstation.
24
- # We will avoid adding non default module like:
25
- # - ptemplates, django for template interpreter. We use our own simple code to make it work with basics rules.
26
- # It provides variable detection, with comments and default variables.
27
-
28
- import sys
29
- import getopt
30
- #import urllib2
31
- #from urlparse import urlparse,ParseResult
32
- import re
33
- import logging
34
- import logging.handlers
35
- import yaml
36
- import os
37
- #import subprocess
38
- #import distutils.spawn
39
- #import string
40
- #from datetime import date,datetime
41
- #import time
42
- #import tempfile
43
- import readline
44
-
45
- # Defining defaults
46
-
47
- GITBRANCH='master'
48
- MAESTRO_RPATH_TMPL="templates/infra/"
49
- MAESTRO_TMPL_FILE="maestro.box.GITBRANCH.env.tmpl"
50
- MAESTRO_TMPL_PROVIDER='hpcloud'
51
-
52
- #
53
- #
54
-
55
- ##############################
56
- def help(sMsg):
57
- print 'build-env.py [-h|--help] --maestro-repo MaestroPath --env-path BuildEnvPath [--gitbranch BranchName] [-d|--debug] [-v|--verbose]'
58
-
59
- # TODO Support for re-build it.
60
-
61
- ##############################
62
- # TODO: split this function in 3, for code readibility
63
-
64
- def BuildEnv(EnvPath, MaestroFile, MaestroPath, GitBranch):
65
- """Build env file if doesn't exist."""
66
-
67
- global MAESTRO_TMPL_FILE
68
- oLogging=logging.getLogger('build-env')
69
-
70
- # -----------------------------------------------
71
- # Check step ------------------------------------
72
-
73
- if not os.path.exists(EnvPath):
74
- oLogging.error("'%s' do not exist. This directory is required. (--env-path)", EnvPath)
75
- sys.exit(1)
76
-
77
- if not os.path.isdir(EnvPath):
78
- oLogging.error("'%s' is not a valid directory (--env_path)", EnvPath)
79
- sys.exit(1)
80
-
81
- if not os.path.isdir(MaestroPath):
82
- oLogging.error("'%s' is not a valid directory. Should refer to Maestro repository root dir.(--maestro-path)", MaestroPath)
83
- sys.exit(1)
84
-
85
-
86
- sInputFile=os.path.join(MaestroPath, MaestroFile)
87
- if not os.path.exists(sInputFile):
88
- oLogging.error("Unable to find template '%s' from '%s'. Are you sure about Maestro Repository root path given? Check and retry.", MaestroPath, MaestroFile)
89
- sys.exit(1)
90
-
91
- # Replace GITBRANCH Name by real git branch value.
92
- sOutputFile=os.path.join(EnvPath,re.sub('GITBRANCH',GITBRANCH,MAESTRO_TMPL_FILE))
93
- sOutputFile=re.sub('.tmpl$','',sOutputFile)
94
-
95
- if os.path.exists(sOutputFile):
96
- # TODO Support for re-build it.
97
- oLogging.info("'%s' exists. If you want to rewrite it, remove the file before.", sOutputFile)
98
- sys.exit(0)
99
-
100
- # Load template variables and build list of variable to query
101
- oLogging.debug("Opening template '%s'",sInputFile)
102
- try:
103
- fTmpl=open(sInputFile)
104
- except IOError as e:
105
- oLogging.error("Unable to open '%s'. Errno: %s (%s)", sInputFile, e.errno, e.strerror)
106
- sys.exit(2)
107
-
108
- # -----------------------------------------------
109
- # Reading template ------------------------------
110
-
111
- print("Reading template '{0}'".format(sInputFile))
112
- oComments={}
113
- oVars={}
114
-
115
- # Search for Variable. If the variable name ends with '!', this value could not be null.
116
- reVar=re.compile('[^$]{([A-Z_-]+)(!)?(:.*?)?}')
117
- # 1: Variable Name
118
- # 2: Required if = '!'
119
- # 3: Default
120
-
121
-
122
- # Search for comment
123
- reComment=re.compile('^ *# +([A-Z_-]+): (.*)$')
124
-
125
- for line in fTmpl:
126
-
127
- # Detecting comment
128
- oComment=reComment.search(line)
129
- if oComment <> None:
130
- oLogging.debug('Found "%s" = "%s"', oComment.group(1), oComment.group(2))
131
- if oVars.has_key(oComment.group(1)):
132
- oComments[oComment.group(1)]=oVars[oVar.group(1)]['comments']+'\n# '+oComment.group(2)
133
- elif oComments.has_key(oComment.group(1)):
134
- oComments[oComment.group(1)]=oComments[oComment.group(1)]+'\n# '+ oComment.group(2)
135
- else:
136
- oComments[oComment.group(1)]='# '+oComment.group(2)
137
-
138
- oVar=reVar.search(line)
139
- if oVar <> None:
140
- oLogging.debug('Found var "%s" from "%s"',oVar.group(1),line)
141
-
142
- sComment=''
143
- if oComments.has_key(oVar.group(1)):
144
- sComment=oComments[oVar.group(1)]
145
- else:
146
- oComments.remove(oVar.group(1))
147
-
148
- sDefault=''
149
- bRequired=False
150
- if oVar.group(2) <> None :
151
- bRequired=True
152
- oLogging.debug("'%s' is required",oVar.group(1))
153
- if oVar.group(3) <> None:
154
- sDefault=oVar.group(3)[1:]
155
- oLogging.debug("'%s' default value is '%s'",oVar.group(1),sDefault)
156
-
157
-
158
- oVars[oVar.group(1)]={ 'comments': sComment,
159
- 'required': bRequired,
160
- 'default': sDefault }
161
-
162
- oLogging.debug('template loaded.')
163
-
164
- # -----------------------------------------------
165
- # Ask section -----------------------------------
166
-
167
- print "We need some information from you. Please ask the following question:\n"
168
- # Time to ask information to the user.
169
-
170
- for sElem in oVars:
171
- print '{0}'.format(oVars[sElem]['comments'])
172
- sPar="# "
173
- if oVars[sElem]['default'] <> '':
174
- sPar+='Default is "'+oVars[sElem]['default']+'".'
175
- if oVars[sElem]['required'] :
176
- if sPar <> "# " :
177
- sPar+=' Required.'
178
- else:
179
- sPar='# Required.'
180
-
181
- if sPar <> "":
182
- print sPar
183
- sValue=""
184
-
185
- while sValue == "":
186
- sValue=raw_input(sElem+'=')
187
-
188
- if sValue == "":
189
- sValue=oVars[sElem]['default']
190
-
191
- if oVars[sElem]['required']:
192
- if sValue == "":
193
- print "Value required. Please enter a value."
194
- else:
195
- break
196
-
197
- oVars[sElem]['value']=sValue
198
- print '{0}="{1}"\n'.format(sElem,sValue)
199
-
200
-
201
- fTmpl.seek(0) # Read the file again to replace data
202
- try:
203
- fOutputFile=open(sOutputFile,"w+")
204
- except IOError as e:
205
- oLogging.error("Unable to open '%s' for write. Errno: %s (%s)", sOutputFile, e.errno, e.strerror)
206
- sys.exit(2)
207
-
208
- print "--------------------------------\nThank you\nWriting '{0}'".format(sOutputFile)
209
-
210
- # -----------------------------------------------
211
- # Time to save the template. --------------------
212
-
213
- reReplaced=re.compile('([^$])({([A-Z_-]+)(!)?(:.*?)?})')
214
- for line in fTmpl:
215
- oVar=reReplaced.search(line)
216
-
217
- if oVar <> None:
218
-
219
- if oVar.group(1) <> None:
220
- sValue=oVar.group(1)+oVars[oVar.group(3)]['value']
221
- else:
222
- sValue=oVars[oVar.group(3)]['value']
223
- sNewLine=reReplaced.sub(sValue,line)
224
- else:
225
- sNewLine=line
226
-
227
- sys.stdout.flush()
228
- fOutputFile.write(sNewLine)
229
-
230
- fOutputFile.close()
231
- fTmpl.close()
232
- print 'Done'
233
-
234
-
235
-
236
- ##############################
237
- def main(argv):
238
- """Main function"""
239
-
240
- global GITBRANCH
241
- global MAESTRO_TMPL_PROVIDER
242
- global MAESTRO_RPATH_TMPL
243
-
244
- oLogging=logging.getLogger('build-env')
245
- oLogging.setLevel(20)
246
-
247
- try:
248
- opts,args = getopt.getopt(argv,"hp:vd:r:P:", ["help", "--for-provider=", "env-path=" , "maestro-path=" ,"debug" ,"verbose" ])
249
- except getopt.GetoptError, e:
250
- oLogging.error('Error: '+e.msg)
251
- help()
252
- sys.exit(2)
253
-
254
- for opt, arg in opts:
255
- if opt in ('-h', '--help'):
256
- help()
257
- sys.exit()
258
- elif opt in ('-v','--verbose'):
259
- if oLogging.level >20:
260
- oLogging.setLevel(oLogging.level-10)
261
- elif opt in ('--debug','-d'):
262
- logging.getLogger().setLevel(logging.DEBUG)
263
- logging.debug("Setting debug mode")
264
- oLogging.setLevel(logging.DEBUG)
265
- elif opt in ('-p', '--env-path'):
266
- ENV_PATH=arg
267
- elif opt in ('--gitbranch'):
268
- GITBRANCH=arg
269
- elif opt in ('-r','--maestro-path'):
270
- MAESTRO_PATH=arg
271
- elif opt in ('-P','--for-provider'):
272
- TMPL_PROVIDER=arg
273
-
274
- # Start Main tasks - Testing required variables.
275
- if not 'ENV_PATH' in locals() or not 'MAESTRO_PATH' in locals():
276
- oLogging.error("--env-path or --maestro-path values missing. Please check command flags.")
277
- sys.exit(1)
278
-
279
-
280
- global MAESTRO_TMPL_FILE # template file to use.
281
-
282
- sMaestroFile=os.path.join(MAESTRO_RPATH_TMPL, MAESTRO_TMPL_PROVIDER+'-'+MAESTRO_TMPL_FILE)
283
- BuildEnv(ENV_PATH, sMaestroFile, MAESTRO_PATH, GITBRANCH)
284
-
285
- sys.exit(0)
286
-
287
- #####################################
288
- logging.basicConfig(format='%(asctime)s: %(levelname)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
289
-
290
- if __name__ == "__main__":
291
- main(sys.argv[1:])
292
-
293
-