Example #1
0
    def take_action(self, args):
        configp = self.fetch_config(args)

        conf = FormatConfig(logger=self.app.log)

        conf.mergeConfig(args, configp)

        # Parse if we have to check if running from root
        # XXX document this feature.
        if string_to_boolean(getattr(conf, 'root_check', 'True').lower()):
          check_root_user(self)

        if not self.app.options.log_file and conf.log_file:
            # no log file is provided by argparser,
            # we set up the one from config
            file_handler = logging.FileHandler(conf.log_file)
            formatter = logging.Formatter(self.app.LOG_FILE_MESSAGE_FORMAT)
            file_handler.setFormatter(formatter)
            self.app.log.addHandler(file_handler)

        try:
            conf.setConfig()
        except UsageError as err:
            sys.stderr.write(err.message + '\n')
            sys.stderr.write("For help use --help\n")
            sys.exit(1)

        tracing_monkeypatch(conf)

        do_format(conf=conf)
Example #2
0
    def take_action(self, args):
        configp = self.fetch_config(args) # read the options in .cfg

        conf = FormatConfig(logger=self.app.log)

        conf.mergeConfig(args, configp) # commandline options overwrite .cfg options

        # Parse if we have to check if running from root
        # XXX document this feature.
        if string_to_boolean(getattr(conf, 'root_check', 'True').lower()):
          check_root_user(self)

        if len(self.app.log.handlers) == 0 and not self.app.options.log_file and conf.log_file:
            # This block is called again if "slapos node boot" failed.
            # Don't add a handler again, otherwise the output becomes double.
            #
            # no log file is provided by argparser,
            # we set up the one from config
            file_handler = logging.FileHandler(conf.log_file)
            formatter = logging.Formatter(self.app.LOG_FILE_MESSAGE_FORMAT)
            file_handler.setFormatter(formatter)
            self.app.log.addHandler(file_handler)

        try:
            conf.setConfig()
        except UsageError as err:
            sys.stderr.write(err.message + '\n')
            sys.stderr.write("For help use --help\n")
            sys.exit(1)

        tracing_monkeypatch(conf)

        do_format(conf=conf)
Example #3
0
    def take_action(self, args):
        configp = self.fetch_config(args)

        conf = FormatConfig(logger=self.app.log)

        conf.mergeConfig(args, configp)

        if not self.app.options.log_file and conf.log_file:
            # no log file is provided by argparser,
            # we set up the one from config
            file_handler = logging.FileHandler(conf.log_file)
            formatter = logging.Formatter(self.app.LOG_FILE_MESSAGE_FORMAT)
            file_handler.setFormatter(formatter)
            self.app.log.addHandler(file_handler)

        try:
            conf.setConfig()
        except UsageError as err:
            sys.stderr.write(err.message + '\n')
            sys.stderr.write("For help use --help\n")
            sys.exit(1)

        tracing_monkeypatch(conf)

        do_format(conf=conf)
Example #4
0
def do_configure(args, fetch_config_func, logger):
    """
    Generate configuration files,
    Create the instance path by running slapformat (but will crash),
    Add proxy to supervisor,
    Run supervisor, which will run the proxy,
    Run format, which will finish correctly.
    """
    slapos_node_config_path = os.path.join(
        args.slapos_configuration_directory, 'slapos.cfg')
    if os.path.exists(slapos_node_config_path):
        logger.error('A SlapOS configuration directory already exist at'
                     ' %s. Aborting.' % slapos_node_config_path)
        raise SystemExit(1)
    if not getattr(args, 'cfg', None):
        args.cfg = slapos_node_config_path
    _createConfigurationDirectory(args.slapos_configuration_directory)
    _generateSlaposNodeConfigurationFile(slapos_node_config_path, args)
    configp = fetch_config_func(args)
    conf = FormatConfig(logger=logger)
    conf.mergeConfig(args, configp)
    # The First thing we have to do here is to generate slapproxy conf
    # for supervisord, then supervisord certainly start slapproxy.
    proxy_configuration_file = _generateSlaposProxyConfigurationFile(conf)
    conf.proxy_configuration_file = proxy_configuration_file
    _addProxyToSupervisor(conf)
    # Do the rest
    slapgrid = create_slapgrid_object(conf.__dict__, logger)
    createPrivateDirectory(os.path.join(conf.slapos_buildout_directory, 'log'))
    _runFormat(conf.slapos_buildout_directory)
    slapgrid.checkEnvironmentAndCreateStructure()
    home_folder_path = os.environ['HOME']
    createPrivateDirectory("%s/.slapos" % home_folder_path)
    slapos_client_cfg_path = '%s/.slapos/slapos-client.cfg' % home_folder_path
    if not os.path.exists(slapos_client_cfg_path):
        os.symlink(slapos_node_config_path, slapos_client_cfg_path)
    launchSupervisord(instance_root=conf.instance_root, logger=logger)
    _runFormat(conf.slapos_buildout_directory)
    return 0
Example #5
0
def main(*args):
  "Run default configuration."

  ap = argparse.ArgumentParser()

  ap.add_argument('-x', '--computer_xml',
                  help="Path to file with computer's XML. If does not exists, will be created",
                  default=None)

  ap.add_argument('--computer_json',
                  help="Path to a JSON version of the computer's XML (for development only).",
                  default=None)

  ap.add_argument('-l', '--log_file',
                  help="The path to the log file used by the script.")

  ap.add_argument('-i', '--input_definition_file',
                  help="Path to file to read definition of computer instead of "
                  "declaration. Using definition file allows to disable "
                  "'discovery' of machine services and allows to define computer "
                  "configuration in fully controlled manner.")

  ap.add_argument('-o', '--output_definition_file',
                  help="Path to file to write definition of computer from "
                  "declaration.")

  ap.add_argument('-n', '--dry_run',
                  help="Don't actually do anything.",
                  default=False,
                  action="store_true")

  ap.add_argument('-v', '--verbose',
                  default=False,
                  action="store_true",
                  help="Verbose output.")

  # the console option is actually ignored and not used anymore.
  ap.add_argument('-c', '--console',
                  default=False,
                  action="store_true",
                  help="Console output.")

  ap.add_argument('--alter_user',
                  choices=['True', 'False'],
                  help="Shall slapformat alter user database [default: True]")

  ap.add_argument('--alter_network',
                  choices=['True', 'False'],
                  help="Shall slapformat alter network configuration [default: True]")

  ap.add_argument('--now',
                  help="Launch slapformat without delay",
                  default=False,
                  action="store_true")

  ap.add_argument('configuration_file',
                  help='path to slapos.cfg')

  if args:
    args = ap.parse_args(list(args))
  else:
    args = ap.parse_args()

  logger = logging.getLogger("slapformat")
  logger.addHandler(logging.StreamHandler())

  if args.verbose:
    logger.setLevel(logging.DEBUG)
    logger.debug("Verbose mode enabled.")
  else:
    logger.setLevel(logging.INFO)

  conf = FormatConfig(logger=logger)

  configp = ConfigParser.SafeConfigParser()
  if configp.read(args.configuration_file) != [args.configuration_file]:
    raise UsageError('Cannot find or parse configuration file: %s' % args.configuration_file)

  conf.mergeConfig(args, configp)

  if conf.log_file:
    if not os.path.isdir(os.path.dirname(conf.log_file)):
      # fallback to console only if directory for logs does not exists and
      # continue to run
      raise ValueError('Please create directory %r to store %r log file' % (
        os.path.dirname(conf.log_file), conf.log_file))
    else:
      file_handler = logging.FileHandler(conf.log_file)
      file_handler.setFormatter(logging.Formatter("%(asctime)s - "
        "%(name)s - %(levelname)s - %(message)s"))
      conf.logger.addHandler(file_handler)
      conf.logger.info('Configured logging to file %r' % conf.log_file)

  try:
    conf.setConfig()
  except UsageError as exc:
    sys.stderr.write(exc.message + '\n')
    sys.stderr.write("For help use --help\n")
    sys.exit(1)

  tracing_monkeypatch(conf)

  try:
    do_format(conf=conf)
  except:
    conf.logger.exception('Uncaught exception:')
    raise