- Timestamp:
- 03/28/11 16:48:56 (13 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/sara_cmt/cmt.py
r12458 r12624 89 89 90 90 # Setup the logger for logging 91 loglevel_str = config_parser.get('defaults', 'LOGLEVEL') 92 logger.setLevel(config_parser.getint('loglevels', loglevel_str)) 91 loglevel = config_parser.get('defaults', 'LOGLEVEL') 92 if loglevel == 'NOTSET' and settings.DEBUG == True: 93 logger.setLevel(config_parser.getint('loglevels', 'DEBUG')) 94 else: 95 logger.setLevel(config_parser.getint('loglevels', loglevel)) 93 96 94 97 … … 248 251 249 252 def generate(option, opt_str, value, parser, *args, **kwargs): 250 from sara_cmt.template import CMTTemplate251 253 from django.template import Context 252 254 253 255 # Save full path of templatefile to generate 254 filename = value256 template_filename = value 255 257 256 258 # Make a dict with filenames of the available templates … … 264 266 i+=1 265 267 266 if filename[-4:] != '.cmt':267 filename += '.cmt'268 if template_filename[-4:] != '.cmt': 269 template_filename += '.cmt' 268 270 269 271 # Loop until a valid template has been chosen by the user 270 while filename not in fdict.values():271 logger.warning("File '%s' not known"% filename)272 while template_filename not in fdict.values(): 273 logger.warning("File '%s' not known"%template_filename) 272 274 273 275 # Give a numbered overview of the available templates … … 275 277 print '%s : %s'%(str(key).rjust(2),val) 276 278 logger.debug('fdict: %s'%fdict.values()) 277 filename = raw_input('\nChoose: ')279 template_filename = raw_input('\nChoose: ') 278 280 279 281 # If number given, lookup the filename in the dictionary 280 if filename.isdigit():281 num = int( filename)282 if template_filename.isdigit(): 283 num = int(template_filename) 282 284 if num <= len(fdict): 283 filename = fdict[num]284 logger.debug('filename: %s'% filename)285 template_filename = fdict[num] 286 logger.debug('filename: %s'%template_filename) 285 287 else: 286 288 continue 287 289 # Else check for the extension 288 elif filename[-4:]!='.cmt': 289 filename+='.cmt' 290 291 logger.debug('%s (%s)'%(filename,type(filename))) 292 293 fullpath = os.path.join(settings.CMT_TEMPLATES_DIR, filename) 294 295 # Load the contents of the templatefile as a CMTTemplate 290 elif template_filename[-4:] != '.cmt': 291 template_filename += '.cmt' 292 293 logger.debug('%s (%s)'%(template_filename,type(template_filename))) 294 295 template_fullpath = os.path.join(settings.CMT_TEMPLATES_DIR, template_filename) 296 296 297 try: 297 f = open(fullpath, 'r') 298 templatestr = f.read() 299 f.close() 300 301 template = CMTTemplate(templatestr) 302 303 # Render the CMTTemplate with a Context 298 # Initialize a Context to render the template with 304 299 template_data = {} 305 300 template_data['version'] = CMTSARA_VERSION 306 301 template_data['svn_id'] = '$Id:$' 307 302 template_data['svn_url'] = '$URL:$' 308 template_data['input'] = fullpath 309 template_data['stores'] = { } 310 311 c = Context(template_data) 312 res = template.render(c) 313 314 # While rendering the CMTTemplate there are variables added to the 315 # context, so these can be used for post-processing. 316 317 ### <DEBUG> 318 logger.debug('<RESULT>\n%s'%res) 319 logger.debug('</RESULT>') 320 ### </DEBUG> 303 template_data['input'] = template_fullpath 304 template_data['__template_outputfiles__'] = {} # reserved for data to write to files 305 context = Context(template_data) 306 307 template_data['stores'] = template_data['__template_outputfiles__'] # to stay bw compatible with ramon's code (temporary) 308 309 rendered_string = render_to_string(template_filename, context_instance=context) 310 # While rendering the template there are variables added to the 311 # Context, so these can be used for post-processing. 312 logger.debug('<RESULT>\n%s\n</RESULT>'%rendered_string) 313 321 314 except IOError, e: 322 315 logger.error('Template does not exist: %s' % e) 323 316 324 if not parser.values.DRYRUN: # Write output file(s)325 317 326 c['stores'] = c['stores'] or {c['output']:res} 327 328 for store_file, store_output in c['stores'].items(): 329 330 write_msg = 'Writing outputfile: %s' %store_file 331 created_msg = 'Outputfile(s) created: %s' %store_file 332 318 for outputfile, content in context['__template_outputfiles__'].items(): 319 write_msg = 'Writing outputfile: %s' % outputfile 320 created_msg = 'Outputfile(s) created: %s' % outputfile 321 322 if not parser.values.DRYRUN: # Write output file(s) 333 323 try: 334 324 logger.info(write_msg) 335 f = open( store_file, 'w')336 f.writelines( store_output)325 f = open(outputfile, 'w') 326 f.writelines(content) 337 327 f.close() 338 328 logger.info(created_msg) … … 340 330 logger.error('Failed creating outputfile: %s' % e) 341 331 except KeyError, e: 342 logger.error('No output/stores defined in template') 343 344 else: 345 logger.info('[DRYRUN] Not writing files' ) 346 logger.info('[DRYRUN] Nothing created' ) 332 logger.error('No outputfiles defined in template') 333 else: 334 write_msg = '[DRYRUN] %s' % write_msg 335 created_msg = '[DRYRUN] %s' % created_msg 336 logger.info(write_msg) 337 logger.info(created_msg) 347 338 348 339 if not parser.values.DRYRUN: 349 340 try: 350 for script in c['epilogue']: 351 ### <DEBUG> 352 logger.info('Now executing epilogue script') 353 #logger.debug('<EPILOGUE>') 341 for script in context['epilogue']: 342 logger.info('Executing epilogue script') 354 343 os.system(script) 355 #logger.debug('</EPILOGUE>')356 344 logger.info('Finished epilogue script') 357 ### </DEBUG>358 345 except KeyError, e: 359 logger. info('Did not find an epilogue script')346 logger.debug('No epilogue script found') 360 347 return 361 348 362 349 363 #def mac(option, opt_str, value, parser, *args, **kwargs):364 # """365 # Change the MAC-address of an existing interface.366 # """367 # old_mac, new_mac = value368 #369 # query = {'ent': search_model('interface'),370 # 'get': {'hwaddress': [old_mac]}, 'set': {'hwaddress': [new_mac]}}371 #372 # _object = object_mgr.get_object(query)373 #374 # if _object:375 # logger.debug('Found a unique object matching query: %s' % _object)376 # confirmed = not parser.values.INTERACTIVE or \377 # raw_input('Are you sure? [Yn] ')378 # if confirmed in ['', 'y', 'Y', True]:379 # attr_set_msg = 'Attributes has been set: %s' % _object380 # if not parser.values.DRYRUN:381 # _object.setattrs_from_dict(query['set'])382 # logger.debug(attr_set_msg)383 # else:384 # logger.debug('[DRYRUN] %s' % attr_set_msg)385 # else:386 # logger.info('Change of MAC-address has been cancelled')387 # else:388 # logger.error('Unable to execute this request')389 390 #391 # </Database related methods>392 #393 #####394 395 396 350 ##### 397 351 # 398 352 # <Methods for processing of arguments> 399 353 # 400 #def collect_args(option):401 354 402 355 … … 495 448 The query, which consists out of one or more terms, is 496 449 used to make a selection of objects to list.""") 497 # parser.add_option('-m', '--mac',498 # action='callback',499 # callback=mac,500 # type='string',501 # metavar='<old MAC> <new MAC>',502 # nargs=2,503 # help='Change the MAC-address of an interface')504 450 parser.add_option('-r', '--remove', 505 451 action='callback',
Note: See TracChangeset
for help on using the changeset viewer.