Ticket #184: bcfg2-export-config

File bcfg2-export-config, 4.1 KB (added by gogo, 16 years ago)

implementation example

Line 
1#!/usr/bin/env python
2
3'''TODO'''
4__revision__ = '$Revision: 221 $'
5
6import logging, lxml.etree, Bcfg2.Logging, Bcfg2.Server.Core, Bcfg2.Server.Metadata, Bcfg2.Server.Plugin
7import sys,os,time,errno
8from optparse import OptionParser
9
10def buildConfiguration(core, client):
11  '''Build client configuration.'''
12
13  return core.BuildConfiguration(client)
14
15def write_siggi_entry(user, group, permission, path):
16  '''Write an entry to the configfiles.siggi file which is needed by siggi.'''
17  f = open(outputdir + '/configfiles.siggi', 'a')
18  f.write("%s,%s,%s,%s\n" % (user, group, permission, path))
19  f.close()
20  logger.info("Wrote siggi entry." )
21
22class ConfigFileNotBuild(Exception):
23  def __init__(self, value):
24    self.value = value
25  def __str__(self):
26    return repr(self.value)
27
28
29def handleConfigFileEntry(cfg):
30  '''Store file content of an <ConfigFile name='/path/to/file' ...>...</ConfigFile> entry
31  in the appropriate directory under the output directory.'''
32  name       = cfg.get('name')
33  permission = cfg.get('perms').rjust(4,'0')
34  user       = cfg.get('owner')
35  group      = cfg.get('group')
36
37  logger.info("\nHandling ConfigFile entry %s >>>" % name)
38
39  # directory creation
40  logger.info("Creating directory %s" % ( os.path.dirname(outputdir + name)) )
41  try:
42    os.makedirs(os.path.dirname(outputdir + name))
43  except OSError,err:
44    if err.errno != errno.EEXIST:
45      raise
46  except:
47    logger.error("Fatal error during directory creation!")
48    raise
49
50  # write config file
51  f = open(outputdir + name, "w" )
52  try:
53    f.write(cfg.text)
54  except: # plugin throw an exception and therefore there is no content => None
55    raise ConfigFileNotBuild(name)
56  f.close()
57
58  # write siggi entry
59  try:
60    write_siggi_entry(user, group, permission, name)
61  except:
62    logger.error("Writing entry to configfiles.siggi failed!")
63    raise
64
65  logger.info("<<<")
66
67if __name__ == '__main__':
68  Bcfg2.Logging.setup_logging('export-config-AMS', to_syslog=False)
69  logger = logging.getLogger('export-config-AMS')
70
71  # parse command line options, arguments
72  parser = OptionParser(usage = "%prog [options] client outputdir", version = __revision__)
73  parser.add_option("-c", "--config-file", action="store", dest="configfile", 
74      help="Use given bcfg2.conf file, default: /etc/bcfg2.conf")
75
76  parser.add_option("-f", "--fam-steps", action="store", dest="famsteps",
77      type = "int", help="How many times to handle fam events, default: 10")
78
79  parser.set_defaults(famsteps = 10, configfile="/etc/bcfg2.conf")
80
81  (options, args) = parser.parse_args()
82
83  # ensure client hostname is given
84  if len(args) != 2:
85    parser.error("incorrect number of arguments.")
86
87  client = args[0]
88  outputdir = args[1]
89
90  # stop if output directory exists
91  if os.path.exists(outputdir):
92    logger.error("Output directory already exists, won't override!")
93    raise SystemExit, 1
94
95  logger.info("Generating configuration for %s" % client)
96
97  # load Bcfg2 Core
98  try:
99    logger.debug("Trying to load core...")
100    bcore = Bcfg2.Server.Core.Core({}, options.configfile)
101  except Bcfg2.Server.Core.CoreInitError, msg:
102    logger.error("Core load failed because %s" % msg)
103    raise SystemExit, 1
104  else:
105    logger.debug("Core loaded.")
106
107  # FAM service handling
108  for i in range(options.famsteps):
109    logger.info("FAM service handling: %s to go..." % str(options.famsteps - i) )
110    bcore.fam.Service()
111    time.sleep(0.5)
112
113  # get configuration for client
114  try:
115    client_config = buildConfiguration( bcore, client)
116  except:
117    logger.error("Building client configuration failed. Exiting...")
118    raise SystemExit, 1
119
120  # client could be without a group, not listed in client.xml ...
121  if client_config.tag == 'error':
122    logger.error("Building client configuration failed. Exiting...")
123    raise SystemExit, 1
124
125  # handle <ConfigFile> entries
126  for configfile in [cfile for cfile in client_config.findall(".//ConfigFile")]:
127    try:
128      handleConfigFileEntry(configfile)
129    except ConfigFileNotBuild, e:
130      logger.error("Error: Plugin failed to generate file content for ConfigFile %s !" % e)
131      raise SystemExit, 1
132    except:
133      raise SystemExit, 1