def test_json_file_validate_config1(self, tmpdir): '''! Test reading a valid json file and validate the configuration ''' d = tmpdir.mkdir("valid") fh = d.join("test.json") fh.write(""" { "reboot-on-success": "red" } """) ztpcfg = ZTPCfg(str(fh)) assert (ztpcfg != None) assert (ztpcfg.get('reboot-on-success') == 'red') with pytest.raises(TypeError): validateZtpCfg(ztpcfg)
def test_json_file_validate_config5(self, tmpdir): '''! Test reading a valid json file and validate the configuration ''' d = tmpdir.mkdir("valid") fh = d.join("test.json") fh.write(""" { "admin-mode" : true, "plugins-dir" : "/usr/lib/ztp/plugins", "ztp-json-local" : "/usr/lib/ztp/ztp_data_local.json", "ztp-json-opt67" : "/var/run/ztp/ztp_data_opt67.json", "ztp-json" : "/var/lib/ztp/ztp_data.json", "provisioning-script" : "/var/lib/ztp/provisioning-script", "opt67-url" : "/var/run/ztp/dhcp_67-ztp_data_url", "opt59-v6-url" : "/var/run/ztp/dhcp6_59-ztp_data_url", "opt239-url" : "/var/run/ztp/dhcp_239-provisioning-script_url", "opt239-v6-url" : "/var/run/ztp/dhcp6_239-provisioning-script_url", "curl-retries" : 3, "curl-timeout" : 30, "ignore-result" : false, "reboot-on-success" : false, "reboot-on-failure" : false, "halt-on-failure" : false, "include-http-headers" : true, "https-secure" : true, "http-user-agent" : "SONiC-ZTP/0.1", "ztp-tmp-persistent" : "/var/lib/ztp/sections", "ztp-tmp" : "/var/lib/ztp/tmp2", "section-input-file" : "input.json", "log-file" : "/var/log/ztp.log", "log-level-stdout" : "DEBUG", "log-level-file" : "DEBUG", "discovery-interval" : 10 } """) ztpcfg = ZTPCfg(str(fh)) assert (ztpcfg != None) assert (ztpcfg.get('ztp-tmp') == '/var/lib/ztp/tmp2') try: shutil.rmtree('/var/lib/ztp/tmp2') except OSError: pass validateZtpCfg(ztpcfg)
def test_json_file_valid_set_key3(self, tmpdir): '''! Test writing into jason file ''' d = tmpdir.mkdir("valid") fh = d.join("test4.json") fh.write(""" { "admin-mode" : true, "ztp-json" : "ztp_data.json", "curl-retries" : 1 } """) ztpcfg = ZTPCfg(str(fh)) assert (ztpcfg != None) assert (ztpcfg.get('admin-mode') == True) assert (ztpcfg.get('ztp-json') == 'ztp_data.json') assert (ztpcfg.get('curl-retries') == 1) ztpcfg.set('admin-mode', 123) with pytest.raises(TypeError): validateZtpCfg(ztpcfg) ztpcfg.set('admin-mode', False) ztpcfg.set('ztp-json', 123) with pytest.raises(TypeError): validateZtpCfg(ztpcfg) ztpcfg.set('ztp-json', 'ztp_data2.json') ztpcfg.set('curl-retries', 'abc') with pytest.raises(TypeError): validateZtpCfg(ztpcfg) ztpcfg.set('curl-retries', 3) ztpcfg.set('http-user-agent', 'sonic', save=True) f = self.__read_file(str(fh)) assert (f == """{ "admin-mode": false, "curl-retries": 3, "http-user-agent": "sonic", "ztp-json": "ztp_data2.json" }""")
def main(): '''! Entry point for ZTP service ''' # Only privileged users can execute this command if os.geteuid() != 0: sys.exit("Root privileges required for this operation") # Add supported arguments parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action="store_true", help="Turn on debug level logging") parser.add_argument( "-t", "--test", action="store_true", default=False, help="Start service in test mode with restricted functionality") parser.add_argument("-C", "--config-json", metavar='FILE', default=None, help="ZTP service configuration file") # Parse provided arguments options = parser.parse_args() # Evaluate options if options.debug: _debug = True else: _debug = False if options.test: _test_mode = True else: _test_mode = False # Parse user provided configuration file cfg_json = options.config_json # Create directories if they do not exist dir_objs = ['ztp-tmp-persistent', 'ztp-tmp', 'ztp-cfg-dir', 'ztp-run-dir'] for d in dir_objs: loc = getCfg(d) if os.path.isdir(loc) is False: os.makedirs(loc) # Register signal handlers signal.signal(signal.SIGTERM, signal_handler) signal.signal(signal.SIGINT, signal_handler) # Read and validate configuration file try: ztp.ZTPCfg.ztpCfg = ztp.ZTPCfg.ZTPCfg(cfg_json_file=cfg_json) validateZtpCfg(ztp.ZTPCfg.ztpCfg) # Since we have now the configuration, update the variables in some classes which # use the configuration for their values, default or not. logger.setLevel(getCfg('log-level', 'INFO')) logger.setlogFile(getCfg('log-file')) if _debug: os.environ["DEBUG"] = "yes" logger.setLevel('DEBUG') # Read test-mode from configuration file if getCfg('test-mode') is True: _test_mode = True except Exception as e: print('Exception [%s] occured while reading ZTP configuration file.' % str(e)) print('Exiting ZTP service.') sys.exit(1) # When running in test-mode enable console logging if _test_mode and getCfg('feat-console-logging', True): logger.setConsoleLogging(True) # Start ZTP service objEngine = ZTPEngine() # Run ZTP service to completion objEngine.executeLoop(_test_mode) sys.exit(0)