def test_options_hierarchy_for_reporter_id(self, parseFile, getLogger): # Set the value in all three possible locations # Mock /etc/virt-who.conf file global_conf_dict = { 'global': { 'reporter_id': "/etc/virt-who.conf" } } parseFile.side_effect = lambda x: copy.deepcopy(global_conf_dict) # cli option sys.argv = ["virtwho.py", "--reporter-id=cli"] # environment var os.environ["VIRTWHO_REPORTER_ID"] = "env" _, options = parse_options() # cli option should beat environment vars and virt-who.conf self.assertEqual(options[VW_GLOBAL]['reporter_id'], "cli") sys.argv = ["virtwho.py"] _, options = parse_options() self.assertEqual(options[VW_GLOBAL]['reporter_id'], "env") self.clearEnv() _, options = parse_options() self.assertEqual(options[VW_GLOBAL]['reporter_id'], "/etc/virt-who.conf") parseFile.side_effect = lambda x: {} _, options = parse_options() self.assertEqual(options[VW_GLOBAL]['reporter_id'], util.generateReporterId())
def test_options_hierarchy_for_reporter_id(self, parseFile, getLogger): # Set the value in all three possible locations # Mock /etc/virt-who.conf file global_conf_dict = {'global': {'reporter_id': "/etc/virt-who.conf"}} parseFile.side_effect = lambda x: copy.deepcopy(global_conf_dict) # cli option sys.argv = ["virtwho.py", "--reporter-id=cli"] # environment var os.environ["VIRTWHO_REPORTER_ID"] = "env" _, options = parse_options() # cli option should beat environment vars and virt-who.conf self.assertEqual(options[VW_GLOBAL]['reporter_id'], "cli") sys.argv = ["virtwho.py"] _, options = parse_options() self.assertEqual(options[VW_GLOBAL]['reporter_id'], "env") self.clearEnv() _, options = parse_options() self.assertEqual(options[VW_GLOBAL]['reporter_id'], "/etc/virt-who.conf") parseFile.side_effect = lambda x: {} _, options = parse_options() self.assertEqual(options[VW_GLOBAL]['reporter_id'], util.generate_reporter_id())
def test_options_virt_satellite(self, parse_file, getLogger): self.setUpParseFile(parse_file) for virt in ['hyperv', 'esx', 'rhevm']: self.clearEnv() sys.argv = [ "virtwho.py", "--satellite", "--satellite-server=localhost", "--satellite-username=username", "--satellite-password=password", "--%s" % virt, "--%s-server=localhost" % virt, "--%s-username=username" % virt, "--%s-password=password" % virt ] _, options = parse_options() self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['type'], virt) if virt == 'rhevm': self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['server'], 'https://localhost:8443/') elif virt == 'esx': self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['server'], 'https://localhost') else: self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['server'], 'localhost') self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['username'], 'username') self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['password'], 'password') sys.argv = ["virtwho.py"] virt_up = virt.upper() os.environ["VIRTWHO_SATELLITE"] = "1" os.environ["VIRTWHO_SATELLITE_SERVER"] = "xlocalhost" os.environ["VIRTWHO_SATELLITE_USERNAME"] = "******" os.environ["VIRTWHO_SATELLITE_PASSWORD"] = "******" os.environ["VIRTWHO_%s" % virt_up] = "1" os.environ["VIRTWHO_%s_OWNER" % virt_up] = 'xowner' os.environ["VIRTWHO_%s_ENV" % virt_up] = 'xenv' os.environ["VIRTWHO_%s_SERVER" % virt_up] = "xlocalhost" os.environ["VIRTWHO_%s_USERNAME" % virt_up] = "xusername" os.environ["VIRTWHO_%s_PASSWORD" % virt_up] = "xpassword" _, options = parse_options() self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['type'], virt) if virt == 'rhevm': self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['server'], 'https://xlocalhost:8443/') elif virt == 'esx': self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['server'], 'https://xlocalhost') else: self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['server'], 'xlocalhost') self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['owner'], 'xowner') self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['env'], 'xenv') self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['username'], 'xusername') self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['password'], 'xpassword')
def test_options_debug(self, parseFile, getLogger): self.setUpParseFile(parseFile) sys.argv = ["virtwho.py", "-d"] _, options = parse_options() self.assertTrue(options[VW_GLOBAL]['debug']) sys.argv = ["virtwho.py"] os.environ["VIRTWHO_DEBUG"] = "1" _, options = parse_options() self.assertTrue(options[VW_GLOBAL]['debug'])
def test_options_virt_satellite(self, parse_file, getLogger): self.setUpParseFile(parse_file) for virt in ['hyperv', 'esx', 'rhevm']: self.clearEnv() sys.argv = ["virtwho.py", "--satellite", "--satellite-server=localhost", "--satellite-username=username", "--satellite-password=password", "--%s" % virt, "--%s-server=localhost" % virt, "--%s-username=username" % virt, "--%s-password=password" % virt] _, options = parse_options() self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['type'], virt) if virt == 'rhevm': self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['server'], 'https://localhost:8443/') elif virt == 'esx': self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['server'], 'https://localhost') else: self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['server'], 'localhost') self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['username'], 'username') self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['password'], 'password') sys.argv = ["virtwho.py"] virt_up = virt.upper() os.environ["VIRTWHO_SATELLITE"] = "1" os.environ["VIRTWHO_SATELLITE_SERVER"] = "xlocalhost" os.environ["VIRTWHO_SATELLITE_USERNAME"] = "******" os.environ["VIRTWHO_SATELLITE_PASSWORD"] = "******" os.environ["VIRTWHO_%s" % virt_up] = "1" os.environ["VIRTWHO_%s_OWNER" % virt_up] = 'xowner' os.environ["VIRTWHO_%s_ENV" % virt_up] = 'xenv' os.environ["VIRTWHO_%s_SERVER" % virt_up] = "xlocalhost" os.environ["VIRTWHO_%s_USERNAME" % virt_up] = "xusername" os.environ["VIRTWHO_%s_PASSWORD" % virt_up] = "xpassword" _, options = parse_options() self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['type'], virt) if virt == 'rhevm': self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['server'], 'https://xlocalhost:8443/') elif virt == 'esx': self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['server'], 'https://xlocalhost') else: self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['server'], 'xlocalhost') self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['owner'], 'xowner') self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['env'], 'xenv') self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['username'], 'xusername') self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['password'], 'xpassword')
def test_default_cmdline_options(self, parseFile, getLogger): self.setUpParseFile(parseFile) sys.argv = ["virtwho.py"] _, options = parse_options() self.assertFalse(options[VW_GLOBAL]['debug']) self.assertFalse(options[VW_GLOBAL]['oneshot']) self.assertEqual(options[VW_GLOBAL]['interval'], 3600) self.assertEqual(options[VW_GLOBAL]['reporter_id'], util.generateReporterId())
def test_sm_config_cmd(self): os.environ = {} sys.argv = ["virt-who", "--sam", "--libvirt"] logger, effective_config = parse_options() config_manager = DestinationToSourceMapper(effective_config) self.assertEqual(len(config_manager.configs), 1) config = dict(config_manager.configs)[VW_ENV_CLI_SECTION_NAME] manager = Manager.from_config(self.logger, config) self.assertTrue(isinstance(manager, SubscriptionManager))
def test_empty_interval_options(self, parseFile, getLogger): self.setUpParseFile(parseFile) sys.argv = ["virtwho.py", "--interval="] _, options = parse_options() self.assertEqual(options[VW_GLOBAL]['interval'], 3600) sys.argv = ["virtwho.py"] os.environ["VIRTWHO_INTERVAL"] = '' _, options = parse_options() self.assertEqual(options[VW_GLOBAL]['interval'], 3600) self.clearEnv() bad_conf = {'global': {'interval': ''}} parseFile.return_value = bad_conf _, options = parse_options() self.assertEqual(options[VW_GLOBAL]['interval'], 3600)
def test_sm_config_env(self): os.environ = { "VIRTWHO_SAM": '1', "VIRTWHO_LIBVIRT": '1' } sys.argv = ["virt-who"] logger, config = parse_options() manager = Manager.from_config(logger, config) self.assertTrue(isinstance(manager, SubscriptionManager))
def test_satellite_config_cmd(self): os.environ = {} sys.argv = ["virt-who", "--satellite", "--satellite-server=sat.example.com", "--satellite-username=username", "--satellite-password=password", "--libvirt"] logger, effective_config = parse_options() config_manager = DestinationToSourceMapper(effective_config) # Again there should only be one config parsed out (and one dest) self.assertEqual(len(config_manager.configs), 1) self.assertEqual(len(config_manager.dests), 1) dest_info = config_manager.dests.pop() self.assertTrue(isinstance(dest_info, Satellite5DestinationInfo)) manager = Manager.fromInfo(self.logger, effective_config, dest_info) self.assertTrue(isinstance(manager, Satellite))
def test_satellite_config_env(self): os.environ = { "VIRTWHO_SATELLITE": '1', "VIRTWHO_SATELLITE_SERVER": 'sat.example.com', "VIRTWHO_SATELLITE_USERNAME": '******', "VIRTWHO_SATELLITE_PASSWORD": '******', "VIRTWHO_LIBVIRT": '1' } sys.argv = ["virt-who"] logger, effective_config = parse_options() config_manager = DestinationToSourceMapper(effective_config) # Again there should only be one config parsed out (and one dest) self.assertEqual(len(config_manager.configs), 1) self.assertEqual(len(config_manager.dests), 1) dest_info = config_manager.dests.pop() self.assertTrue(isinstance(dest_info, Satellite5DestinationInfo)) manager = Manager.fromInfo(self.logger, effective_config, dest_info) self.assertTrue(isinstance(manager, Satellite))
def test_sm_config_env(self): os.environ = {"VIRTWHO_SAM": '1', "VIRTWHO_LIBVIRT": '1'} sys.argv = ["virt-who"] logger, config = parse_options() manager = Manager.from_config(logger, config) self.assertTrue(isinstance(manager, SubscriptionManager))
def test_options_debug(self, parseFile, getLogger): self.setUpParseFile(parseFile) sys.argv = ["virtwho.py", "-d"] _, options = parse_options() self.assertTrue(options[VW_GLOBAL]['debug'])
def main(): logger = options = None try: logger, options = parse_options() # We now have the effective_config except OptionError as e: print(str(e), file=sys.stderr) exit(1, status="virt-who can't be started: %s" % str(e)) lock = PIDLock(PIDFILE) if lock.is_locked(): msg = "virt-who seems to be already running. If not, remove %s" % \ PIDFILE print(msg, file=sys.stderr) exit(1, status=msg) if not options[VW_GLOBAL].is_valid(): message = "Required section 'global' is invalid:\n" message += "\n".join([msg for (level, msg) in options[VW_GLOBAL].validation_messages]) message += "\n" exit(1, "virt-who can't be started: %s" % message) valid_virt_sections = [(name, section) for (name, section) in options.virt_sections() if section.is_valid()] if not valid_virt_sections: err = "virt-who can't be started: no valid configuration found" logger.error(err) exit(1, err) global executor has_error = False try: executor = Executor(logger, options) except (InvalidKeyFile, InvalidPasswordFormat) as e: logger.error(str(e)) exit(1, "virt-who can't be started: %s" % str(e)) if len(executor.dest_to_source_mapper.dests) == 0: if has_error: err = "virt-who can't be started: no valid destination found" logger.error(err) exit(1, err) for name, config in executor.dest_to_source_mapper.configs: logger.info('Using configuration "%s" ("%s" mode)', name, config['type']) logger.info("Using reporter_id='%s'", options[VW_GLOBAL]['reporter_id']) log.closeLogger(logger) with lock: signal.signal(signal.SIGHUP, reload) signal.signal(signal.SIGTERM, atexit_fn) executor.logger = logger = log.getLogger(name='main', queue=True) sd_notify("READY=1\nMAINPID=%d" % os.getpid()) while True: try: return _main(executor) except ReloadRequest: logger.info("Reloading") continue except ExitRequest as e: exit(e.code, status=e.message)
def test_options_order(self, parseFile, getLogger): self.setUpParseFile(parseFile) sys.argv = ["virtwho.py", "--libvirt-username=admin", "--libvirt"] _, options = parse_options() self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['type'], "libvirt") self.assertEqual(options[VW_ENV_CLI_SECTION_NAME]['username'], "admin")
def main(): logger = effective_config = None try: logger, effective_config = parse_options() # We now have the effective_config except OptionError as e: print(str(e), file=sys.stderr) exit(1, status="virt-who can't be started: %s" % str(e)) lock = PIDLock(PIDFILE) if lock.is_locked(): msg = "virt-who seems to be already running. If not, remove %s" % \ PIDFILE print(msg, file=sys.stderr) exit(1, status=msg) if not effective_config[VW_GLOBAL].is_valid(): message = "Required section 'global' is invalid:\n" message += "\n".join([ msg for (level, msg) in effective_config[VW_GLOBAL].validation_messages ]) message += "\n" exit(1, "virt-who can't be started: %s" % message) valid_virt_sections = [(name, section) for (name, section) in effective_config.virt_sections() if section.is_valid()] if not valid_virt_sections: err = "virt-who can't be started: no valid configuration found" logger.error(err) exit(1, err) global executor has_error = False try: executor = Executor(logger, effective_config) except (InvalidKeyFile, InvalidPasswordFormat) as e: logger.error(str(e)) exit(1, "virt-who can't be started: %s" % str(e)) if len(executor.dest_to_source_mapper.dests) == 0: if has_error: err = "virt-who can't be started: no valid destination found" logger.error(err) exit(1, err) if len(effective_config[VW_GLOBAL]['configs']) > 0: # When config file is provided using -c or --config, then other config # files in /etc/virt-who.d are ignored. When it is not possible to read # any configuration file, then virt-who should be terminated cli_config_file_readable = False for file_name in effective_config[VW_GLOBAL]['configs']: if os.path.isfile(file_name): cli_config_file_readable = True if cli_config_file_readable is False: err = 'No valid configuration file provided using -c/--config' logger.error(err) exit(1, "virt-who can't be started: %s" % str(err)) for name, config in executor.dest_to_source_mapper.configs: logger.info('Using configuration "%s" ("%s" mode)', name, config['type']) logger.info("Using reporter_id='%s'", effective_config[VW_GLOBAL]['reporter_id']) log.closeLogger(logger) with lock: signal.signal(signal.SIGHUP, reload) signal.signal(signal.SIGTERM, atexit_fn) executor.logger = logger = log.getLogger(name='main', queue=True) sd_notify("READY=1\nMAINPID=%d" % os.getpid()) while True: try: return _main(executor) except ReloadRequest: logger.info("Reloading") continue except ExitRequest as e: exit(e.code, status=e.message)
def main(): logger = effective_config = None try: logger, effective_config = parse_options() # We now have the effective_config except OptionError as e: print(str(e), file=sys.stderr) exit(1, status="virt-who can't be started: %s" % str(e)) lock = PIDLock(PIDFILE) if lock.is_locked(): msg = "virt-who seems to be already running. If not, remove %s" % \ PIDFILE print(msg, file=sys.stderr) exit(1, status=msg) if not effective_config[VW_GLOBAL].is_valid(): message = "Required section 'global' is invalid:\n" message += "\n".join([msg for (level, msg) in effective_config[VW_GLOBAL].validation_messages]) message += "\n" exit(1, "virt-who can't be started: %s" % message) valid_virt_sections = [(name, section) for (name, section) in effective_config.virt_sections() if section.is_valid()] if not valid_virt_sections: err = "virt-who can't be started: no valid configuration found" logger.error(err) exit(1, err) global executor has_error = False try: executor = Executor(logger, effective_config) except (InvalidKeyFile, InvalidPasswordFormat) as e: logger.error(str(e)) exit(1, "virt-who can't be started: %s" % str(e)) if len(executor.dest_to_source_mapper.dests) == 0: if has_error: err = "virt-who can't be started: no valid destination found" logger.error(err) exit(1, err) for name, config in executor.dest_to_source_mapper.configs: logger.info('Using configuration "%s" ("%s" mode)', name, config['type']) logger.info("Using reporter_id='%s'", effective_config[VW_GLOBAL]['reporter_id']) log.closeLogger(logger) with lock: signal.signal(signal.SIGHUP, reload) signal.signal(signal.SIGTERM, atexit_fn) executor.logger = logger = log.getLogger(name='main', queue=True) sd_notify("READY=1\nMAINPID=%d" % os.getpid()) while True: try: return _main(executor) except ReloadRequest: logger.info("Reloading") continue except ExitRequest as e: exit(e.code, status=e.message)