id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
226,700
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.start
def start(self): """ Starts the IOU process. """ self._check_requirements() if not self.is_running(): yield from self._library_check() try: self._rename_nvram_file() except OSError as e: raise IOUError("Could not rename nvram files: {}".format(e)) iourc_path = self.iourc_path if not iourc_path: raise IOUError("Could not find an iourc file (IOU license)") if not os.path.isfile(iourc_path): raise IOUError("The iourc path '{}' is not a regular file".format(iourc_path)) yield from self._check_iou_licence() yield from self._start_ubridge() self._create_netmap_config() if self.use_default_iou_values: # make sure we have the default nvram amount to correctly push the configs yield from self.update_default_iou_values() self._push_configs_to_nvram() # check if there is enough RAM to run self.check_available_ram(self.ram) self._nvram_watcher = FileWatcher(self._nvram_file(), self._nvram_changed, delay=2) # created a environment variable pointing to the iourc file. env = os.environ.copy() if "IOURC" not in os.environ: env["IOURC"] = iourc_path command = yield from self._build_command() try: log.info("Starting IOU: {}".format(command)) self.command_line = ' '.join(command) self._iou_process = yield from asyncio.create_subprocess_exec( *command, stdout=asyncio.subprocess.PIPE, stdin=asyncio.subprocess.PIPE, stderr=subprocess.STDOUT, cwd=self.working_dir, env=env) log.info("IOU instance {} started PID={}".format(self._id, self._iou_process.pid)) self._started = True self.status = "started" callback = functools.partial(self._termination_callback, "IOU") gns3server.utils.asyncio.monitor_process(self._iou_process, callback) except FileNotFoundError as e: raise IOUError("Could not start IOU: {}: 32-bit binary support is probably not installed".format(e)) except (OSError, subprocess.SubprocessError) as e: iou_stdout = self.read_iou_stdout() log.error("Could not start IOU {}: {}\n{}".format(self._path, e, iou_stdout)) raise IOUError("Could not start IOU {}: {}\n{}".format(self._path, e, iou_stdout)) server = AsyncioTelnetServer(reader=self._iou_process.stdout, writer=self._iou_process.stdin, binary=True, echo=True) self._telnet_server = yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console) # configure networking support yield from self._networking()
python
def start(self): """ Starts the IOU process. """ self._check_requirements() if not self.is_running(): yield from self._library_check() try: self._rename_nvram_file() except OSError as e: raise IOUError("Could not rename nvram files: {}".format(e)) iourc_path = self.iourc_path if not iourc_path: raise IOUError("Could not find an iourc file (IOU license)") if not os.path.isfile(iourc_path): raise IOUError("The iourc path '{}' is not a regular file".format(iourc_path)) yield from self._check_iou_licence() yield from self._start_ubridge() self._create_netmap_config() if self.use_default_iou_values: # make sure we have the default nvram amount to correctly push the configs yield from self.update_default_iou_values() self._push_configs_to_nvram() # check if there is enough RAM to run self.check_available_ram(self.ram) self._nvram_watcher = FileWatcher(self._nvram_file(), self._nvram_changed, delay=2) # created a environment variable pointing to the iourc file. env = os.environ.copy() if "IOURC" not in os.environ: env["IOURC"] = iourc_path command = yield from self._build_command() try: log.info("Starting IOU: {}".format(command)) self.command_line = ' '.join(command) self._iou_process = yield from asyncio.create_subprocess_exec( *command, stdout=asyncio.subprocess.PIPE, stdin=asyncio.subprocess.PIPE, stderr=subprocess.STDOUT, cwd=self.working_dir, env=env) log.info("IOU instance {} started PID={}".format(self._id, self._iou_process.pid)) self._started = True self.status = "started" callback = functools.partial(self._termination_callback, "IOU") gns3server.utils.asyncio.monitor_process(self._iou_process, callback) except FileNotFoundError as e: raise IOUError("Could not start IOU: {}: 32-bit binary support is probably not installed".format(e)) except (OSError, subprocess.SubprocessError) as e: iou_stdout = self.read_iou_stdout() log.error("Could not start IOU {}: {}\n{}".format(self._path, e, iou_stdout)) raise IOUError("Could not start IOU {}: {}\n{}".format(self._path, e, iou_stdout)) server = AsyncioTelnetServer(reader=self._iou_process.stdout, writer=self._iou_process.stdin, binary=True, echo=True) self._telnet_server = yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console) # configure networking support yield from self._networking()
[ "def", "start", "(", "self", ")", ":", "self", ".", "_check_requirements", "(", ")", "if", "not", "self", ".", "is_running", "(", ")", ":", "yield", "from", "self", ".", "_library_check", "(", ")", "try", ":", "self", ".", "_rename_nvram_file", "(", ")", "except", "OSError", "as", "e", ":", "raise", "IOUError", "(", "\"Could not rename nvram files: {}\"", ".", "format", "(", "e", ")", ")", "iourc_path", "=", "self", ".", "iourc_path", "if", "not", "iourc_path", ":", "raise", "IOUError", "(", "\"Could not find an iourc file (IOU license)\"", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "iourc_path", ")", ":", "raise", "IOUError", "(", "\"The iourc path '{}' is not a regular file\"", ".", "format", "(", "iourc_path", ")", ")", "yield", "from", "self", ".", "_check_iou_licence", "(", ")", "yield", "from", "self", ".", "_start_ubridge", "(", ")", "self", ".", "_create_netmap_config", "(", ")", "if", "self", ".", "use_default_iou_values", ":", "# make sure we have the default nvram amount to correctly push the configs", "yield", "from", "self", ".", "update_default_iou_values", "(", ")", "self", ".", "_push_configs_to_nvram", "(", ")", "# check if there is enough RAM to run", "self", ".", "check_available_ram", "(", "self", ".", "ram", ")", "self", ".", "_nvram_watcher", "=", "FileWatcher", "(", "self", ".", "_nvram_file", "(", ")", ",", "self", ".", "_nvram_changed", ",", "delay", "=", "2", ")", "# created a environment variable pointing to the iourc file.", "env", "=", "os", ".", "environ", ".", "copy", "(", ")", "if", "\"IOURC\"", "not", "in", "os", ".", "environ", ":", "env", "[", "\"IOURC\"", "]", "=", "iourc_path", "command", "=", "yield", "from", "self", ".", "_build_command", "(", ")", "try", ":", "log", ".", "info", "(", "\"Starting IOU: {}\"", ".", "format", "(", "command", ")", ")", "self", ".", "command_line", "=", "' '", ".", "join", "(", "command", ")", "self", ".", "_iou_process", "=", "yield", "from", "asyncio", ".", "create_subprocess_exec", "(", "*", "command", ",", "stdout", "=", "asyncio", ".", "subprocess", ".", "PIPE", ",", "stdin", "=", "asyncio", ".", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "cwd", "=", "self", ".", "working_dir", ",", "env", "=", "env", ")", "log", ".", "info", "(", "\"IOU instance {} started PID={}\"", ".", "format", "(", "self", ".", "_id", ",", "self", ".", "_iou_process", ".", "pid", ")", ")", "self", ".", "_started", "=", "True", "self", ".", "status", "=", "\"started\"", "callback", "=", "functools", ".", "partial", "(", "self", ".", "_termination_callback", ",", "\"IOU\"", ")", "gns3server", ".", "utils", ".", "asyncio", ".", "monitor_process", "(", "self", ".", "_iou_process", ",", "callback", ")", "except", "FileNotFoundError", "as", "e", ":", "raise", "IOUError", "(", "\"Could not start IOU: {}: 32-bit binary support is probably not installed\"", ".", "format", "(", "e", ")", ")", "except", "(", "OSError", ",", "subprocess", ".", "SubprocessError", ")", "as", "e", ":", "iou_stdout", "=", "self", ".", "read_iou_stdout", "(", ")", "log", ".", "error", "(", "\"Could not start IOU {}: {}\\n{}\"", ".", "format", "(", "self", ".", "_path", ",", "e", ",", "iou_stdout", ")", ")", "raise", "IOUError", "(", "\"Could not start IOU {}: {}\\n{}\"", ".", "format", "(", "self", ".", "_path", ",", "e", ",", "iou_stdout", ")", ")", "server", "=", "AsyncioTelnetServer", "(", "reader", "=", "self", ".", "_iou_process", ".", "stdout", ",", "writer", "=", "self", ".", "_iou_process", ".", "stdin", ",", "binary", "=", "True", ",", "echo", "=", "True", ")", "self", ".", "_telnet_server", "=", "yield", "from", "asyncio", ".", "start_server", "(", "server", ".", "run", ",", "self", ".", "_manager", ".", "port_manager", ".", "console_host", ",", "self", ".", "console", ")", "# configure networking support", "yield", "from", "self", ".", "_networking", "(", ")" ]
Starts the IOU process.
[ "Starts", "the", "IOU", "process", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L480-L547
226,701
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM._networking
def _networking(self): """ Configures the IOL bridge in uBridge. """ bridge_name = "IOL-BRIDGE-{}".format(self.application_id + 512) try: # delete any previous bridge if it exists yield from self._ubridge_send("iol_bridge delete {name}".format(name=bridge_name)) except UbridgeError: pass yield from self._ubridge_send("iol_bridge create {name} {bridge_id}".format(name=bridge_name, bridge_id=self.application_id + 512)) bay_id = 0 for adapter in self._adapters: unit_id = 0 for unit in adapter.ports.keys(): nio = adapter.get_nio(unit) if nio and isinstance(nio, NIOUDP): yield from self._ubridge_send("iol_bridge add_nio_udp {name} {iol_id} {bay} {unit} {lport} {rhost} {rport}".format(name=bridge_name, iol_id=self.application_id, bay=bay_id, unit=unit_id, lport=nio.lport, rhost=nio.rhost, rport=nio.rport)) if nio.capturing: yield from self._ubridge_send('iol_bridge start_capture {name} "{output_file}" {data_link_type}'.format(name=bridge_name, output_file=nio.pcap_output_file, data_link_type=re.sub("^DLT_", "", nio.pcap_data_link_type))) yield from self._ubridge_apply_filters(bay_id, unit_id, nio.filters) unit_id += 1 bay_id += 1 yield from self._ubridge_send("iol_bridge start {name}".format(name=bridge_name))
python
def _networking(self): """ Configures the IOL bridge in uBridge. """ bridge_name = "IOL-BRIDGE-{}".format(self.application_id + 512) try: # delete any previous bridge if it exists yield from self._ubridge_send("iol_bridge delete {name}".format(name=bridge_name)) except UbridgeError: pass yield from self._ubridge_send("iol_bridge create {name} {bridge_id}".format(name=bridge_name, bridge_id=self.application_id + 512)) bay_id = 0 for adapter in self._adapters: unit_id = 0 for unit in adapter.ports.keys(): nio = adapter.get_nio(unit) if nio and isinstance(nio, NIOUDP): yield from self._ubridge_send("iol_bridge add_nio_udp {name} {iol_id} {bay} {unit} {lport} {rhost} {rport}".format(name=bridge_name, iol_id=self.application_id, bay=bay_id, unit=unit_id, lport=nio.lport, rhost=nio.rhost, rport=nio.rport)) if nio.capturing: yield from self._ubridge_send('iol_bridge start_capture {name} "{output_file}" {data_link_type}'.format(name=bridge_name, output_file=nio.pcap_output_file, data_link_type=re.sub("^DLT_", "", nio.pcap_data_link_type))) yield from self._ubridge_apply_filters(bay_id, unit_id, nio.filters) unit_id += 1 bay_id += 1 yield from self._ubridge_send("iol_bridge start {name}".format(name=bridge_name))
[ "def", "_networking", "(", "self", ")", ":", "bridge_name", "=", "\"IOL-BRIDGE-{}\"", ".", "format", "(", "self", ".", "application_id", "+", "512", ")", "try", ":", "# delete any previous bridge if it exists", "yield", "from", "self", ".", "_ubridge_send", "(", "\"iol_bridge delete {name}\"", ".", "format", "(", "name", "=", "bridge_name", ")", ")", "except", "UbridgeError", ":", "pass", "yield", "from", "self", ".", "_ubridge_send", "(", "\"iol_bridge create {name} {bridge_id}\"", ".", "format", "(", "name", "=", "bridge_name", ",", "bridge_id", "=", "self", ".", "application_id", "+", "512", ")", ")", "bay_id", "=", "0", "for", "adapter", "in", "self", ".", "_adapters", ":", "unit_id", "=", "0", "for", "unit", "in", "adapter", ".", "ports", ".", "keys", "(", ")", ":", "nio", "=", "adapter", ".", "get_nio", "(", "unit", ")", "if", "nio", "and", "isinstance", "(", "nio", ",", "NIOUDP", ")", ":", "yield", "from", "self", ".", "_ubridge_send", "(", "\"iol_bridge add_nio_udp {name} {iol_id} {bay} {unit} {lport} {rhost} {rport}\"", ".", "format", "(", "name", "=", "bridge_name", ",", "iol_id", "=", "self", ".", "application_id", ",", "bay", "=", "bay_id", ",", "unit", "=", "unit_id", ",", "lport", "=", "nio", ".", "lport", ",", "rhost", "=", "nio", ".", "rhost", ",", "rport", "=", "nio", ".", "rport", ")", ")", "if", "nio", ".", "capturing", ":", "yield", "from", "self", ".", "_ubridge_send", "(", "'iol_bridge start_capture {name} \"{output_file}\" {data_link_type}'", ".", "format", "(", "name", "=", "bridge_name", ",", "output_file", "=", "nio", ".", "pcap_output_file", ",", "data_link_type", "=", "re", ".", "sub", "(", "\"^DLT_\"", ",", "\"\"", ",", "nio", ".", "pcap_data_link_type", ")", ")", ")", "yield", "from", "self", ".", "_ubridge_apply_filters", "(", "bay_id", ",", "unit_id", ",", "nio", ".", "filters", ")", "unit_id", "+=", "1", "bay_id", "+=", "1", "yield", "from", "self", ".", "_ubridge_send", "(", "\"iol_bridge start {name}\"", ".", "format", "(", "name", "=", "bridge_name", ")", ")" ]
Configures the IOL bridge in uBridge.
[ "Configures", "the", "IOL", "bridge", "in", "uBridge", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L550-L585
226,702
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM._rename_nvram_file
def _rename_nvram_file(self): """ Before starting the VM, rename the nvram and vlan.dat files with the correct IOU application identifier. """ destination = self._nvram_file() for file_path in glob.glob(os.path.join(glob.escape(self.working_dir), "nvram_*")): shutil.move(file_path, destination) destination = os.path.join(self.working_dir, "vlan.dat-{:05d}".format(self.application_id)) for file_path in glob.glob(os.path.join(glob.escape(self.working_dir), "vlan.dat-*")): shutil.move(file_path, destination)
python
def _rename_nvram_file(self): """ Before starting the VM, rename the nvram and vlan.dat files with the correct IOU application identifier. """ destination = self._nvram_file() for file_path in glob.glob(os.path.join(glob.escape(self.working_dir), "nvram_*")): shutil.move(file_path, destination) destination = os.path.join(self.working_dir, "vlan.dat-{:05d}".format(self.application_id)) for file_path in glob.glob(os.path.join(glob.escape(self.working_dir), "vlan.dat-*")): shutil.move(file_path, destination)
[ "def", "_rename_nvram_file", "(", "self", ")", ":", "destination", "=", "self", ".", "_nvram_file", "(", ")", "for", "file_path", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "glob", ".", "escape", "(", "self", ".", "working_dir", ")", ",", "\"nvram_*\"", ")", ")", ":", "shutil", ".", "move", "(", "file_path", ",", "destination", ")", "destination", "=", "os", ".", "path", ".", "join", "(", "self", ".", "working_dir", ",", "\"vlan.dat-{:05d}\"", ".", "format", "(", "self", ".", "application_id", ")", ")", "for", "file_path", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "glob", ".", "escape", "(", "self", ".", "working_dir", ")", ",", "\"vlan.dat-*\"", ")", ")", ":", "shutil", ".", "move", "(", "file_path", ",", "destination", ")" ]
Before starting the VM, rename the nvram and vlan.dat files with the correct IOU application identifier.
[ "Before", "starting", "the", "VM", "rename", "the", "nvram", "and", "vlan", ".", "dat", "files", "with", "the", "correct", "IOU", "application", "identifier", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L608-L618
226,703
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.stop
def stop(self): """ Stops the IOU process. """ yield from self._stop_ubridge() if self._nvram_watcher: self._nvram_watcher.close() self._nvram_watcher = None if self._telnet_server: self._telnet_server.close() self._telnet_server = None if self.is_running(): self._terminate_process_iou() if self._iou_process.returncode is None: try: yield from gns3server.utils.asyncio.wait_for_process_termination(self._iou_process, timeout=3) except asyncio.TimeoutError: if self._iou_process.returncode is None: log.warning("IOU process {} is still running... killing it".format(self._iou_process.pid)) try: self._iou_process.kill() except ProcessLookupError: pass self._iou_process = None self._started = False self.save_configs()
python
def stop(self): """ Stops the IOU process. """ yield from self._stop_ubridge() if self._nvram_watcher: self._nvram_watcher.close() self._nvram_watcher = None if self._telnet_server: self._telnet_server.close() self._telnet_server = None if self.is_running(): self._terminate_process_iou() if self._iou_process.returncode is None: try: yield from gns3server.utils.asyncio.wait_for_process_termination(self._iou_process, timeout=3) except asyncio.TimeoutError: if self._iou_process.returncode is None: log.warning("IOU process {} is still running... killing it".format(self._iou_process.pid)) try: self._iou_process.kill() except ProcessLookupError: pass self._iou_process = None self._started = False self.save_configs()
[ "def", "stop", "(", "self", ")", ":", "yield", "from", "self", ".", "_stop_ubridge", "(", ")", "if", "self", ".", "_nvram_watcher", ":", "self", ".", "_nvram_watcher", ".", "close", "(", ")", "self", ".", "_nvram_watcher", "=", "None", "if", "self", ".", "_telnet_server", ":", "self", ".", "_telnet_server", ".", "close", "(", ")", "self", ".", "_telnet_server", "=", "None", "if", "self", ".", "is_running", "(", ")", ":", "self", ".", "_terminate_process_iou", "(", ")", "if", "self", ".", "_iou_process", ".", "returncode", "is", "None", ":", "try", ":", "yield", "from", "gns3server", ".", "utils", ".", "asyncio", ".", "wait_for_process_termination", "(", "self", ".", "_iou_process", ",", "timeout", "=", "3", ")", "except", "asyncio", ".", "TimeoutError", ":", "if", "self", ".", "_iou_process", ".", "returncode", "is", "None", ":", "log", ".", "warning", "(", "\"IOU process {} is still running... killing it\"", ".", "format", "(", "self", ".", "_iou_process", ".", "pid", ")", ")", "try", ":", "self", ".", "_iou_process", ".", "kill", "(", ")", "except", "ProcessLookupError", ":", "pass", "self", ".", "_iou_process", "=", "None", "self", ".", "_started", "=", "False", "self", ".", "save_configs", "(", ")" ]
Stops the IOU process.
[ "Stops", "the", "IOU", "process", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L621-L650
226,704
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM._terminate_process_iou
def _terminate_process_iou(self): """ Terminate the IOU process if running """ if self._iou_process: log.info('Stopping IOU process for IOU VM "{}" PID={}'.format(self.name, self._iou_process.pid)) try: self._iou_process.terminate() # Sometime the process can already be dead when we garbage collect except ProcessLookupError: pass self._started = False self.status = "stopped"
python
def _terminate_process_iou(self): """ Terminate the IOU process if running """ if self._iou_process: log.info('Stopping IOU process for IOU VM "{}" PID={}'.format(self.name, self._iou_process.pid)) try: self._iou_process.terminate() # Sometime the process can already be dead when we garbage collect except ProcessLookupError: pass self._started = False self.status = "stopped"
[ "def", "_terminate_process_iou", "(", "self", ")", ":", "if", "self", ".", "_iou_process", ":", "log", ".", "info", "(", "'Stopping IOU process for IOU VM \"{}\" PID={}'", ".", "format", "(", "self", ".", "name", ",", "self", ".", "_iou_process", ".", "pid", ")", ")", "try", ":", "self", ".", "_iou_process", ".", "terminate", "(", ")", "# Sometime the process can already be dead when we garbage collect", "except", "ProcessLookupError", ":", "pass", "self", ".", "_started", "=", "False", "self", ".", "status", "=", "\"stopped\"" ]
Terminate the IOU process if running
[ "Terminate", "the", "IOU", "process", "if", "running" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L652-L665
226,705
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM._create_netmap_config
def _create_netmap_config(self): """ Creates the NETMAP file. """ netmap_path = os.path.join(self.working_dir, "NETMAP") try: with open(netmap_path, "w", encoding="utf-8") as f: for bay in range(0, 16): for unit in range(0, 4): f.write("{ubridge_id}:{bay}/{unit}{iou_id:>5d}:{bay}/{unit}\n".format(ubridge_id=str(self.application_id + 512), bay=bay, unit=unit, iou_id=self.application_id)) log.info("IOU {name} [id={id}]: NETMAP file created".format(name=self._name, id=self._id)) except OSError as e: raise IOUError("Could not create {}: {}".format(netmap_path, e))
python
def _create_netmap_config(self): """ Creates the NETMAP file. """ netmap_path = os.path.join(self.working_dir, "NETMAP") try: with open(netmap_path, "w", encoding="utf-8") as f: for bay in range(0, 16): for unit in range(0, 4): f.write("{ubridge_id}:{bay}/{unit}{iou_id:>5d}:{bay}/{unit}\n".format(ubridge_id=str(self.application_id + 512), bay=bay, unit=unit, iou_id=self.application_id)) log.info("IOU {name} [id={id}]: NETMAP file created".format(name=self._name, id=self._id)) except OSError as e: raise IOUError("Could not create {}: {}".format(netmap_path, e))
[ "def", "_create_netmap_config", "(", "self", ")", ":", "netmap_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "working_dir", ",", "\"NETMAP\"", ")", "try", ":", "with", "open", "(", "netmap_path", ",", "\"w\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "for", "bay", "in", "range", "(", "0", ",", "16", ")", ":", "for", "unit", "in", "range", "(", "0", ",", "4", ")", ":", "f", ".", "write", "(", "\"{ubridge_id}:{bay}/{unit}{iou_id:>5d}:{bay}/{unit}\\n\"", ".", "format", "(", "ubridge_id", "=", "str", "(", "self", ".", "application_id", "+", "512", ")", ",", "bay", "=", "bay", ",", "unit", "=", "unit", ",", "iou_id", "=", "self", ".", "application_id", ")", ")", "log", ".", "info", "(", "\"IOU {name} [id={id}]: NETMAP file created\"", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "id", "=", "self", ".", "_id", ")", ")", "except", "OSError", "as", "e", ":", "raise", "IOUError", "(", "\"Could not create {}: {}\"", ".", "format", "(", "netmap_path", ",", "e", ")", ")" ]
Creates the NETMAP file.
[ "Creates", "the", "NETMAP", "file", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L687-L704
226,706
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.read_iou_stdout
def read_iou_stdout(self): """ Reads the standard output of the IOU process. Only use when the process has been stopped or has crashed. """ output = "" if self._iou_stdout_file: try: with open(self._iou_stdout_file, "rb") as file: output = file.read().decode("utf-8", errors="replace") except OSError as e: log.warn("could not read {}: {}".format(self._iou_stdout_file, e)) return output
python
def read_iou_stdout(self): """ Reads the standard output of the IOU process. Only use when the process has been stopped or has crashed. """ output = "" if self._iou_stdout_file: try: with open(self._iou_stdout_file, "rb") as file: output = file.read().decode("utf-8", errors="replace") except OSError as e: log.warn("could not read {}: {}".format(self._iou_stdout_file, e)) return output
[ "def", "read_iou_stdout", "(", "self", ")", ":", "output", "=", "\"\"", "if", "self", ".", "_iou_stdout_file", ":", "try", ":", "with", "open", "(", "self", ".", "_iou_stdout_file", ",", "\"rb\"", ")", "as", "file", ":", "output", "=", "file", ".", "read", "(", ")", ".", "decode", "(", "\"utf-8\"", ",", "errors", "=", "\"replace\"", ")", "except", "OSError", "as", "e", ":", "log", ".", "warn", "(", "\"could not read {}: {}\"", ".", "format", "(", "self", ".", "_iou_stdout_file", ",", "e", ")", ")", "return", "output" ]
Reads the standard output of the IOU process. Only use when the process has been stopped or has crashed.
[ "Reads", "the", "standard", "output", "of", "the", "IOU", "process", ".", "Only", "use", "when", "the", "process", "has", "been", "stopped", "or", "has", "crashed", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L756-L769
226,707
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.ethernet_adapters
def ethernet_adapters(self, ethernet_adapters): """ Sets the number of Ethernet adapters for this IOU VM. :param ethernet_adapters: number of adapters """ self._ethernet_adapters.clear() for _ in range(0, ethernet_adapters): self._ethernet_adapters.append(EthernetAdapter(interfaces=4)) log.info('IOU "{name}" [{id}]: number of Ethernet adapters changed to {adapters}'.format(name=self._name, id=self._id, adapters=len(self._ethernet_adapters))) self._adapters = self._ethernet_adapters + self._serial_adapters
python
def ethernet_adapters(self, ethernet_adapters): """ Sets the number of Ethernet adapters for this IOU VM. :param ethernet_adapters: number of adapters """ self._ethernet_adapters.clear() for _ in range(0, ethernet_adapters): self._ethernet_adapters.append(EthernetAdapter(interfaces=4)) log.info('IOU "{name}" [{id}]: number of Ethernet adapters changed to {adapters}'.format(name=self._name, id=self._id, adapters=len(self._ethernet_adapters))) self._adapters = self._ethernet_adapters + self._serial_adapters
[ "def", "ethernet_adapters", "(", "self", ",", "ethernet_adapters", ")", ":", "self", ".", "_ethernet_adapters", ".", "clear", "(", ")", "for", "_", "in", "range", "(", "0", ",", "ethernet_adapters", ")", ":", "self", ".", "_ethernet_adapters", ".", "append", "(", "EthernetAdapter", "(", "interfaces", "=", "4", ")", ")", "log", ".", "info", "(", "'IOU \"{name}\" [{id}]: number of Ethernet adapters changed to {adapters}'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "id", "=", "self", ".", "_id", ",", "adapters", "=", "len", "(", "self", ".", "_ethernet_adapters", ")", ")", ")", "self", ".", "_adapters", "=", "self", ".", "_ethernet_adapters", "+", "self", ".", "_serial_adapters" ]
Sets the number of Ethernet adapters for this IOU VM. :param ethernet_adapters: number of adapters
[ "Sets", "the", "number", "of", "Ethernet", "adapters", "for", "this", "IOU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L786-L801
226,708
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.serial_adapters
def serial_adapters(self, serial_adapters): """ Sets the number of Serial adapters for this IOU VM. :param serial_adapters: number of adapters """ self._serial_adapters.clear() for _ in range(0, serial_adapters): self._serial_adapters.append(SerialAdapter(interfaces=4)) log.info('IOU "{name}" [{id}]: number of Serial adapters changed to {adapters}'.format(name=self._name, id=self._id, adapters=len(self._serial_adapters))) self._adapters = self._ethernet_adapters + self._serial_adapters
python
def serial_adapters(self, serial_adapters): """ Sets the number of Serial adapters for this IOU VM. :param serial_adapters: number of adapters """ self._serial_adapters.clear() for _ in range(0, serial_adapters): self._serial_adapters.append(SerialAdapter(interfaces=4)) log.info('IOU "{name}" [{id}]: number of Serial adapters changed to {adapters}'.format(name=self._name, id=self._id, adapters=len(self._serial_adapters))) self._adapters = self._ethernet_adapters + self._serial_adapters
[ "def", "serial_adapters", "(", "self", ",", "serial_adapters", ")", ":", "self", ".", "_serial_adapters", ".", "clear", "(", ")", "for", "_", "in", "range", "(", "0", ",", "serial_adapters", ")", ":", "self", ".", "_serial_adapters", ".", "append", "(", "SerialAdapter", "(", "interfaces", "=", "4", ")", ")", "log", ".", "info", "(", "'IOU \"{name}\" [{id}]: number of Serial adapters changed to {adapters}'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "id", "=", "self", ".", "_id", ",", "adapters", "=", "len", "(", "self", ".", "_serial_adapters", ")", ")", ")", "self", ".", "_adapters", "=", "self", ".", "_ethernet_adapters", "+", "self", ".", "_serial_adapters" ]
Sets the number of Serial adapters for this IOU VM. :param serial_adapters: number of adapters
[ "Sets", "the", "number", "of", "Serial", "adapters", "for", "this", "IOU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L814-L829
226,709
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.adapter_add_nio_binding
def adapter_add_nio_binding(self, adapter_number, port_number, nio): """ Adds a adapter NIO binding. :param adapter_number: adapter number :param port_number: port number :param nio: NIO instance to add to the adapter/port """ try: adapter = self._adapters[adapter_number] except IndexError: raise IOUError('Adapter {adapter_number} does not exist for IOU "{name}"'.format(name=self._name, adapter_number=adapter_number)) if not adapter.port_exists(port_number): raise IOUError("Port {port_number} does not exist in adapter {adapter}".format(adapter=adapter, port_number=port_number)) adapter.add_nio(port_number, nio) log.info('IOU "{name}" [{id}]: {nio} added to {adapter_number}/{port_number}'.format(name=self._name, id=self._id, nio=nio, adapter_number=adapter_number, port_number=port_number)) if self.ubridge: bridge_name = "IOL-BRIDGE-{}".format(self.application_id + 512) yield from self._ubridge_send("iol_bridge add_nio_udp {name} {iol_id} {bay} {unit} {lport} {rhost} {rport}".format(name=bridge_name, iol_id=self.application_id, bay=adapter_number, unit=port_number, lport=nio.lport, rhost=nio.rhost, rport=nio.rport)) yield from self._ubridge_apply_filters(adapter_number, port_number, nio.filters)
python
def adapter_add_nio_binding(self, adapter_number, port_number, nio): """ Adds a adapter NIO binding. :param adapter_number: adapter number :param port_number: port number :param nio: NIO instance to add to the adapter/port """ try: adapter = self._adapters[adapter_number] except IndexError: raise IOUError('Adapter {adapter_number} does not exist for IOU "{name}"'.format(name=self._name, adapter_number=adapter_number)) if not adapter.port_exists(port_number): raise IOUError("Port {port_number} does not exist in adapter {adapter}".format(adapter=adapter, port_number=port_number)) adapter.add_nio(port_number, nio) log.info('IOU "{name}" [{id}]: {nio} added to {adapter_number}/{port_number}'.format(name=self._name, id=self._id, nio=nio, adapter_number=adapter_number, port_number=port_number)) if self.ubridge: bridge_name = "IOL-BRIDGE-{}".format(self.application_id + 512) yield from self._ubridge_send("iol_bridge add_nio_udp {name} {iol_id} {bay} {unit} {lport} {rhost} {rport}".format(name=bridge_name, iol_id=self.application_id, bay=adapter_number, unit=port_number, lport=nio.lport, rhost=nio.rhost, rport=nio.rport)) yield from self._ubridge_apply_filters(adapter_number, port_number, nio.filters)
[ "def", "adapter_add_nio_binding", "(", "self", ",", "adapter_number", ",", "port_number", ",", "nio", ")", ":", "try", ":", "adapter", "=", "self", ".", "_adapters", "[", "adapter_number", "]", "except", "IndexError", ":", "raise", "IOUError", "(", "'Adapter {adapter_number} does not exist for IOU \"{name}\"'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "adapter_number", "=", "adapter_number", ")", ")", "if", "not", "adapter", ".", "port_exists", "(", "port_number", ")", ":", "raise", "IOUError", "(", "\"Port {port_number} does not exist in adapter {adapter}\"", ".", "format", "(", "adapter", "=", "adapter", ",", "port_number", "=", "port_number", ")", ")", "adapter", ".", "add_nio", "(", "port_number", ",", "nio", ")", "log", ".", "info", "(", "'IOU \"{name}\" [{id}]: {nio} added to {adapter_number}/{port_number}'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "id", "=", "self", ".", "_id", ",", "nio", "=", "nio", ",", "adapter_number", "=", "adapter_number", ",", "port_number", "=", "port_number", ")", ")", "if", "self", ".", "ubridge", ":", "bridge_name", "=", "\"IOL-BRIDGE-{}\"", ".", "format", "(", "self", ".", "application_id", "+", "512", ")", "yield", "from", "self", ".", "_ubridge_send", "(", "\"iol_bridge add_nio_udp {name} {iol_id} {bay} {unit} {lport} {rhost} {rport}\"", ".", "format", "(", "name", "=", "bridge_name", ",", "iol_id", "=", "self", ".", "application_id", ",", "bay", "=", "adapter_number", ",", "unit", "=", "port_number", ",", "lport", "=", "nio", ".", "lport", ",", "rhost", "=", "nio", ".", "rhost", ",", "rport", "=", "nio", ".", "rport", ")", ")", "yield", "from", "self", ".", "_ubridge_apply_filters", "(", "adapter_number", ",", "port_number", ",", "nio", ".", "filters", ")" ]
Adds a adapter NIO binding. :param adapter_number: adapter number :param port_number: port number :param nio: NIO instance to add to the adapter/port
[ "Adds", "a", "adapter", "NIO", "binding", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L832-L867
226,710
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM._ubridge_apply_filters
def _ubridge_apply_filters(self, adapter_number, port_number, filters): """ Apply filter like rate limiting :param adapter_number: adapter number :param port_number: port number :param filters: Array of filter dictionnary """ bridge_name = "IOL-BRIDGE-{}".format(self.application_id + 512) location = '{bridge_name} {bay} {unit}'.format( bridge_name=bridge_name, bay=adapter_number, unit=port_number) yield from self._ubridge_send('iol_bridge reset_packet_filters ' + location) for filter in self._build_filter_list(filters): cmd = 'iol_bridge add_packet_filter {} {}'.format( location, filter) yield from self._ubridge_send(cmd)
python
def _ubridge_apply_filters(self, adapter_number, port_number, filters): """ Apply filter like rate limiting :param adapter_number: adapter number :param port_number: port number :param filters: Array of filter dictionnary """ bridge_name = "IOL-BRIDGE-{}".format(self.application_id + 512) location = '{bridge_name} {bay} {unit}'.format( bridge_name=bridge_name, bay=adapter_number, unit=port_number) yield from self._ubridge_send('iol_bridge reset_packet_filters ' + location) for filter in self._build_filter_list(filters): cmd = 'iol_bridge add_packet_filter {} {}'.format( location, filter) yield from self._ubridge_send(cmd)
[ "def", "_ubridge_apply_filters", "(", "self", ",", "adapter_number", ",", "port_number", ",", "filters", ")", ":", "bridge_name", "=", "\"IOL-BRIDGE-{}\"", ".", "format", "(", "self", ".", "application_id", "+", "512", ")", "location", "=", "'{bridge_name} {bay} {unit}'", ".", "format", "(", "bridge_name", "=", "bridge_name", ",", "bay", "=", "adapter_number", ",", "unit", "=", "port_number", ")", "yield", "from", "self", ".", "_ubridge_send", "(", "'iol_bridge reset_packet_filters '", "+", "location", ")", "for", "filter", "in", "self", ".", "_build_filter_list", "(", "filters", ")", ":", "cmd", "=", "'iol_bridge add_packet_filter {} {}'", ".", "format", "(", "location", ",", "filter", ")", "yield", "from", "self", ".", "_ubridge_send", "(", "cmd", ")" ]
Apply filter like rate limiting :param adapter_number: adapter number :param port_number: port number :param filters: Array of filter dictionnary
[ "Apply", "filter", "like", "rate", "limiting" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L883-L901
226,711
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.l1_keepalives
def l1_keepalives(self, state): """ Enables or disables layer 1 keepalive messages. :param state: boolean """ self._l1_keepalives = state if state: log.info('IOU "{name}" [{id}]: has activated layer 1 keepalive messages'.format(name=self._name, id=self._id)) else: log.info('IOU "{name}" [{id}]: has deactivated layer 1 keepalive messages'.format(name=self._name, id=self._id))
python
def l1_keepalives(self, state): """ Enables or disables layer 1 keepalive messages. :param state: boolean """ self._l1_keepalives = state if state: log.info('IOU "{name}" [{id}]: has activated layer 1 keepalive messages'.format(name=self._name, id=self._id)) else: log.info('IOU "{name}" [{id}]: has deactivated layer 1 keepalive messages'.format(name=self._name, id=self._id))
[ "def", "l1_keepalives", "(", "self", ",", "state", ")", ":", "self", ".", "_l1_keepalives", "=", "state", "if", "state", ":", "log", ".", "info", "(", "'IOU \"{name}\" [{id}]: has activated layer 1 keepalive messages'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "id", "=", "self", ".", "_id", ")", ")", "else", ":", "log", ".", "info", "(", "'IOU \"{name}\" [{id}]: has deactivated layer 1 keepalive messages'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "id", "=", "self", ".", "_id", ")", ")" ]
Enables or disables layer 1 keepalive messages. :param state: boolean
[ "Enables", "or", "disables", "layer", "1", "keepalive", "messages", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L952-L963
226,712
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM._enable_l1_keepalives
def _enable_l1_keepalives(self, command): """ Enables L1 keepalive messages if supported. :param command: command line """ env = os.environ.copy() if "IOURC" not in os.environ: env["IOURC"] = self.iourc_path try: output = yield from gns3server.utils.asyncio.subprocess_check_output(self._path, "-h", cwd=self.working_dir, env=env, stderr=True) if re.search("-l\s+Enable Layer 1 keepalive messages", output): command.extend(["-l"]) else: raise IOUError("layer 1 keepalive messages are not supported by {}".format(os.path.basename(self._path))) except (OSError, subprocess.SubprocessError) as e: log.warning("could not determine if layer 1 keepalive messages are supported by {}: {}".format(os.path.basename(self._path), e))
python
def _enable_l1_keepalives(self, command): """ Enables L1 keepalive messages if supported. :param command: command line """ env = os.environ.copy() if "IOURC" not in os.environ: env["IOURC"] = self.iourc_path try: output = yield from gns3server.utils.asyncio.subprocess_check_output(self._path, "-h", cwd=self.working_dir, env=env, stderr=True) if re.search("-l\s+Enable Layer 1 keepalive messages", output): command.extend(["-l"]) else: raise IOUError("layer 1 keepalive messages are not supported by {}".format(os.path.basename(self._path))) except (OSError, subprocess.SubprocessError) as e: log.warning("could not determine if layer 1 keepalive messages are supported by {}: {}".format(os.path.basename(self._path), e))
[ "def", "_enable_l1_keepalives", "(", "self", ",", "command", ")", ":", "env", "=", "os", ".", "environ", ".", "copy", "(", ")", "if", "\"IOURC\"", "not", "in", "os", ".", "environ", ":", "env", "[", "\"IOURC\"", "]", "=", "self", ".", "iourc_path", "try", ":", "output", "=", "yield", "from", "gns3server", ".", "utils", ".", "asyncio", ".", "subprocess_check_output", "(", "self", ".", "_path", ",", "\"-h\"", ",", "cwd", "=", "self", ".", "working_dir", ",", "env", "=", "env", ",", "stderr", "=", "True", ")", "if", "re", ".", "search", "(", "\"-l\\s+Enable Layer 1 keepalive messages\"", ",", "output", ")", ":", "command", ".", "extend", "(", "[", "\"-l\"", "]", ")", "else", ":", "raise", "IOUError", "(", "\"layer 1 keepalive messages are not supported by {}\"", ".", "format", "(", "os", ".", "path", ".", "basename", "(", "self", ".", "_path", ")", ")", ")", "except", "(", "OSError", ",", "subprocess", ".", "SubprocessError", ")", "as", "e", ":", "log", ".", "warning", "(", "\"could not determine if layer 1 keepalive messages are supported by {}: {}\"", ".", "format", "(", "os", ".", "path", ".", "basename", "(", "self", ".", "_path", ")", ",", "e", ")", ")" ]
Enables L1 keepalive messages if supported. :param command: command line
[ "Enables", "L1", "keepalive", "messages", "if", "supported", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L966-L983
226,713
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.startup_config_content
def startup_config_content(self): """ Returns the content of the current startup-config file. """ config_file = self.startup_config_file if config_file is None: return None try: with open(config_file, "rb") as f: return f.read().decode("utf-8", errors="replace") except OSError as e: raise IOUError("Can't read startup-config file '{}': {}".format(config_file, e))
python
def startup_config_content(self): """ Returns the content of the current startup-config file. """ config_file = self.startup_config_file if config_file is None: return None try: with open(config_file, "rb") as f: return f.read().decode("utf-8", errors="replace") except OSError as e: raise IOUError("Can't read startup-config file '{}': {}".format(config_file, e))
[ "def", "startup_config_content", "(", "self", ")", ":", "config_file", "=", "self", ".", "startup_config_file", "if", "config_file", "is", "None", ":", "return", "None", "try", ":", "with", "open", "(", "config_file", ",", "\"rb\"", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")", ".", "decode", "(", "\"utf-8\"", ",", "errors", "=", "\"replace\"", ")", "except", "OSError", "as", "e", ":", "raise", "IOUError", "(", "\"Can't read startup-config file '{}': {}\"", ".", "format", "(", "config_file", ",", "e", ")", ")" ]
Returns the content of the current startup-config file.
[ "Returns", "the", "content", "of", "the", "current", "startup", "-", "config", "file", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L986-L999
226,714
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.startup_config_content
def startup_config_content(self, startup_config): """ Update the startup config :param startup_config: content of the startup configuration file """ try: startup_config_path = os.path.join(self.working_dir, "startup-config.cfg") if startup_config is None: startup_config = '' # We disallow erasing the startup config file if len(startup_config) == 0 and os.path.exists(startup_config_path): return with open(startup_config_path, 'w+', encoding='utf-8') as f: if len(startup_config) == 0: f.write('') else: startup_config = startup_config.replace("%h", self._name) f.write(startup_config) vlan_file = os.path.join(self.working_dir, "vlan.dat-{:05d}".format(self.application_id)) if os.path.exists(vlan_file): try: os.remove(vlan_file) except OSError as e: log.error("Could not delete VLAN file '{}': {}".format(vlan_file, e)) except OSError as e: raise IOUError("Can't write startup-config file '{}': {}".format(startup_config_path, e))
python
def startup_config_content(self, startup_config): """ Update the startup config :param startup_config: content of the startup configuration file """ try: startup_config_path = os.path.join(self.working_dir, "startup-config.cfg") if startup_config is None: startup_config = '' # We disallow erasing the startup config file if len(startup_config) == 0 and os.path.exists(startup_config_path): return with open(startup_config_path, 'w+', encoding='utf-8') as f: if len(startup_config) == 0: f.write('') else: startup_config = startup_config.replace("%h", self._name) f.write(startup_config) vlan_file = os.path.join(self.working_dir, "vlan.dat-{:05d}".format(self.application_id)) if os.path.exists(vlan_file): try: os.remove(vlan_file) except OSError as e: log.error("Could not delete VLAN file '{}': {}".format(vlan_file, e)) except OSError as e: raise IOUError("Can't write startup-config file '{}': {}".format(startup_config_path, e))
[ "def", "startup_config_content", "(", "self", ",", "startup_config", ")", ":", "try", ":", "startup_config_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "working_dir", ",", "\"startup-config.cfg\"", ")", "if", "startup_config", "is", "None", ":", "startup_config", "=", "''", "# We disallow erasing the startup config file", "if", "len", "(", "startup_config", ")", "==", "0", "and", "os", ".", "path", ".", "exists", "(", "startup_config_path", ")", ":", "return", "with", "open", "(", "startup_config_path", ",", "'w+'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "if", "len", "(", "startup_config", ")", "==", "0", ":", "f", ".", "write", "(", "''", ")", "else", ":", "startup_config", "=", "startup_config", ".", "replace", "(", "\"%h\"", ",", "self", ".", "_name", ")", "f", ".", "write", "(", "startup_config", ")", "vlan_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "working_dir", ",", "\"vlan.dat-{:05d}\"", ".", "format", "(", "self", ".", "application_id", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "vlan_file", ")", ":", "try", ":", "os", ".", "remove", "(", "vlan_file", ")", "except", "OSError", "as", "e", ":", "log", ".", "error", "(", "\"Could not delete VLAN file '{}': {}\"", ".", "format", "(", "vlan_file", ",", "e", ")", ")", "except", "OSError", "as", "e", ":", "raise", "IOUError", "(", "\"Can't write startup-config file '{}': {}\"", ".", "format", "(", "startup_config_path", ",", "e", ")", ")" ]
Update the startup config :param startup_config: content of the startup configuration file
[ "Update", "the", "startup", "config" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L1002-L1034
226,715
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.private_config_content
def private_config_content(self): """ Returns the content of the current private-config file. """ config_file = self.private_config_file if config_file is None: return None try: with open(config_file, "rb") as f: return f.read().decode("utf-8", errors="replace") except OSError as e: raise IOUError("Can't read private-config file '{}': {}".format(config_file, e))
python
def private_config_content(self): """ Returns the content of the current private-config file. """ config_file = self.private_config_file if config_file is None: return None try: with open(config_file, "rb") as f: return f.read().decode("utf-8", errors="replace") except OSError as e: raise IOUError("Can't read private-config file '{}': {}".format(config_file, e))
[ "def", "private_config_content", "(", "self", ")", ":", "config_file", "=", "self", ".", "private_config_file", "if", "config_file", "is", "None", ":", "return", "None", "try", ":", "with", "open", "(", "config_file", ",", "\"rb\"", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")", ".", "decode", "(", "\"utf-8\"", ",", "errors", "=", "\"replace\"", ")", "except", "OSError", "as", "e", ":", "raise", "IOUError", "(", "\"Can't read private-config file '{}': {}\"", ".", "format", "(", "config_file", ",", "e", ")", ")" ]
Returns the content of the current private-config file.
[ "Returns", "the", "content", "of", "the", "current", "private", "-", "config", "file", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L1037-L1050
226,716
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.private_config_content
def private_config_content(self, private_config): """ Update the private config :param private_config: content of the private configuration file """ try: private_config_path = os.path.join(self.working_dir, "private-config.cfg") if private_config is None: private_config = '' # We disallow erasing the private config file if len(private_config) == 0 and os.path.exists(private_config_path): return with open(private_config_path, 'w+', encoding='utf-8') as f: if len(private_config) == 0: f.write('') else: private_config = private_config.replace("%h", self._name) f.write(private_config) except OSError as e: raise IOUError("Can't write private-config file '{}': {}".format(private_config_path, e))
python
def private_config_content(self, private_config): """ Update the private config :param private_config: content of the private configuration file """ try: private_config_path = os.path.join(self.working_dir, "private-config.cfg") if private_config is None: private_config = '' # We disallow erasing the private config file if len(private_config) == 0 and os.path.exists(private_config_path): return with open(private_config_path, 'w+', encoding='utf-8') as f: if len(private_config) == 0: f.write('') else: private_config = private_config.replace("%h", self._name) f.write(private_config) except OSError as e: raise IOUError("Can't write private-config file '{}': {}".format(private_config_path, e))
[ "def", "private_config_content", "(", "self", ",", "private_config", ")", ":", "try", ":", "private_config_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "working_dir", ",", "\"private-config.cfg\"", ")", "if", "private_config", "is", "None", ":", "private_config", "=", "''", "# We disallow erasing the private config file", "if", "len", "(", "private_config", ")", "==", "0", "and", "os", ".", "path", ".", "exists", "(", "private_config_path", ")", ":", "return", "with", "open", "(", "private_config_path", ",", "'w+'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "if", "len", "(", "private_config", ")", "==", "0", ":", "f", ".", "write", "(", "''", ")", "else", ":", "private_config", "=", "private_config", ".", "replace", "(", "\"%h\"", ",", "self", ".", "_name", ")", "f", ".", "write", "(", "private_config", ")", "except", "OSError", "as", "e", ":", "raise", "IOUError", "(", "\"Can't write private-config file '{}': {}\"", ".", "format", "(", "private_config_path", ",", "e", ")", ")" ]
Update the private config :param private_config: content of the private configuration file
[ "Update", "the", "private", "config" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L1053-L1077
226,717
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.startup_config_file
def startup_config_file(self): """ Returns the startup-config file for this IOU VM. :returns: path to config file. None if the file doesn't exist """ path = os.path.join(self.working_dir, 'startup-config.cfg') if os.path.exists(path): return path else: return None
python
def startup_config_file(self): """ Returns the startup-config file for this IOU VM. :returns: path to config file. None if the file doesn't exist """ path = os.path.join(self.working_dir, 'startup-config.cfg') if os.path.exists(path): return path else: return None
[ "def", "startup_config_file", "(", "self", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "working_dir", ",", "'startup-config.cfg'", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "path", "else", ":", "return", "None" ]
Returns the startup-config file for this IOU VM. :returns: path to config file. None if the file doesn't exist
[ "Returns", "the", "startup", "-", "config", "file", "for", "this", "IOU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L1080-L1091
226,718
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.private_config_file
def private_config_file(self): """ Returns the private-config file for this IOU VM. :returns: path to config file. None if the file doesn't exist """ path = os.path.join(self.working_dir, 'private-config.cfg') if os.path.exists(path): return path else: return None
python
def private_config_file(self): """ Returns the private-config file for this IOU VM. :returns: path to config file. None if the file doesn't exist """ path = os.path.join(self.working_dir, 'private-config.cfg') if os.path.exists(path): return path else: return None
[ "def", "private_config_file", "(", "self", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "working_dir", ",", "'private-config.cfg'", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "path", "else", ":", "return", "None" ]
Returns the private-config file for this IOU VM. :returns: path to config file. None if the file doesn't exist
[ "Returns", "the", "private", "-", "config", "file", "for", "this", "IOU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L1094-L1105
226,719
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.relative_startup_config_file
def relative_startup_config_file(self): """ Returns the startup-config file relative to the project directory. It's compatible with pre 1.3 projects. :returns: path to startup-config file. None if the file doesn't exist """ path = os.path.join(self.working_dir, 'startup-config.cfg') if os.path.exists(path): return 'startup-config.cfg' else: return None
python
def relative_startup_config_file(self): """ Returns the startup-config file relative to the project directory. It's compatible with pre 1.3 projects. :returns: path to startup-config file. None if the file doesn't exist """ path = os.path.join(self.working_dir, 'startup-config.cfg') if os.path.exists(path): return 'startup-config.cfg' else: return None
[ "def", "relative_startup_config_file", "(", "self", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "working_dir", ",", "'startup-config.cfg'", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "'startup-config.cfg'", "else", ":", "return", "None" ]
Returns the startup-config file relative to the project directory. It's compatible with pre 1.3 projects. :returns: path to startup-config file. None if the file doesn't exist
[ "Returns", "the", "startup", "-", "config", "file", "relative", "to", "the", "project", "directory", ".", "It", "s", "compatible", "with", "pre", "1", ".", "3", "projects", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L1108-L1120
226,720
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.relative_private_config_file
def relative_private_config_file(self): """ Returns the private-config file relative to the project directory. :returns: path to private-config file. None if the file doesn't exist """ path = os.path.join(self.working_dir, 'private-config.cfg') if os.path.exists(path): return 'private-config.cfg' else: return None
python
def relative_private_config_file(self): """ Returns the private-config file relative to the project directory. :returns: path to private-config file. None if the file doesn't exist """ path = os.path.join(self.working_dir, 'private-config.cfg') if os.path.exists(path): return 'private-config.cfg' else: return None
[ "def", "relative_private_config_file", "(", "self", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "working_dir", ",", "'private-config.cfg'", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "'private-config.cfg'", "else", ":", "return", "None" ]
Returns the private-config file relative to the project directory. :returns: path to private-config file. None if the file doesn't exist
[ "Returns", "the", "private", "-", "config", "file", "relative", "to", "the", "project", "directory", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L1123-L1134
226,721
GNS3/gns3-server
gns3server/controller/drawing.py
Drawing.svg
def svg(self, value): """ Set SVG field value. If the svg has embed base64 element we will extract them to disk in order to avoid duplication of content """ if len(value) < 500: self._svg = value return try: root = ET.fromstring(value) except ET.ParseError as e: log.error("Can't parse SVG: {}".format(e)) return # SVG is the default namespace no need to prefix it ET.register_namespace('xmlns', "http://www.w3.org/2000/svg") ET.register_namespace('xmlns:xlink', "http://www.w3.org/1999/xlink") if len(root.findall("{http://www.w3.org/2000/svg}image")) == 1: href = "{http://www.w3.org/1999/xlink}href" elem = root.find("{http://www.w3.org/2000/svg}image") if elem.get(href, "").startswith("data:image/"): changed = True data = elem.get(href, "") extension = re.sub(r"[^a-z0-9]", "", data.split(";")[0].split("/")[1].lower()) data = base64.decodebytes(data.split(",", 1)[1].encode()) # We compute an hash of the image file to avoid duplication filename = hashlib.md5(data).hexdigest() + "." + extension elem.set(href, filename) file_path = os.path.join(self._project.pictures_directory, filename) if not os.path.exists(file_path): with open(file_path, "wb") as f: f.write(data) value = filename # We dump also large svg on disk to keep .gns3 small if len(value) > 1000: filename = hashlib.md5(value.encode()).hexdigest() + ".svg" file_path = os.path.join(self._project.pictures_directory, filename) if not os.path.exists(file_path): with open(file_path, "w+", encoding="utf-8") as f: f.write(value) self._svg = filename else: self._svg = value
python
def svg(self, value): """ Set SVG field value. If the svg has embed base64 element we will extract them to disk in order to avoid duplication of content """ if len(value) < 500: self._svg = value return try: root = ET.fromstring(value) except ET.ParseError as e: log.error("Can't parse SVG: {}".format(e)) return # SVG is the default namespace no need to prefix it ET.register_namespace('xmlns', "http://www.w3.org/2000/svg") ET.register_namespace('xmlns:xlink', "http://www.w3.org/1999/xlink") if len(root.findall("{http://www.w3.org/2000/svg}image")) == 1: href = "{http://www.w3.org/1999/xlink}href" elem = root.find("{http://www.w3.org/2000/svg}image") if elem.get(href, "").startswith("data:image/"): changed = True data = elem.get(href, "") extension = re.sub(r"[^a-z0-9]", "", data.split(";")[0].split("/")[1].lower()) data = base64.decodebytes(data.split(",", 1)[1].encode()) # We compute an hash of the image file to avoid duplication filename = hashlib.md5(data).hexdigest() + "." + extension elem.set(href, filename) file_path = os.path.join(self._project.pictures_directory, filename) if not os.path.exists(file_path): with open(file_path, "wb") as f: f.write(data) value = filename # We dump also large svg on disk to keep .gns3 small if len(value) > 1000: filename = hashlib.md5(value.encode()).hexdigest() + ".svg" file_path = os.path.join(self._project.pictures_directory, filename) if not os.path.exists(file_path): with open(file_path, "w+", encoding="utf-8") as f: f.write(value) self._svg = filename else: self._svg = value
[ "def", "svg", "(", "self", ",", "value", ")", ":", "if", "len", "(", "value", ")", "<", "500", ":", "self", ".", "_svg", "=", "value", "return", "try", ":", "root", "=", "ET", ".", "fromstring", "(", "value", ")", "except", "ET", ".", "ParseError", "as", "e", ":", "log", ".", "error", "(", "\"Can't parse SVG: {}\"", ".", "format", "(", "e", ")", ")", "return", "# SVG is the default namespace no need to prefix it", "ET", ".", "register_namespace", "(", "'xmlns'", ",", "\"http://www.w3.org/2000/svg\"", ")", "ET", ".", "register_namespace", "(", "'xmlns:xlink'", ",", "\"http://www.w3.org/1999/xlink\"", ")", "if", "len", "(", "root", ".", "findall", "(", "\"{http://www.w3.org/2000/svg}image\"", ")", ")", "==", "1", ":", "href", "=", "\"{http://www.w3.org/1999/xlink}href\"", "elem", "=", "root", ".", "find", "(", "\"{http://www.w3.org/2000/svg}image\"", ")", "if", "elem", ".", "get", "(", "href", ",", "\"\"", ")", ".", "startswith", "(", "\"data:image/\"", ")", ":", "changed", "=", "True", "data", "=", "elem", ".", "get", "(", "href", ",", "\"\"", ")", "extension", "=", "re", ".", "sub", "(", "r\"[^a-z0-9]\"", ",", "\"\"", ",", "data", ".", "split", "(", "\";\"", ")", "[", "0", "]", ".", "split", "(", "\"/\"", ")", "[", "1", "]", ".", "lower", "(", ")", ")", "data", "=", "base64", ".", "decodebytes", "(", "data", ".", "split", "(", "\",\"", ",", "1", ")", "[", "1", "]", ".", "encode", "(", ")", ")", "# We compute an hash of the image file to avoid duplication", "filename", "=", "hashlib", ".", "md5", "(", "data", ")", ".", "hexdigest", "(", ")", "+", "\".\"", "+", "extension", "elem", ".", "set", "(", "href", ",", "filename", ")", "file_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_project", ".", "pictures_directory", ",", "filename", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "with", "open", "(", "file_path", ",", "\"wb\"", ")", "as", "f", ":", "f", ".", "write", "(", "data", ")", "value", "=", "filename", "# We dump also large svg on disk to keep .gns3 small", "if", "len", "(", "value", ")", ">", "1000", ":", "filename", "=", "hashlib", ".", "md5", "(", "value", ".", "encode", "(", ")", ")", ".", "hexdigest", "(", ")", "+", "\".svg\"", "file_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_project", ".", "pictures_directory", ",", "filename", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "with", "open", "(", "file_path", ",", "\"w+\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "f", ".", "write", "(", "value", ")", "self", ".", "_svg", "=", "filename", "else", ":", "self", ".", "_svg", "=", "value" ]
Set SVG field value. If the svg has embed base64 element we will extract them to disk in order to avoid duplication of content
[ "Set", "SVG", "field", "value", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/drawing.py#L84-L134
226,722
GNS3/gns3-server
gns3server/controller/drawing.py
Drawing.update
def update(self, **kwargs): """ Update the drawing :param kwargs: Drawing properties """ # Update node properties with additional elements svg_changed = False for prop in kwargs: if prop == "drawing_id": pass # No good reason to change a drawing_id elif getattr(self, prop) != kwargs[prop]: if prop == "svg": # To avoid spamming client with large data we don't send the svg if the SVG didn't change svg_changed = True setattr(self, prop, kwargs[prop]) data = self.__json__() if not svg_changed: del data["svg"] self._project.controller.notification.emit("drawing.updated", data) self._project.dump()
python
def update(self, **kwargs): """ Update the drawing :param kwargs: Drawing properties """ # Update node properties with additional elements svg_changed = False for prop in kwargs: if prop == "drawing_id": pass # No good reason to change a drawing_id elif getattr(self, prop) != kwargs[prop]: if prop == "svg": # To avoid spamming client with large data we don't send the svg if the SVG didn't change svg_changed = True setattr(self, prop, kwargs[prop]) data = self.__json__() if not svg_changed: del data["svg"] self._project.controller.notification.emit("drawing.updated", data) self._project.dump()
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Update node properties with additional elements", "svg_changed", "=", "False", "for", "prop", "in", "kwargs", ":", "if", "prop", "==", "\"drawing_id\"", ":", "pass", "# No good reason to change a drawing_id", "elif", "getattr", "(", "self", ",", "prop", ")", "!=", "kwargs", "[", "prop", "]", ":", "if", "prop", "==", "\"svg\"", ":", "# To avoid spamming client with large data we don't send the svg if the SVG didn't change", "svg_changed", "=", "True", "setattr", "(", "self", ",", "prop", ",", "kwargs", "[", "prop", "]", ")", "data", "=", "self", ".", "__json__", "(", ")", "if", "not", "svg_changed", ":", "del", "data", "[", "\"svg\"", "]", "self", ".", "_project", ".", "controller", ".", "notification", ".", "emit", "(", "\"drawing.updated\"", ",", "data", ")", "self", ".", "_project", ".", "dump", "(", ")" ]
Update the drawing :param kwargs: Drawing properties
[ "Update", "the", "drawing" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/drawing.py#L169-L190
226,723
GNS3/gns3-server
gns3server/compute/vpcs/__init__.py
VPCS.create_node
def create_node(self, *args, **kwargs): """ Creates a new VPCS VM. :returns: VPCSVM instance """ node = yield from super().create_node(*args, **kwargs) self._free_mac_ids.setdefault(node.project.id, list(range(0, 255))) try: self._used_mac_ids[node.id] = self._free_mac_ids[node.project.id].pop(0) except IndexError: raise VPCSError("Cannot create a new VPCS VM (limit of 255 VMs reached on this host)") return node
python
def create_node(self, *args, **kwargs): """ Creates a new VPCS VM. :returns: VPCSVM instance """ node = yield from super().create_node(*args, **kwargs) self._free_mac_ids.setdefault(node.project.id, list(range(0, 255))) try: self._used_mac_ids[node.id] = self._free_mac_ids[node.project.id].pop(0) except IndexError: raise VPCSError("Cannot create a new VPCS VM (limit of 255 VMs reached on this host)") return node
[ "def", "create_node", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "node", "=", "yield", "from", "super", "(", ")", ".", "create_node", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "_free_mac_ids", ".", "setdefault", "(", "node", ".", "project", ".", "id", ",", "list", "(", "range", "(", "0", ",", "255", ")", ")", ")", "try", ":", "self", ".", "_used_mac_ids", "[", "node", ".", "id", "]", "=", "self", ".", "_free_mac_ids", "[", "node", ".", "project", ".", "id", "]", ".", "pop", "(", "0", ")", "except", "IndexError", ":", "raise", "VPCSError", "(", "\"Cannot create a new VPCS VM (limit of 255 VMs reached on this host)\"", ")", "return", "node" ]
Creates a new VPCS VM. :returns: VPCSVM instance
[ "Creates", "a", "new", "VPCS", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/__init__.py#L41-L54
226,724
GNS3/gns3-server
gns3server/compute/vpcs/__init__.py
VPCS.close_node
def close_node(self, node_id, *args, **kwargs): """ Closes a VPCS VM. :returns: VPCSVM instance """ node = self.get_node(node_id) if node_id in self._used_mac_ids: i = self._used_mac_ids[node_id] self._free_mac_ids[node.project.id].insert(0, i) del self._used_mac_ids[node_id] yield from super().close_node(node_id, *args, **kwargs) return node
python
def close_node(self, node_id, *args, **kwargs): """ Closes a VPCS VM. :returns: VPCSVM instance """ node = self.get_node(node_id) if node_id in self._used_mac_ids: i = self._used_mac_ids[node_id] self._free_mac_ids[node.project.id].insert(0, i) del self._used_mac_ids[node_id] yield from super().close_node(node_id, *args, **kwargs) return node
[ "def", "close_node", "(", "self", ",", "node_id", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "node", "=", "self", ".", "get_node", "(", "node_id", ")", "if", "node_id", "in", "self", ".", "_used_mac_ids", ":", "i", "=", "self", ".", "_used_mac_ids", "[", "node_id", "]", "self", ".", "_free_mac_ids", "[", "node", ".", "project", ".", "id", "]", ".", "insert", "(", "0", ",", "i", ")", "del", "self", ".", "_used_mac_ids", "[", "node_id", "]", "yield", "from", "super", "(", ")", ".", "close_node", "(", "node_id", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "node" ]
Closes a VPCS VM. :returns: VPCSVM instance
[ "Closes", "a", "VPCS", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/__init__.py#L57-L70
226,725
GNS3/gns3-server
gns3server/compute/dynamips/nios/nio.py
NIO.delete
def delete(self): """ Deletes this NIO. """ if self._input_filter or self._output_filter: yield from self.unbind_filter("both") yield from self._hypervisor.send("nio delete {}".format(self._name)) log.info("NIO {name} has been deleted".format(name=self._name))
python
def delete(self): """ Deletes this NIO. """ if self._input_filter or self._output_filter: yield from self.unbind_filter("both") yield from self._hypervisor.send("nio delete {}".format(self._name)) log.info("NIO {name} has been deleted".format(name=self._name))
[ "def", "delete", "(", "self", ")", ":", "if", "self", ".", "_input_filter", "or", "self", ".", "_output_filter", ":", "yield", "from", "self", ".", "unbind_filter", "(", "\"both\"", ")", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "\"nio delete {}\"", ".", "format", "(", "self", ".", "_name", ")", ")", "log", ".", "info", "(", "\"NIO {name} has been deleted\"", ".", "format", "(", "name", "=", "self", ".", "_name", ")", ")" ]
Deletes this NIO.
[ "Deletes", "this", "NIO", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L61-L69
226,726
GNS3/gns3-server
gns3server/compute/dynamips/nios/nio.py
NIO.rename
def rename(self, new_name): """ Renames this NIO :param new_name: new NIO name """ yield from self._hypervisor.send("nio rename {name} {new_name}".format(name=self._name, new_name=new_name)) log.info("NIO {name} renamed to {new_name}".format(name=self._name, new_name=new_name)) self._name = new_name
python
def rename(self, new_name): """ Renames this NIO :param new_name: new NIO name """ yield from self._hypervisor.send("nio rename {name} {new_name}".format(name=self._name, new_name=new_name)) log.info("NIO {name} renamed to {new_name}".format(name=self._name, new_name=new_name)) self._name = new_name
[ "def", "rename", "(", "self", ",", "new_name", ")", ":", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "\"nio rename {name} {new_name}\"", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "new_name", "=", "new_name", ")", ")", "log", ".", "info", "(", "\"NIO {name} renamed to {new_name}\"", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "new_name", "=", "new_name", ")", ")", "self", ".", "_name", "=", "new_name" ]
Renames this NIO :param new_name: new NIO name
[ "Renames", "this", "NIO" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L72-L82
226,727
GNS3/gns3-server
gns3server/compute/dynamips/nios/nio.py
NIO.bind_filter
def bind_filter(self, direction, filter_name): """ Adds a packet filter to this NIO. Filter "freq_drop" drops packets. Filter "capture" captures packets. :param direction: "in", "out" or "both" :param filter_name: name of the filter to apply """ if direction not in self._dynamips_direction: raise DynamipsError("Unknown direction {} to bind filter {}:".format(direction, filter_name)) dynamips_direction = self._dynamips_direction[direction] yield from self._hypervisor.send("nio bind_filter {name} {direction} {filter}".format(name=self._name, direction=dynamips_direction, filter=filter_name)) if direction == "in": self._input_filter = filter_name elif direction == "out": self._output_filter = filter_name elif direction == "both": self._input_filter = filter_name self._output_filter = filter_name
python
def bind_filter(self, direction, filter_name): """ Adds a packet filter to this NIO. Filter "freq_drop" drops packets. Filter "capture" captures packets. :param direction: "in", "out" or "both" :param filter_name: name of the filter to apply """ if direction not in self._dynamips_direction: raise DynamipsError("Unknown direction {} to bind filter {}:".format(direction, filter_name)) dynamips_direction = self._dynamips_direction[direction] yield from self._hypervisor.send("nio bind_filter {name} {direction} {filter}".format(name=self._name, direction=dynamips_direction, filter=filter_name)) if direction == "in": self._input_filter = filter_name elif direction == "out": self._output_filter = filter_name elif direction == "both": self._input_filter = filter_name self._output_filter = filter_name
[ "def", "bind_filter", "(", "self", ",", "direction", ",", "filter_name", ")", ":", "if", "direction", "not", "in", "self", ".", "_dynamips_direction", ":", "raise", "DynamipsError", "(", "\"Unknown direction {} to bind filter {}:\"", ".", "format", "(", "direction", ",", "filter_name", ")", ")", "dynamips_direction", "=", "self", ".", "_dynamips_direction", "[", "direction", "]", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "\"nio bind_filter {name} {direction} {filter}\"", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "direction", "=", "dynamips_direction", ",", "filter", "=", "filter_name", ")", ")", "if", "direction", "==", "\"in\"", ":", "self", ".", "_input_filter", "=", "filter_name", "elif", "direction", "==", "\"out\"", ":", "self", ".", "_output_filter", "=", "filter_name", "elif", "direction", "==", "\"both\"", ":", "self", ".", "_input_filter", "=", "filter_name", "self", ".", "_output_filter", "=", "filter_name" ]
Adds a packet filter to this NIO. Filter "freq_drop" drops packets. Filter "capture" captures packets. :param direction: "in", "out" or "both" :param filter_name: name of the filter to apply
[ "Adds", "a", "packet", "filter", "to", "this", "NIO", ".", "Filter", "freq_drop", "drops", "packets", ".", "Filter", "capture", "captures", "packets", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L95-L119
226,728
GNS3/gns3-server
gns3server/compute/dynamips/nios/nio.py
NIO.unbind_filter
def unbind_filter(self, direction): """ Removes packet filter for this NIO. :param direction: "in", "out" or "both" """ if direction not in self._dynamips_direction: raise DynamipsError("Unknown direction {} to unbind filter:".format(direction)) dynamips_direction = self._dynamips_direction[direction] yield from self._hypervisor.send("nio unbind_filter {name} {direction}".format(name=self._name, direction=dynamips_direction)) if direction == "in": self._input_filter = None elif direction == "out": self._output_filter = None elif direction == "both": self._input_filter = None self._output_filter = None
python
def unbind_filter(self, direction): """ Removes packet filter for this NIO. :param direction: "in", "out" or "both" """ if direction not in self._dynamips_direction: raise DynamipsError("Unknown direction {} to unbind filter:".format(direction)) dynamips_direction = self._dynamips_direction[direction] yield from self._hypervisor.send("nio unbind_filter {name} {direction}".format(name=self._name, direction=dynamips_direction)) if direction == "in": self._input_filter = None elif direction == "out": self._output_filter = None elif direction == "both": self._input_filter = None self._output_filter = None
[ "def", "unbind_filter", "(", "self", ",", "direction", ")", ":", "if", "direction", "not", "in", "self", ".", "_dynamips_direction", ":", "raise", "DynamipsError", "(", "\"Unknown direction {} to unbind filter:\"", ".", "format", "(", "direction", ")", ")", "dynamips_direction", "=", "self", ".", "_dynamips_direction", "[", "direction", "]", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "\"nio unbind_filter {name} {direction}\"", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "direction", "=", "dynamips_direction", ")", ")", "if", "direction", "==", "\"in\"", ":", "self", ".", "_input_filter", "=", "None", "elif", "direction", "==", "\"out\"", ":", "self", ".", "_output_filter", "=", "None", "elif", "direction", "==", "\"both\"", ":", "self", ".", "_input_filter", "=", "None", "self", ".", "_output_filter", "=", "None" ]
Removes packet filter for this NIO. :param direction: "in", "out" or "both"
[ "Removes", "packet", "filter", "for", "this", "NIO", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L122-L142
226,729
GNS3/gns3-server
gns3server/compute/dynamips/nios/nio.py
NIO.setup_filter
def setup_filter(self, direction, options): """ Setups a packet filter bound with this NIO. Filter "freq_drop" has 1 argument "<frequency>". It will drop everything with a -1 frequency, drop every Nth packet with a positive frequency, or drop nothing. Filter "capture" has 2 arguments "<link_type_name> <output_file>". It will capture packets to the target output file. The link type name is a case-insensitive DLT_ name from the PCAP library constants with the DLT_ part removed.See http://www.tcpdump.org/linktypes.html for a list of all available DLT values. :param direction: "in", "out" or "both" :param options: options for the packet filter (string) """ if direction not in self._dynamips_direction: raise DynamipsError("Unknown direction {} to setup filter:".format(direction)) dynamips_direction = self._dynamips_direction[direction] yield from self._hypervisor.send("nio setup_filter {name} {direction} {options}".format(name=self._name, direction=dynamips_direction, options=options)) if direction == "in": self._input_filter_options = options elif direction == "out": self._output_filter_options = options elif direction == "both": self._input_filter_options = options self._output_filter_options = options
python
def setup_filter(self, direction, options): """ Setups a packet filter bound with this NIO. Filter "freq_drop" has 1 argument "<frequency>". It will drop everything with a -1 frequency, drop every Nth packet with a positive frequency, or drop nothing. Filter "capture" has 2 arguments "<link_type_name> <output_file>". It will capture packets to the target output file. The link type name is a case-insensitive DLT_ name from the PCAP library constants with the DLT_ part removed.See http://www.tcpdump.org/linktypes.html for a list of all available DLT values. :param direction: "in", "out" or "both" :param options: options for the packet filter (string) """ if direction not in self._dynamips_direction: raise DynamipsError("Unknown direction {} to setup filter:".format(direction)) dynamips_direction = self._dynamips_direction[direction] yield from self._hypervisor.send("nio setup_filter {name} {direction} {options}".format(name=self._name, direction=dynamips_direction, options=options)) if direction == "in": self._input_filter_options = options elif direction == "out": self._output_filter_options = options elif direction == "both": self._input_filter_options = options self._output_filter_options = options
[ "def", "setup_filter", "(", "self", ",", "direction", ",", "options", ")", ":", "if", "direction", "not", "in", "self", ".", "_dynamips_direction", ":", "raise", "DynamipsError", "(", "\"Unknown direction {} to setup filter:\"", ".", "format", "(", "direction", ")", ")", "dynamips_direction", "=", "self", ".", "_dynamips_direction", "[", "direction", "]", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "\"nio setup_filter {name} {direction} {options}\"", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "direction", "=", "dynamips_direction", ",", "options", "=", "options", ")", ")", "if", "direction", "==", "\"in\"", ":", "self", ".", "_input_filter_options", "=", "options", "elif", "direction", "==", "\"out\"", ":", "self", ".", "_output_filter_options", "=", "options", "elif", "direction", "==", "\"both\"", ":", "self", ".", "_input_filter_options", "=", "options", "self", ".", "_output_filter_options", "=", "options" ]
Setups a packet filter bound with this NIO. Filter "freq_drop" has 1 argument "<frequency>". It will drop everything with a -1 frequency, drop every Nth packet with a positive frequency, or drop nothing. Filter "capture" has 2 arguments "<link_type_name> <output_file>". It will capture packets to the target output file. The link type name is a case-insensitive DLT_ name from the PCAP library constants with the DLT_ part removed.See http://www.tcpdump.org/linktypes.html for a list of all available DLT values. :param direction: "in", "out" or "both" :param options: options for the packet filter (string)
[ "Setups", "a", "packet", "filter", "bound", "with", "this", "NIO", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L145-L177
226,730
GNS3/gns3-server
gns3server/compute/dynamips/nios/nio.py
NIO.get_stats
def get_stats(self): """ Gets statistics for this NIO. :returns: NIO statistics (string with packets in, packets out, bytes in, bytes out) """ stats = yield from self._hypervisor.send("nio get_stats {}".format(self._name)) return stats[0]
python
def get_stats(self): """ Gets statistics for this NIO. :returns: NIO statistics (string with packets in, packets out, bytes in, bytes out) """ stats = yield from self._hypervisor.send("nio get_stats {}".format(self._name)) return stats[0]
[ "def", "get_stats", "(", "self", ")", ":", "stats", "=", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "\"nio get_stats {}\"", ".", "format", "(", "self", ".", "_name", ")", ")", "return", "stats", "[", "0", "]" ]
Gets statistics for this NIO. :returns: NIO statistics (string with packets in, packets out, bytes in, bytes out)
[ "Gets", "statistics", "for", "this", "NIO", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L200-L208
226,731
GNS3/gns3-server
gns3server/compute/dynamips/nios/nio.py
NIO.set_bandwidth
def set_bandwidth(self, bandwidth): """ Sets bandwidth constraint. :param bandwidth: bandwidth integer value (in Kb/s) """ yield from self._hypervisor.send("nio set_bandwidth {name} {bandwidth}".format(name=self._name, bandwidth=bandwidth)) self._bandwidth = bandwidth
python
def set_bandwidth(self, bandwidth): """ Sets bandwidth constraint. :param bandwidth: bandwidth integer value (in Kb/s) """ yield from self._hypervisor.send("nio set_bandwidth {name} {bandwidth}".format(name=self._name, bandwidth=bandwidth)) self._bandwidth = bandwidth
[ "def", "set_bandwidth", "(", "self", ",", "bandwidth", ")", ":", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "\"nio set_bandwidth {name} {bandwidth}\"", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "bandwidth", "=", "bandwidth", ")", ")", "self", ".", "_bandwidth", "=", "bandwidth" ]
Sets bandwidth constraint. :param bandwidth: bandwidth integer value (in Kb/s)
[ "Sets", "bandwidth", "constraint", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L229-L237
226,732
GNS3/gns3-server
gns3server/controller/node.py
Node.create
def create(self): """ Create the node on the compute server """ data = self._node_data() data["node_id"] = self._id if self._node_type == "docker": timeout = None else: timeout = 1200 trial = 0 while trial != 6: try: response = yield from self._compute.post("/projects/{}/{}/nodes".format(self._project.id, self._node_type), data=data, timeout=timeout) except ComputeConflict as e: if e.response.get("exception") == "ImageMissingError": res = yield from self._upload_missing_image(self._node_type, e.response["image"]) if not res: raise e else: raise e else: yield from self.parse_node_response(response.json) return True trial += 1
python
def create(self): """ Create the node on the compute server """ data = self._node_data() data["node_id"] = self._id if self._node_type == "docker": timeout = None else: timeout = 1200 trial = 0 while trial != 6: try: response = yield from self._compute.post("/projects/{}/{}/nodes".format(self._project.id, self._node_type), data=data, timeout=timeout) except ComputeConflict as e: if e.response.get("exception") == "ImageMissingError": res = yield from self._upload_missing_image(self._node_type, e.response["image"]) if not res: raise e else: raise e else: yield from self.parse_node_response(response.json) return True trial += 1
[ "def", "create", "(", "self", ")", ":", "data", "=", "self", ".", "_node_data", "(", ")", "data", "[", "\"node_id\"", "]", "=", "self", ".", "_id", "if", "self", ".", "_node_type", "==", "\"docker\"", ":", "timeout", "=", "None", "else", ":", "timeout", "=", "1200", "trial", "=", "0", "while", "trial", "!=", "6", ":", "try", ":", "response", "=", "yield", "from", "self", ".", "_compute", ".", "post", "(", "\"/projects/{}/{}/nodes\"", ".", "format", "(", "self", ".", "_project", ".", "id", ",", "self", ".", "_node_type", ")", ",", "data", "=", "data", ",", "timeout", "=", "timeout", ")", "except", "ComputeConflict", "as", "e", ":", "if", "e", ".", "response", ".", "get", "(", "\"exception\"", ")", "==", "\"ImageMissingError\"", ":", "res", "=", "yield", "from", "self", ".", "_upload_missing_image", "(", "self", ".", "_node_type", ",", "e", ".", "response", "[", "\"image\"", "]", ")", "if", "not", "res", ":", "raise", "e", "else", ":", "raise", "e", "else", ":", "yield", "from", "self", ".", "parse_node_response", "(", "response", ".", "json", ")", "return", "True", "trial", "+=", "1" ]
Create the node on the compute server
[ "Create", "the", "node", "on", "the", "compute", "server" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L326-L350
226,733
GNS3/gns3-server
gns3server/controller/node.py
Node.update
def update(self, **kwargs): """ Update the node on the compute server :param kwargs: Node properties """ # When updating properties used only on controller we don't need to call the compute update_compute = False old_json = self.__json__() compute_properties = None # Update node properties with additional elements for prop in kwargs: if getattr(self, prop) != kwargs[prop]: if prop not in self.CONTROLLER_ONLY_PROPERTIES: update_compute = True # We update properties on the compute and wait for the anwser from the compute node if prop == "properties": compute_properties = kwargs[prop] else: setattr(self, prop, kwargs[prop]) self._list_ports() # We send notif only if object has changed if old_json != self.__json__(): self.project.controller.notification.emit("node.updated", self.__json__()) if update_compute: data = self._node_data(properties=compute_properties) response = yield from self.put(None, data=data) yield from self.parse_node_response(response.json) self.project.dump()
python
def update(self, **kwargs): """ Update the node on the compute server :param kwargs: Node properties """ # When updating properties used only on controller we don't need to call the compute update_compute = False old_json = self.__json__() compute_properties = None # Update node properties with additional elements for prop in kwargs: if getattr(self, prop) != kwargs[prop]: if prop not in self.CONTROLLER_ONLY_PROPERTIES: update_compute = True # We update properties on the compute and wait for the anwser from the compute node if prop == "properties": compute_properties = kwargs[prop] else: setattr(self, prop, kwargs[prop]) self._list_ports() # We send notif only if object has changed if old_json != self.__json__(): self.project.controller.notification.emit("node.updated", self.__json__()) if update_compute: data = self._node_data(properties=compute_properties) response = yield from self.put(None, data=data) yield from self.parse_node_response(response.json) self.project.dump()
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# When updating properties used only on controller we don't need to call the compute", "update_compute", "=", "False", "old_json", "=", "self", ".", "__json__", "(", ")", "compute_properties", "=", "None", "# Update node properties with additional elements", "for", "prop", "in", "kwargs", ":", "if", "getattr", "(", "self", ",", "prop", ")", "!=", "kwargs", "[", "prop", "]", ":", "if", "prop", "not", "in", "self", ".", "CONTROLLER_ONLY_PROPERTIES", ":", "update_compute", "=", "True", "# We update properties on the compute and wait for the anwser from the compute node", "if", "prop", "==", "\"properties\"", ":", "compute_properties", "=", "kwargs", "[", "prop", "]", "else", ":", "setattr", "(", "self", ",", "prop", ",", "kwargs", "[", "prop", "]", ")", "self", ".", "_list_ports", "(", ")", "# We send notif only if object has changed", "if", "old_json", "!=", "self", ".", "__json__", "(", ")", ":", "self", ".", "project", ".", "controller", ".", "notification", ".", "emit", "(", "\"node.updated\"", ",", "self", ".", "__json__", "(", ")", ")", "if", "update_compute", ":", "data", "=", "self", ".", "_node_data", "(", "properties", "=", "compute_properties", ")", "response", "=", "yield", "from", "self", ".", "put", "(", "None", ",", "data", "=", "data", ")", "yield", "from", "self", ".", "parse_node_response", "(", "response", ".", "json", ")", "self", ".", "project", ".", "dump", "(", ")" ]
Update the node on the compute server :param kwargs: Node properties
[ "Update", "the", "node", "on", "the", "compute", "server" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L353-L386
226,734
GNS3/gns3-server
gns3server/controller/node.py
Node.parse_node_response
def parse_node_response(self, response): """ Update the object with the remote node object """ for key, value in response.items(): if key == "console": self._console = value elif key == "node_directory": self._node_directory = value elif key == "command_line": self._command_line = value elif key == "status": self._status = value elif key == "console_type": self._console_type = value elif key == "name": self.name = value elif key in ["node_id", "project_id", "console_host", "startup_config_content", "private_config_content", "startup_script"]: if key in self._properties: del self._properties[key] else: self._properties[key] = value self._list_ports() for link in self._links: yield from link.node_updated(self)
python
def parse_node_response(self, response): """ Update the object with the remote node object """ for key, value in response.items(): if key == "console": self._console = value elif key == "node_directory": self._node_directory = value elif key == "command_line": self._command_line = value elif key == "status": self._status = value elif key == "console_type": self._console_type = value elif key == "name": self.name = value elif key in ["node_id", "project_id", "console_host", "startup_config_content", "private_config_content", "startup_script"]: if key in self._properties: del self._properties[key] else: self._properties[key] = value self._list_ports() for link in self._links: yield from link.node_updated(self)
[ "def", "parse_node_response", "(", "self", ",", "response", ")", ":", "for", "key", ",", "value", "in", "response", ".", "items", "(", ")", ":", "if", "key", "==", "\"console\"", ":", "self", ".", "_console", "=", "value", "elif", "key", "==", "\"node_directory\"", ":", "self", ".", "_node_directory", "=", "value", "elif", "key", "==", "\"command_line\"", ":", "self", ".", "_command_line", "=", "value", "elif", "key", "==", "\"status\"", ":", "self", ".", "_status", "=", "value", "elif", "key", "==", "\"console_type\"", ":", "self", ".", "_console_type", "=", "value", "elif", "key", "==", "\"name\"", ":", "self", ".", "name", "=", "value", "elif", "key", "in", "[", "\"node_id\"", ",", "\"project_id\"", ",", "\"console_host\"", ",", "\"startup_config_content\"", ",", "\"private_config_content\"", ",", "\"startup_script\"", "]", ":", "if", "key", "in", "self", ".", "_properties", ":", "del", "self", ".", "_properties", "[", "key", "]", "else", ":", "self", ".", "_properties", "[", "key", "]", "=", "value", "self", ".", "_list_ports", "(", ")", "for", "link", "in", "self", ".", "_links", ":", "yield", "from", "link", ".", "node_updated", "(", "self", ")" ]
Update the object with the remote node object
[ "Update", "the", "object", "with", "the", "remote", "node", "object" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L389-L416
226,735
GNS3/gns3-server
gns3server/controller/node.py
Node._node_data
def _node_data(self, properties=None): """ Prepare node data to send to the remote controller :param properties: If properties is None use actual property otherwise use the parameter """ if properties: data = copy.copy(properties) else: data = copy.copy(self._properties) # We replace the startup script name by the content of the file mapping = { "base_script_file": "startup_script", "startup_config": "startup_config_content", "private_config": "private_config_content", } for k, v in mapping.items(): if k in list(self._properties.keys()): data[v] = self._base_config_file_content(self._properties[k]) del data[k] del self._properties[k] # We send the file only one time data["name"] = self._name if self._console: # console is optional for builtin nodes data["console"] = self._console if self._console_type: data["console_type"] = self._console_type # None properties are not be send. Because it can mean the emulator doesn't support it for key in list(data.keys()): if data[key] is None or data[key] is {} or key in self.CONTROLLER_ONLY_PROPERTIES: del data[key] return data
python
def _node_data(self, properties=None): """ Prepare node data to send to the remote controller :param properties: If properties is None use actual property otherwise use the parameter """ if properties: data = copy.copy(properties) else: data = copy.copy(self._properties) # We replace the startup script name by the content of the file mapping = { "base_script_file": "startup_script", "startup_config": "startup_config_content", "private_config": "private_config_content", } for k, v in mapping.items(): if k in list(self._properties.keys()): data[v] = self._base_config_file_content(self._properties[k]) del data[k] del self._properties[k] # We send the file only one time data["name"] = self._name if self._console: # console is optional for builtin nodes data["console"] = self._console if self._console_type: data["console_type"] = self._console_type # None properties are not be send. Because it can mean the emulator doesn't support it for key in list(data.keys()): if data[key] is None or data[key] is {} or key in self.CONTROLLER_ONLY_PROPERTIES: del data[key] return data
[ "def", "_node_data", "(", "self", ",", "properties", "=", "None", ")", ":", "if", "properties", ":", "data", "=", "copy", ".", "copy", "(", "properties", ")", "else", ":", "data", "=", "copy", ".", "copy", "(", "self", ".", "_properties", ")", "# We replace the startup script name by the content of the file", "mapping", "=", "{", "\"base_script_file\"", ":", "\"startup_script\"", ",", "\"startup_config\"", ":", "\"startup_config_content\"", ",", "\"private_config\"", ":", "\"private_config_content\"", ",", "}", "for", "k", ",", "v", "in", "mapping", ".", "items", "(", ")", ":", "if", "k", "in", "list", "(", "self", ".", "_properties", ".", "keys", "(", ")", ")", ":", "data", "[", "v", "]", "=", "self", ".", "_base_config_file_content", "(", "self", ".", "_properties", "[", "k", "]", ")", "del", "data", "[", "k", "]", "del", "self", ".", "_properties", "[", "k", "]", "# We send the file only one time", "data", "[", "\"name\"", "]", "=", "self", ".", "_name", "if", "self", ".", "_console", ":", "# console is optional for builtin nodes", "data", "[", "\"console\"", "]", "=", "self", ".", "_console", "if", "self", ".", "_console_type", ":", "data", "[", "\"console_type\"", "]", "=", "self", ".", "_console_type", "# None properties are not be send. Because it can mean the emulator doesn't support it", "for", "key", "in", "list", "(", "data", ".", "keys", "(", ")", ")", ":", "if", "data", "[", "key", "]", "is", "None", "or", "data", "[", "key", "]", "is", "{", "}", "or", "key", "in", "self", ".", "CONTROLLER_ONLY_PROPERTIES", ":", "del", "data", "[", "key", "]", "return", "data" ]
Prepare node data to send to the remote controller :param properties: If properties is None use actual property otherwise use the parameter
[ "Prepare", "node", "data", "to", "send", "to", "the", "remote", "controller" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L418-L450
226,736
GNS3/gns3-server
gns3server/controller/node.py
Node.reload
def reload(self): """ Suspend a node """ try: yield from self.post("/reload", timeout=240) except asyncio.TimeoutError: raise aiohttp.web.HTTPRequestTimeout(text="Timeout when reloading {}".format(self._name))
python
def reload(self): """ Suspend a node """ try: yield from self.post("/reload", timeout=240) except asyncio.TimeoutError: raise aiohttp.web.HTTPRequestTimeout(text="Timeout when reloading {}".format(self._name))
[ "def", "reload", "(", "self", ")", ":", "try", ":", "yield", "from", "self", ".", "post", "(", "\"/reload\"", ",", "timeout", "=", "240", ")", "except", "asyncio", ".", "TimeoutError", ":", "raise", "aiohttp", ".", "web", ".", "HTTPRequestTimeout", "(", "text", "=", "\"Timeout when reloading {}\"", ".", "format", "(", "self", ".", "_name", ")", ")" ]
Suspend a node
[ "Suspend", "a", "node" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L498-L505
226,737
GNS3/gns3-server
gns3server/controller/node.py
Node._upload_missing_image
def _upload_missing_image(self, type, img): """ Search an image on local computer and upload it to remote compute if the image exists """ for directory in images_directories(type): image = os.path.join(directory, img) if os.path.exists(image): self.project.controller.notification.emit("log.info", {"message": "Uploading missing image {}".format(img)}) try: with open(image, 'rb') as f: yield from self._compute.post("/{}/images/{}".format(self._node_type, os.path.basename(img)), data=f, timeout=None) except OSError as e: raise aiohttp.web.HTTPConflict(text="Can't upload {}: {}".format(image, str(e))) self.project.controller.notification.emit("log.info", {"message": "Upload finished for {}".format(img)}) return True return False
python
def _upload_missing_image(self, type, img): """ Search an image on local computer and upload it to remote compute if the image exists """ for directory in images_directories(type): image = os.path.join(directory, img) if os.path.exists(image): self.project.controller.notification.emit("log.info", {"message": "Uploading missing image {}".format(img)}) try: with open(image, 'rb') as f: yield from self._compute.post("/{}/images/{}".format(self._node_type, os.path.basename(img)), data=f, timeout=None) except OSError as e: raise aiohttp.web.HTTPConflict(text="Can't upload {}: {}".format(image, str(e))) self.project.controller.notification.emit("log.info", {"message": "Upload finished for {}".format(img)}) return True return False
[ "def", "_upload_missing_image", "(", "self", ",", "type", ",", "img", ")", ":", "for", "directory", "in", "images_directories", "(", "type", ")", ":", "image", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "img", ")", "if", "os", ".", "path", ".", "exists", "(", "image", ")", ":", "self", ".", "project", ".", "controller", ".", "notification", ".", "emit", "(", "\"log.info\"", ",", "{", "\"message\"", ":", "\"Uploading missing image {}\"", ".", "format", "(", "img", ")", "}", ")", "try", ":", "with", "open", "(", "image", ",", "'rb'", ")", "as", "f", ":", "yield", "from", "self", ".", "_compute", ".", "post", "(", "\"/{}/images/{}\"", ".", "format", "(", "self", ".", "_node_type", ",", "os", ".", "path", ".", "basename", "(", "img", ")", ")", ",", "data", "=", "f", ",", "timeout", "=", "None", ")", "except", "OSError", "as", "e", ":", "raise", "aiohttp", ".", "web", ".", "HTTPConflict", "(", "text", "=", "\"Can't upload {}: {}\"", ".", "format", "(", "image", ",", "str", "(", "e", ")", ")", ")", "self", ".", "project", ".", "controller", ".", "notification", ".", "emit", "(", "\"log.info\"", ",", "{", "\"message\"", ":", "\"Upload finished for {}\"", ".", "format", "(", "img", ")", "}", ")", "return", "True", "return", "False" ]
Search an image on local computer and upload it to remote compute if the image exists
[ "Search", "an", "image", "on", "local", "computer", "and", "upload", "it", "to", "remote", "compute", "if", "the", "image", "exists" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L542-L558
226,738
GNS3/gns3-server
gns3server/controller/node.py
Node.dynamips_auto_idlepc
def dynamips_auto_idlepc(self): """ Compute the idle PC for a dynamips node """ return (yield from self._compute.get("/projects/{}/{}/nodes/{}/auto_idlepc".format(self._project.id, self._node_type, self._id), timeout=240)).json
python
def dynamips_auto_idlepc(self): """ Compute the idle PC for a dynamips node """ return (yield from self._compute.get("/projects/{}/{}/nodes/{}/auto_idlepc".format(self._project.id, self._node_type, self._id), timeout=240)).json
[ "def", "dynamips_auto_idlepc", "(", "self", ")", ":", "return", "(", "yield", "from", "self", ".", "_compute", ".", "get", "(", "\"/projects/{}/{}/nodes/{}/auto_idlepc\"", ".", "format", "(", "self", ".", "_project", ".", "id", ",", "self", ".", "_node_type", ",", "self", ".", "_id", ")", ",", "timeout", "=", "240", ")", ")", ".", "json" ]
Compute the idle PC for a dynamips node
[ "Compute", "the", "idle", "PC", "for", "a", "dynamips", "node" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L561-L565
226,739
GNS3/gns3-server
gns3server/controller/node.py
Node.get_port
def get_port(self, adapter_number, port_number): """ Return the port for this adapter_number and port_number or returns None if the port is not found """ for port in self.ports: if port.adapter_number == adapter_number and port.port_number == port_number: return port return None
python
def get_port(self, adapter_number, port_number): """ Return the port for this adapter_number and port_number or returns None if the port is not found """ for port in self.ports: if port.adapter_number == adapter_number and port.port_number == port_number: return port return None
[ "def", "get_port", "(", "self", ",", "adapter_number", ",", "port_number", ")", ":", "for", "port", "in", "self", ".", "ports", ":", "if", "port", ".", "adapter_number", "==", "adapter_number", "and", "port", ".", "port_number", "==", "port_number", ":", "return", "port", "return", "None" ]
Return the port for this adapter_number and port_number or returns None if the port is not found
[ "Return", "the", "port", "for", "this", "adapter_number", "and", "port_number", "or", "returns", "None", "if", "the", "port", "is", "not", "found" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L574-L582
226,740
GNS3/gns3-server
gns3server/compute/dynamips/nodes/c1700.py
C1700.set_chassis
def set_chassis(self, chassis): """ Sets the chassis. :param: chassis string: 1720, 1721, 1750, 1751 or 1760 """ yield from self._hypervisor.send('c1700 set_chassis "{name}" {chassis}'.format(name=self._name, chassis=chassis)) log.info('Router "{name}" [{id}]: chassis set to {chassis}'.format(name=self._name, id=self._id, chassis=chassis)) self._chassis = chassis self._setup_chassis()
python
def set_chassis(self, chassis): """ Sets the chassis. :param: chassis string: 1720, 1721, 1750, 1751 or 1760 """ yield from self._hypervisor.send('c1700 set_chassis "{name}" {chassis}'.format(name=self._name, chassis=chassis)) log.info('Router "{name}" [{id}]: chassis set to {chassis}'.format(name=self._name, id=self._id, chassis=chassis)) self._chassis = chassis self._setup_chassis()
[ "def", "set_chassis", "(", "self", ",", "chassis", ")", ":", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'c1700 set_chassis \"{name}\" {chassis}'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "chassis", "=", "chassis", ")", ")", "log", ".", "info", "(", "'Router \"{name}\" [{id}]: chassis set to {chassis}'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "id", "=", "self", ".", "_id", ",", "chassis", "=", "chassis", ")", ")", "self", ".", "_chassis", "=", "chassis", "self", ".", "_setup_chassis", "(", ")" ]
Sets the chassis. :param: chassis string: 1720, 1721, 1750, 1751 or 1760
[ "Sets", "the", "chassis", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/c1700.py#L107-L122
226,741
GNS3/gns3-server
gns3server/controller/topology.py
load_topology
def load_topology(path): """ Open a topology file, patch it for last GNS3 release and return it """ log.debug("Read topology %s", path) try: with open(path, encoding="utf-8") as f: topo = json.load(f) except (OSError, UnicodeDecodeError, ValueError) as e: raise aiohttp.web.HTTPConflict(text="Could not load topology {}: {}".format(path, str(e))) if topo.get("revision", 0) > GNS3_FILE_FORMAT_REVISION: raise aiohttp.web.HTTPConflict(text="This project is designed for a more recent version of GNS3 please update GNS3 to version {} or later".format(topo["version"])) changed = False if "revision" not in topo or topo["revision"] < GNS3_FILE_FORMAT_REVISION: # If it's an old GNS3 file we need to convert it # first we backup the file try: shutil.copy(path, path + ".backup{}".format(topo.get("revision", 0))) except (OSError) as e: raise aiohttp.web.HTTPConflict(text="Can't write backup of the topology {}: {}".format(path, str(e))) changed = True if "revision" not in topo or topo["revision"] < 5: topo = _convert_1_3_later(topo, path) # Version before GNS3 2.0 alpha 4 if topo["revision"] < 6: topo = _convert_2_0_0_alpha(topo, path) # Version before GNS3 2.0 beta 3 if topo["revision"] < 7: topo = _convert_2_0_0_beta_2(topo, path) # Version before GNS3 2.1 if topo["revision"] < 8: topo = _convert_2_0_0(topo, path) try: _check_topology_schema(topo) except aiohttp.web.HTTPConflict as e: log.error("Can't load the topology %s", path) raise e if changed: try: with open(path, "w+", encoding="utf-8") as f: json.dump(topo, f, indent=4, sort_keys=True) except (OSError) as e: raise aiohttp.web.HTTPConflict(text="Can't write the topology {}: {}".format(path, str(e))) return topo
python
def load_topology(path): """ Open a topology file, patch it for last GNS3 release and return it """ log.debug("Read topology %s", path) try: with open(path, encoding="utf-8") as f: topo = json.load(f) except (OSError, UnicodeDecodeError, ValueError) as e: raise aiohttp.web.HTTPConflict(text="Could not load topology {}: {}".format(path, str(e))) if topo.get("revision", 0) > GNS3_FILE_FORMAT_REVISION: raise aiohttp.web.HTTPConflict(text="This project is designed for a more recent version of GNS3 please update GNS3 to version {} or later".format(topo["version"])) changed = False if "revision" not in topo or topo["revision"] < GNS3_FILE_FORMAT_REVISION: # If it's an old GNS3 file we need to convert it # first we backup the file try: shutil.copy(path, path + ".backup{}".format(topo.get("revision", 0))) except (OSError) as e: raise aiohttp.web.HTTPConflict(text="Can't write backup of the topology {}: {}".format(path, str(e))) changed = True if "revision" not in topo or topo["revision"] < 5: topo = _convert_1_3_later(topo, path) # Version before GNS3 2.0 alpha 4 if topo["revision"] < 6: topo = _convert_2_0_0_alpha(topo, path) # Version before GNS3 2.0 beta 3 if topo["revision"] < 7: topo = _convert_2_0_0_beta_2(topo, path) # Version before GNS3 2.1 if topo["revision"] < 8: topo = _convert_2_0_0(topo, path) try: _check_topology_schema(topo) except aiohttp.web.HTTPConflict as e: log.error("Can't load the topology %s", path) raise e if changed: try: with open(path, "w+", encoding="utf-8") as f: json.dump(topo, f, indent=4, sort_keys=True) except (OSError) as e: raise aiohttp.web.HTTPConflict(text="Can't write the topology {}: {}".format(path, str(e))) return topo
[ "def", "load_topology", "(", "path", ")", ":", "log", ".", "debug", "(", "\"Read topology %s\"", ",", "path", ")", "try", ":", "with", "open", "(", "path", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "topo", "=", "json", ".", "load", "(", "f", ")", "except", "(", "OSError", ",", "UnicodeDecodeError", ",", "ValueError", ")", "as", "e", ":", "raise", "aiohttp", ".", "web", ".", "HTTPConflict", "(", "text", "=", "\"Could not load topology {}: {}\"", ".", "format", "(", "path", ",", "str", "(", "e", ")", ")", ")", "if", "topo", ".", "get", "(", "\"revision\"", ",", "0", ")", ">", "GNS3_FILE_FORMAT_REVISION", ":", "raise", "aiohttp", ".", "web", ".", "HTTPConflict", "(", "text", "=", "\"This project is designed for a more recent version of GNS3 please update GNS3 to version {} or later\"", ".", "format", "(", "topo", "[", "\"version\"", "]", ")", ")", "changed", "=", "False", "if", "\"revision\"", "not", "in", "topo", "or", "topo", "[", "\"revision\"", "]", "<", "GNS3_FILE_FORMAT_REVISION", ":", "# If it's an old GNS3 file we need to convert it", "# first we backup the file", "try", ":", "shutil", ".", "copy", "(", "path", ",", "path", "+", "\".backup{}\"", ".", "format", "(", "topo", ".", "get", "(", "\"revision\"", ",", "0", ")", ")", ")", "except", "(", "OSError", ")", "as", "e", ":", "raise", "aiohttp", ".", "web", ".", "HTTPConflict", "(", "text", "=", "\"Can't write backup of the topology {}: {}\"", ".", "format", "(", "path", ",", "str", "(", "e", ")", ")", ")", "changed", "=", "True", "if", "\"revision\"", "not", "in", "topo", "or", "topo", "[", "\"revision\"", "]", "<", "5", ":", "topo", "=", "_convert_1_3_later", "(", "topo", ",", "path", ")", "# Version before GNS3 2.0 alpha 4", "if", "topo", "[", "\"revision\"", "]", "<", "6", ":", "topo", "=", "_convert_2_0_0_alpha", "(", "topo", ",", "path", ")", "# Version before GNS3 2.0 beta 3", "if", "topo", "[", "\"revision\"", "]", "<", "7", ":", "topo", "=", "_convert_2_0_0_beta_2", "(", "topo", ",", "path", ")", "# Version before GNS3 2.1", "if", "topo", "[", "\"revision\"", "]", "<", "8", ":", "topo", "=", "_convert_2_0_0", "(", "topo", ",", "path", ")", "try", ":", "_check_topology_schema", "(", "topo", ")", "except", "aiohttp", ".", "web", ".", "HTTPConflict", "as", "e", ":", "log", ".", "error", "(", "\"Can't load the topology %s\"", ",", "path", ")", "raise", "e", "if", "changed", ":", "try", ":", "with", "open", "(", "path", ",", "\"w+\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "json", ".", "dump", "(", "topo", ",", "f", ",", "indent", "=", "4", ",", "sort_keys", "=", "True", ")", "except", "(", "OSError", ")", "as", "e", ":", "raise", "aiohttp", ".", "web", ".", "HTTPConflict", "(", "text", "=", "\"Can't write the topology {}: {}\"", ".", "format", "(", "path", ",", "str", "(", "e", ")", ")", ")", "return", "topo" ]
Open a topology file, patch it for last GNS3 release and return it
[ "Open", "a", "topology", "file", "patch", "it", "for", "last", "GNS3", "release", "and", "return", "it" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/topology.py#L115-L166
226,742
GNS3/gns3-server
gns3server/controller/topology.py
_convert_2_0_0
def _convert_2_0_0(topo, topo_path): """ Convert topologies from GNS3 2.0.0 to 2.1 Changes: * Remove startup_script_path from VPCS and base config file for IOU and Dynamips """ topo["revision"] = 8 for node in topo.get("topology", {}).get("nodes", []): if "properties" in node: if node["node_type"] == "vpcs": if "startup_script_path" in node["properties"]: del node["properties"]["startup_script_path"] if "startup_script" in node["properties"]: del node["properties"]["startup_script"] elif node["node_type"] == "dynamips" or node["node_type"] == "iou": if "startup_config" in node["properties"]: del node["properties"]["startup_config"] if "private_config" in node["properties"]: del node["properties"]["private_config"] if "startup_config_content" in node["properties"]: del node["properties"]["startup_config_content"] if "private_config_content" in node["properties"]: del node["properties"]["private_config_content"] return topo
python
def _convert_2_0_0(topo, topo_path): """ Convert topologies from GNS3 2.0.0 to 2.1 Changes: * Remove startup_script_path from VPCS and base config file for IOU and Dynamips """ topo["revision"] = 8 for node in topo.get("topology", {}).get("nodes", []): if "properties" in node: if node["node_type"] == "vpcs": if "startup_script_path" in node["properties"]: del node["properties"]["startup_script_path"] if "startup_script" in node["properties"]: del node["properties"]["startup_script"] elif node["node_type"] == "dynamips" or node["node_type"] == "iou": if "startup_config" in node["properties"]: del node["properties"]["startup_config"] if "private_config" in node["properties"]: del node["properties"]["private_config"] if "startup_config_content" in node["properties"]: del node["properties"]["startup_config_content"] if "private_config_content" in node["properties"]: del node["properties"]["private_config_content"] return topo
[ "def", "_convert_2_0_0", "(", "topo", ",", "topo_path", ")", ":", "topo", "[", "\"revision\"", "]", "=", "8", "for", "node", "in", "topo", ".", "get", "(", "\"topology\"", ",", "{", "}", ")", ".", "get", "(", "\"nodes\"", ",", "[", "]", ")", ":", "if", "\"properties\"", "in", "node", ":", "if", "node", "[", "\"node_type\"", "]", "==", "\"vpcs\"", ":", "if", "\"startup_script_path\"", "in", "node", "[", "\"properties\"", "]", ":", "del", "node", "[", "\"properties\"", "]", "[", "\"startup_script_path\"", "]", "if", "\"startup_script\"", "in", "node", "[", "\"properties\"", "]", ":", "del", "node", "[", "\"properties\"", "]", "[", "\"startup_script\"", "]", "elif", "node", "[", "\"node_type\"", "]", "==", "\"dynamips\"", "or", "node", "[", "\"node_type\"", "]", "==", "\"iou\"", ":", "if", "\"startup_config\"", "in", "node", "[", "\"properties\"", "]", ":", "del", "node", "[", "\"properties\"", "]", "[", "\"startup_config\"", "]", "if", "\"private_config\"", "in", "node", "[", "\"properties\"", "]", ":", "del", "node", "[", "\"properties\"", "]", "[", "\"private_config\"", "]", "if", "\"startup_config_content\"", "in", "node", "[", "\"properties\"", "]", ":", "del", "node", "[", "\"properties\"", "]", "[", "\"startup_config_content\"", "]", "if", "\"private_config_content\"", "in", "node", "[", "\"properties\"", "]", ":", "del", "node", "[", "\"properties\"", "]", "[", "\"private_config_content\"", "]", "return", "topo" ]
Convert topologies from GNS3 2.0.0 to 2.1 Changes: * Remove startup_script_path from VPCS and base config file for IOU and Dynamips
[ "Convert", "topologies", "from", "GNS3", "2", ".", "0", ".", "0", "to", "2", ".", "1" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/topology.py#L169-L194
226,743
GNS3/gns3-server
gns3server/controller/topology.py
_convert_2_0_0_beta_2
def _convert_2_0_0_beta_2(topo, topo_path): """ Convert topologies from GNS3 2.0.0 beta 2 to beta 3. Changes: * Node id folders for dynamips """ topo_dir = os.path.dirname(topo_path) topo["revision"] = 7 for node in topo.get("topology", {}).get("nodes", []): if node["node_type"] == "dynamips": node_id = node["node_id"] dynamips_id = node["properties"]["dynamips_id"] dynamips_dir = os.path.join(topo_dir, "project-files", "dynamips") node_dir = os.path.join(dynamips_dir, node_id) try: os.makedirs(os.path.join(node_dir, "configs"), exist_ok=True) for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "*_i{}_*".format(dynamips_id))): shutil.move(path, os.path.join(node_dir, os.path.basename(path))) for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "configs", "i{}_*".format(dynamips_id))): shutil.move(path, os.path.join(node_dir, "configs", os.path.basename(path))) except OSError as e: raise aiohttp.web.HTTPConflict(text="Can't convert project {}: {}".format(topo_path, str(e))) return topo
python
def _convert_2_0_0_beta_2(topo, topo_path): """ Convert topologies from GNS3 2.0.0 beta 2 to beta 3. Changes: * Node id folders for dynamips """ topo_dir = os.path.dirname(topo_path) topo["revision"] = 7 for node in topo.get("topology", {}).get("nodes", []): if node["node_type"] == "dynamips": node_id = node["node_id"] dynamips_id = node["properties"]["dynamips_id"] dynamips_dir = os.path.join(topo_dir, "project-files", "dynamips") node_dir = os.path.join(dynamips_dir, node_id) try: os.makedirs(os.path.join(node_dir, "configs"), exist_ok=True) for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "*_i{}_*".format(dynamips_id))): shutil.move(path, os.path.join(node_dir, os.path.basename(path))) for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "configs", "i{}_*".format(dynamips_id))): shutil.move(path, os.path.join(node_dir, "configs", os.path.basename(path))) except OSError as e: raise aiohttp.web.HTTPConflict(text="Can't convert project {}: {}".format(topo_path, str(e))) return topo
[ "def", "_convert_2_0_0_beta_2", "(", "topo", ",", "topo_path", ")", ":", "topo_dir", "=", "os", ".", "path", ".", "dirname", "(", "topo_path", ")", "topo", "[", "\"revision\"", "]", "=", "7", "for", "node", "in", "topo", ".", "get", "(", "\"topology\"", ",", "{", "}", ")", ".", "get", "(", "\"nodes\"", ",", "[", "]", ")", ":", "if", "node", "[", "\"node_type\"", "]", "==", "\"dynamips\"", ":", "node_id", "=", "node", "[", "\"node_id\"", "]", "dynamips_id", "=", "node", "[", "\"properties\"", "]", "[", "\"dynamips_id\"", "]", "dynamips_dir", "=", "os", ".", "path", ".", "join", "(", "topo_dir", ",", "\"project-files\"", ",", "\"dynamips\"", ")", "node_dir", "=", "os", ".", "path", ".", "join", "(", "dynamips_dir", ",", "node_id", ")", "try", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "join", "(", "node_dir", ",", "\"configs\"", ")", ",", "exist_ok", "=", "True", ")", "for", "path", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "glob", ".", "escape", "(", "dynamips_dir", ")", ",", "\"*_i{}_*\"", ".", "format", "(", "dynamips_id", ")", ")", ")", ":", "shutil", ".", "move", "(", "path", ",", "os", ".", "path", ".", "join", "(", "node_dir", ",", "os", ".", "path", ".", "basename", "(", "path", ")", ")", ")", "for", "path", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "glob", ".", "escape", "(", "dynamips_dir", ")", ",", "\"configs\"", ",", "\"i{}_*\"", ".", "format", "(", "dynamips_id", ")", ")", ")", ":", "shutil", ".", "move", "(", "path", ",", "os", ".", "path", ".", "join", "(", "node_dir", ",", "\"configs\"", ",", "os", ".", "path", ".", "basename", "(", "path", ")", ")", ")", "except", "OSError", "as", "e", ":", "raise", "aiohttp", ".", "web", ".", "HTTPConflict", "(", "text", "=", "\"Can't convert project {}: {}\"", ".", "format", "(", "topo_path", ",", "str", "(", "e", ")", ")", ")", "return", "topo" ]
Convert topologies from GNS3 2.0.0 beta 2 to beta 3. Changes: * Node id folders for dynamips
[ "Convert", "topologies", "from", "GNS3", "2", ".", "0", ".", "0", "beta", "2", "to", "beta", "3", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/topology.py#L197-L222
226,744
GNS3/gns3-server
gns3server/controller/topology.py
_convert_2_0_0_alpha
def _convert_2_0_0_alpha(topo, topo_path): """ Convert topologies from GNS3 2.0.0 alpha to 2.0.0 final. Changes: * No more serial console * No more option for VMware / VirtualBox remote console (always use telnet) """ topo["revision"] = 6 for node in topo.get("topology", {}).get("nodes", []): if node.get("console_type") == "serial": node["console_type"] = "telnet" if node["node_type"] in ("vmware", "virtualbox"): prop = node.get("properties") if "enable_remote_console" in prop: del prop["enable_remote_console"] return topo
python
def _convert_2_0_0_alpha(topo, topo_path): """ Convert topologies from GNS3 2.0.0 alpha to 2.0.0 final. Changes: * No more serial console * No more option for VMware / VirtualBox remote console (always use telnet) """ topo["revision"] = 6 for node in topo.get("topology", {}).get("nodes", []): if node.get("console_type") == "serial": node["console_type"] = "telnet" if node["node_type"] in ("vmware", "virtualbox"): prop = node.get("properties") if "enable_remote_console" in prop: del prop["enable_remote_console"] return topo
[ "def", "_convert_2_0_0_alpha", "(", "topo", ",", "topo_path", ")", ":", "topo", "[", "\"revision\"", "]", "=", "6", "for", "node", "in", "topo", ".", "get", "(", "\"topology\"", ",", "{", "}", ")", ".", "get", "(", "\"nodes\"", ",", "[", "]", ")", ":", "if", "node", ".", "get", "(", "\"console_type\"", ")", "==", "\"serial\"", ":", "node", "[", "\"console_type\"", "]", "=", "\"telnet\"", "if", "node", "[", "\"node_type\"", "]", "in", "(", "\"vmware\"", ",", "\"virtualbox\"", ")", ":", "prop", "=", "node", ".", "get", "(", "\"properties\"", ")", "if", "\"enable_remote_console\"", "in", "prop", ":", "del", "prop", "[", "\"enable_remote_console\"", "]", "return", "topo" ]
Convert topologies from GNS3 2.0.0 alpha to 2.0.0 final. Changes: * No more serial console * No more option for VMware / VirtualBox remote console (always use telnet)
[ "Convert", "topologies", "from", "GNS3", "2", ".", "0", ".", "0", "alpha", "to", "2", ".", "0", ".", "0", "final", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/topology.py#L225-L241
226,745
GNS3/gns3-server
gns3server/controller/topology.py
_convert_label
def _convert_label(label): """ Convert a label from 1.X to the new format """ style = qt_font_to_style(label.get("font"), label.get("color")) return { "text": html.escape(label["text"]), "rotation": 0, "style": style, "x": int(label["x"]), "y": int(label["y"]) }
python
def _convert_label(label): """ Convert a label from 1.X to the new format """ style = qt_font_to_style(label.get("font"), label.get("color")) return { "text": html.escape(label["text"]), "rotation": 0, "style": style, "x": int(label["x"]), "y": int(label["y"]) }
[ "def", "_convert_label", "(", "label", ")", ":", "style", "=", "qt_font_to_style", "(", "label", ".", "get", "(", "\"font\"", ")", ",", "label", ".", "get", "(", "\"color\"", ")", ")", "return", "{", "\"text\"", ":", "html", ".", "escape", "(", "label", "[", "\"text\"", "]", ")", ",", "\"rotation\"", ":", "0", ",", "\"style\"", ":", "style", ",", "\"x\"", ":", "int", "(", "label", "[", "\"x\"", "]", ")", ",", "\"y\"", ":", "int", "(", "label", "[", "\"y\"", "]", ")", "}" ]
Convert a label from 1.X to the new format
[ "Convert", "a", "label", "from", "1", ".", "X", "to", "the", "new", "format" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/topology.py#L573-L584
226,746
GNS3/gns3-server
gns3server/controller/topology.py
_convert_snapshots
def _convert_snapshots(topo_dir): """ Convert 1.x snapshot to the new format """ old_snapshots_dir = os.path.join(topo_dir, "project-files", "snapshots") if os.path.exists(old_snapshots_dir): new_snapshots_dir = os.path.join(topo_dir, "snapshots") os.makedirs(new_snapshots_dir) for snapshot in os.listdir(old_snapshots_dir): snapshot_dir = os.path.join(old_snapshots_dir, snapshot) if os.path.isdir(snapshot_dir): is_gns3_topo = False # In .gns3project fileformat the .gns3 should be name project.gns3 for file in os.listdir(snapshot_dir): if file.endswith(".gns3"): shutil.move(os.path.join(snapshot_dir, file), os.path.join(snapshot_dir, "project.gns3")) is_gns3_topo = True if is_gns3_topo: snapshot_arc = os.path.join(new_snapshots_dir, snapshot + ".gns3project") with zipfile.ZipFile(snapshot_arc, 'w', allowZip64=True) as myzip: for root, dirs, files in os.walk(snapshot_dir): for file in files: myzip.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), snapshot_dir), compress_type=zipfile.ZIP_DEFLATED) shutil.rmtree(old_snapshots_dir)
python
def _convert_snapshots(topo_dir): """ Convert 1.x snapshot to the new format """ old_snapshots_dir = os.path.join(topo_dir, "project-files", "snapshots") if os.path.exists(old_snapshots_dir): new_snapshots_dir = os.path.join(topo_dir, "snapshots") os.makedirs(new_snapshots_dir) for snapshot in os.listdir(old_snapshots_dir): snapshot_dir = os.path.join(old_snapshots_dir, snapshot) if os.path.isdir(snapshot_dir): is_gns3_topo = False # In .gns3project fileformat the .gns3 should be name project.gns3 for file in os.listdir(snapshot_dir): if file.endswith(".gns3"): shutil.move(os.path.join(snapshot_dir, file), os.path.join(snapshot_dir, "project.gns3")) is_gns3_topo = True if is_gns3_topo: snapshot_arc = os.path.join(new_snapshots_dir, snapshot + ".gns3project") with zipfile.ZipFile(snapshot_arc, 'w', allowZip64=True) as myzip: for root, dirs, files in os.walk(snapshot_dir): for file in files: myzip.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), snapshot_dir), compress_type=zipfile.ZIP_DEFLATED) shutil.rmtree(old_snapshots_dir)
[ "def", "_convert_snapshots", "(", "topo_dir", ")", ":", "old_snapshots_dir", "=", "os", ".", "path", ".", "join", "(", "topo_dir", ",", "\"project-files\"", ",", "\"snapshots\"", ")", "if", "os", ".", "path", ".", "exists", "(", "old_snapshots_dir", ")", ":", "new_snapshots_dir", "=", "os", ".", "path", ".", "join", "(", "topo_dir", ",", "\"snapshots\"", ")", "os", ".", "makedirs", "(", "new_snapshots_dir", ")", "for", "snapshot", "in", "os", ".", "listdir", "(", "old_snapshots_dir", ")", ":", "snapshot_dir", "=", "os", ".", "path", ".", "join", "(", "old_snapshots_dir", ",", "snapshot", ")", "if", "os", ".", "path", ".", "isdir", "(", "snapshot_dir", ")", ":", "is_gns3_topo", "=", "False", "# In .gns3project fileformat the .gns3 should be name project.gns3", "for", "file", "in", "os", ".", "listdir", "(", "snapshot_dir", ")", ":", "if", "file", ".", "endswith", "(", "\".gns3\"", ")", ":", "shutil", ".", "move", "(", "os", ".", "path", ".", "join", "(", "snapshot_dir", ",", "file", ")", ",", "os", ".", "path", ".", "join", "(", "snapshot_dir", ",", "\"project.gns3\"", ")", ")", "is_gns3_topo", "=", "True", "if", "is_gns3_topo", ":", "snapshot_arc", "=", "os", ".", "path", ".", "join", "(", "new_snapshots_dir", ",", "snapshot", "+", "\".gns3project\"", ")", "with", "zipfile", ".", "ZipFile", "(", "snapshot_arc", ",", "'w'", ",", "allowZip64", "=", "True", ")", "as", "myzip", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "snapshot_dir", ")", ":", "for", "file", "in", "files", ":", "myzip", ".", "write", "(", "os", ".", "path", ".", "join", "(", "root", ",", "file", ")", ",", "os", ".", "path", ".", "relpath", "(", "os", ".", "path", ".", "join", "(", "root", ",", "file", ")", ",", "snapshot_dir", ")", ",", "compress_type", "=", "zipfile", ".", "ZIP_DEFLATED", ")", "shutil", ".", "rmtree", "(", "old_snapshots_dir", ")" ]
Convert 1.x snapshot to the new format
[ "Convert", "1", ".", "x", "snapshot", "to", "the", "new", "format" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/topology.py#L638-L665
226,747
GNS3/gns3-server
gns3server/controller/topology.py
_convert_qemu_node
def _convert_qemu_node(node, old_node): """ Convert qemu node from 1.X to 2.0 """ # In 2.0 the internet VM is replaced by the NAT node if old_node.get("properties", {}).get("hda_disk_image_md5sum") == "8ebc5a6ec53a1c05b7aa101b5ceefe31": node["console"] = None node["console_type"] = None node["node_type"] = "nat" del old_node["properties"] node["properties"] = { "ports": [ { "interface": "eth1", "name": "nat0", "port_number": 0, "type": "ethernet" } ] } if node["symbol"] is None: node["symbol"] = ":/symbols/cloud.svg" return node node["node_type"] = "qemu" if node["symbol"] is None: node["symbol"] = ":/symbols/qemu_guest.svg" return node
python
def _convert_qemu_node(node, old_node): """ Convert qemu node from 1.X to 2.0 """ # In 2.0 the internet VM is replaced by the NAT node if old_node.get("properties", {}).get("hda_disk_image_md5sum") == "8ebc5a6ec53a1c05b7aa101b5ceefe31": node["console"] = None node["console_type"] = None node["node_type"] = "nat" del old_node["properties"] node["properties"] = { "ports": [ { "interface": "eth1", "name": "nat0", "port_number": 0, "type": "ethernet" } ] } if node["symbol"] is None: node["symbol"] = ":/symbols/cloud.svg" return node node["node_type"] = "qemu" if node["symbol"] is None: node["symbol"] = ":/symbols/qemu_guest.svg" return node
[ "def", "_convert_qemu_node", "(", "node", ",", "old_node", ")", ":", "# In 2.0 the internet VM is replaced by the NAT node", "if", "old_node", ".", "get", "(", "\"properties\"", ",", "{", "}", ")", ".", "get", "(", "\"hda_disk_image_md5sum\"", ")", "==", "\"8ebc5a6ec53a1c05b7aa101b5ceefe31\"", ":", "node", "[", "\"console\"", "]", "=", "None", "node", "[", "\"console_type\"", "]", "=", "None", "node", "[", "\"node_type\"", "]", "=", "\"nat\"", "del", "old_node", "[", "\"properties\"", "]", "node", "[", "\"properties\"", "]", "=", "{", "\"ports\"", ":", "[", "{", "\"interface\"", ":", "\"eth1\"", ",", "\"name\"", ":", "\"nat0\"", ",", "\"port_number\"", ":", "0", ",", "\"type\"", ":", "\"ethernet\"", "}", "]", "}", "if", "node", "[", "\"symbol\"", "]", "is", "None", ":", "node", "[", "\"symbol\"", "]", "=", "\":/symbols/cloud.svg\"", "return", "node", "node", "[", "\"node_type\"", "]", "=", "\"qemu\"", "if", "node", "[", "\"symbol\"", "]", "is", "None", ":", "node", "[", "\"symbol\"", "]", "=", "\":/symbols/qemu_guest.svg\"", "return", "node" ]
Convert qemu node from 1.X to 2.0
[ "Convert", "qemu", "node", "from", "1", ".", "X", "to", "2", ".", "0" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/topology.py#L668-L696
226,748
GNS3/gns3-server
gns3server/controller/project.py
open_required
def open_required(func): """ Use this decorator to raise an error if the project is not opened """ def wrapper(self, *args, **kwargs): if self._status == "closed": raise aiohttp.web.HTTPForbidden(text="The project is not opened") return func(self, *args, **kwargs) return wrapper
python
def open_required(func): """ Use this decorator to raise an error if the project is not opened """ def wrapper(self, *args, **kwargs): if self._status == "closed": raise aiohttp.web.HTTPForbidden(text="The project is not opened") return func(self, *args, **kwargs) return wrapper
[ "def", "open_required", "(", "func", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_status", "==", "\"closed\"", ":", "raise", "aiohttp", ".", "web", ".", "HTTPForbidden", "(", "text", "=", "\"The project is not opened\"", ")", "return", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
Use this decorator to raise an error if the project is not opened
[ "Use", "this", "decorator", "to", "raise", "an", "error", "if", "the", "project", "is", "not", "opened" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L47-L56
226,749
GNS3/gns3-server
gns3server/controller/project.py
Project.captures_directory
def captures_directory(self): """ Location of the captures files """ path = os.path.join(self._path, "project-files", "captures") os.makedirs(path, exist_ok=True) return path
python
def captures_directory(self): """ Location of the captures files """ path = os.path.join(self._path, "project-files", "captures") os.makedirs(path, exist_ok=True) return path
[ "def", "captures_directory", "(", "self", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_path", ",", "\"project-files\"", ",", "\"captures\"", ")", "os", ".", "makedirs", "(", "path", ",", "exist_ok", "=", "True", ")", "return", "path" ]
Location of the captures files
[ "Location", "of", "the", "captures", "files" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L325-L331
226,750
GNS3/gns3-server
gns3server/controller/project.py
Project.remove_allocated_node_name
def remove_allocated_node_name(self, name): """ Removes an allocated node name :param name: allocated node name """ if name in self._allocated_node_names: self._allocated_node_names.remove(name)
python
def remove_allocated_node_name(self, name): """ Removes an allocated node name :param name: allocated node name """ if name in self._allocated_node_names: self._allocated_node_names.remove(name)
[ "def", "remove_allocated_node_name", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "_allocated_node_names", ":", "self", ".", "_allocated_node_names", ".", "remove", "(", "name", ")" ]
Removes an allocated node name :param name: allocated node name
[ "Removes", "an", "allocated", "node", "name" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L349-L357
226,751
GNS3/gns3-server
gns3server/controller/project.py
Project.update_allocated_node_name
def update_allocated_node_name(self, base_name): """ Updates a node name or generate a new if no node name is available. :param base_name: new node base name """ if base_name is None: return None base_name = re.sub(r"[ ]", "", base_name) if base_name in self._allocated_node_names: base_name = re.sub(r"[0-9]+$", "{0}", base_name) if '{0}' in base_name or '{id}' in base_name: # base name is a template, replace {0} or {id} by an unique identifier for number in range(1, 1000000): try: name = base_name.format(number, id=number, name="Node") except KeyError as e: raise aiohttp.web.HTTPConflict(text="{" + e.args[0] + "} is not a valid replacement string in the node name") except (ValueError, IndexError) as e: raise aiohttp.web.HTTPConflict(text="{} is not a valid replacement string in the node name".format(base_name)) if name not in self._allocated_node_names: self._allocated_node_names.add(name) return name else: if base_name not in self._allocated_node_names: self._allocated_node_names.add(base_name) return base_name # base name is not unique, let's find a unique name by appending a number for number in range(1, 1000000): name = base_name + str(number) if name not in self._allocated_node_names: self._allocated_node_names.add(name) return name raise aiohttp.web.HTTPConflict(text="A node name could not be allocated (node limit reached?)")
python
def update_allocated_node_name(self, base_name): """ Updates a node name or generate a new if no node name is available. :param base_name: new node base name """ if base_name is None: return None base_name = re.sub(r"[ ]", "", base_name) if base_name in self._allocated_node_names: base_name = re.sub(r"[0-9]+$", "{0}", base_name) if '{0}' in base_name or '{id}' in base_name: # base name is a template, replace {0} or {id} by an unique identifier for number in range(1, 1000000): try: name = base_name.format(number, id=number, name="Node") except KeyError as e: raise aiohttp.web.HTTPConflict(text="{" + e.args[0] + "} is not a valid replacement string in the node name") except (ValueError, IndexError) as e: raise aiohttp.web.HTTPConflict(text="{} is not a valid replacement string in the node name".format(base_name)) if name not in self._allocated_node_names: self._allocated_node_names.add(name) return name else: if base_name not in self._allocated_node_names: self._allocated_node_names.add(base_name) return base_name # base name is not unique, let's find a unique name by appending a number for number in range(1, 1000000): name = base_name + str(number) if name not in self._allocated_node_names: self._allocated_node_names.add(name) return name raise aiohttp.web.HTTPConflict(text="A node name could not be allocated (node limit reached?)")
[ "def", "update_allocated_node_name", "(", "self", ",", "base_name", ")", ":", "if", "base_name", "is", "None", ":", "return", "None", "base_name", "=", "re", ".", "sub", "(", "r\"[ ]\"", ",", "\"\"", ",", "base_name", ")", "if", "base_name", "in", "self", ".", "_allocated_node_names", ":", "base_name", "=", "re", ".", "sub", "(", "r\"[0-9]+$\"", ",", "\"{0}\"", ",", "base_name", ")", "if", "'{0}'", "in", "base_name", "or", "'{id}'", "in", "base_name", ":", "# base name is a template, replace {0} or {id} by an unique identifier", "for", "number", "in", "range", "(", "1", ",", "1000000", ")", ":", "try", ":", "name", "=", "base_name", ".", "format", "(", "number", ",", "id", "=", "number", ",", "name", "=", "\"Node\"", ")", "except", "KeyError", "as", "e", ":", "raise", "aiohttp", ".", "web", ".", "HTTPConflict", "(", "text", "=", "\"{\"", "+", "e", ".", "args", "[", "0", "]", "+", "\"} is not a valid replacement string in the node name\"", ")", "except", "(", "ValueError", ",", "IndexError", ")", "as", "e", ":", "raise", "aiohttp", ".", "web", ".", "HTTPConflict", "(", "text", "=", "\"{} is not a valid replacement string in the node name\"", ".", "format", "(", "base_name", ")", ")", "if", "name", "not", "in", "self", ".", "_allocated_node_names", ":", "self", ".", "_allocated_node_names", ".", "add", "(", "name", ")", "return", "name", "else", ":", "if", "base_name", "not", "in", "self", ".", "_allocated_node_names", ":", "self", ".", "_allocated_node_names", ".", "add", "(", "base_name", ")", "return", "base_name", "# base name is not unique, let's find a unique name by appending a number", "for", "number", "in", "range", "(", "1", ",", "1000000", ")", ":", "name", "=", "base_name", "+", "str", "(", "number", ")", "if", "name", "not", "in", "self", ".", "_allocated_node_names", ":", "self", ".", "_allocated_node_names", ".", "add", "(", "name", ")", "return", "name", "raise", "aiohttp", ".", "web", ".", "HTTPConflict", "(", "text", "=", "\"A node name could not be allocated (node limit reached?)\"", ")" ]
Updates a node name or generate a new if no node name is available. :param base_name: new node base name
[ "Updates", "a", "node", "name", "or", "generate", "a", "new", "if", "no", "node", "name", "is", "available", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L359-L395
226,752
GNS3/gns3-server
gns3server/controller/project.py
Project.add_node_from_appliance
def add_node_from_appliance(self, appliance_id, x=0, y=0, compute_id=None): """ Create a node from an appliance """ try: template = self.controller.appliances[appliance_id].data except KeyError: msg = "Appliance {} doesn't exist".format(appliance_id) log.error(msg) raise aiohttp.web.HTTPNotFound(text=msg) template["x"] = x template["y"] = y node_type = template.pop("node_type") compute = self.controller.get_compute(template.pop("server", compute_id)) name = template.pop("name") default_name_format = template.pop("default_name_format", "{name}-{0}") name = default_name_format.replace("{name}", name) node_id = str(uuid.uuid4()) node = yield from self.add_node(compute, name, node_id, node_type=node_type, **template) return node
python
def add_node_from_appliance(self, appliance_id, x=0, y=0, compute_id=None): """ Create a node from an appliance """ try: template = self.controller.appliances[appliance_id].data except KeyError: msg = "Appliance {} doesn't exist".format(appliance_id) log.error(msg) raise aiohttp.web.HTTPNotFound(text=msg) template["x"] = x template["y"] = y node_type = template.pop("node_type") compute = self.controller.get_compute(template.pop("server", compute_id)) name = template.pop("name") default_name_format = template.pop("default_name_format", "{name}-{0}") name = default_name_format.replace("{name}", name) node_id = str(uuid.uuid4()) node = yield from self.add_node(compute, name, node_id, node_type=node_type, **template) return node
[ "def", "add_node_from_appliance", "(", "self", ",", "appliance_id", ",", "x", "=", "0", ",", "y", "=", "0", ",", "compute_id", "=", "None", ")", ":", "try", ":", "template", "=", "self", ".", "controller", ".", "appliances", "[", "appliance_id", "]", ".", "data", "except", "KeyError", ":", "msg", "=", "\"Appliance {} doesn't exist\"", ".", "format", "(", "appliance_id", ")", "log", ".", "error", "(", "msg", ")", "raise", "aiohttp", ".", "web", ".", "HTTPNotFound", "(", "text", "=", "msg", ")", "template", "[", "\"x\"", "]", "=", "x", "template", "[", "\"y\"", "]", "=", "y", "node_type", "=", "template", ".", "pop", "(", "\"node_type\"", ")", "compute", "=", "self", ".", "controller", ".", "get_compute", "(", "template", ".", "pop", "(", "\"server\"", ",", "compute_id", ")", ")", "name", "=", "template", ".", "pop", "(", "\"name\"", ")", "default_name_format", "=", "template", ".", "pop", "(", "\"default_name_format\"", ",", "\"{name}-{0}\"", ")", "name", "=", "default_name_format", ".", "replace", "(", "\"{name}\"", ",", "name", ")", "node_id", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "node", "=", "yield", "from", "self", ".", "add_node", "(", "compute", ",", "name", ",", "node_id", ",", "node_type", "=", "node_type", ",", "*", "*", "template", ")", "return", "node" ]
Create a node from an appliance
[ "Create", "a", "node", "from", "an", "appliance" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L406-L425
226,753
GNS3/gns3-server
gns3server/controller/project.py
Project.add_node
def add_node(self, compute, name, node_id, dump=True, node_type=None, **kwargs): """ Create a node or return an existing node :param dump: Dump topology to disk :param kwargs: See the documentation of node """ if node_id in self._nodes: return self._nodes[node_id] node = Node(self, compute, name, node_id=node_id, node_type=node_type, **kwargs) if compute not in self._project_created_on_compute: # For a local server we send the project path if compute.id == "local": yield from compute.post("/projects", data={ "name": self._name, "project_id": self._id, "path": self._path }) else: yield from compute.post("/projects", data={ "name": self._name, "project_id": self._id, }) self._project_created_on_compute.add(compute) yield from node.create() self._nodes[node.id] = node self.controller.notification.emit("node.created", node.__json__()) if dump: self.dump() return node
python
def add_node(self, compute, name, node_id, dump=True, node_type=None, **kwargs): """ Create a node or return an existing node :param dump: Dump topology to disk :param kwargs: See the documentation of node """ if node_id in self._nodes: return self._nodes[node_id] node = Node(self, compute, name, node_id=node_id, node_type=node_type, **kwargs) if compute not in self._project_created_on_compute: # For a local server we send the project path if compute.id == "local": yield from compute.post("/projects", data={ "name": self._name, "project_id": self._id, "path": self._path }) else: yield from compute.post("/projects", data={ "name": self._name, "project_id": self._id, }) self._project_created_on_compute.add(compute) yield from node.create() self._nodes[node.id] = node self.controller.notification.emit("node.created", node.__json__()) if dump: self.dump() return node
[ "def", "add_node", "(", "self", ",", "compute", ",", "name", ",", "node_id", ",", "dump", "=", "True", ",", "node_type", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "node_id", "in", "self", ".", "_nodes", ":", "return", "self", ".", "_nodes", "[", "node_id", "]", "node", "=", "Node", "(", "self", ",", "compute", ",", "name", ",", "node_id", "=", "node_id", ",", "node_type", "=", "node_type", ",", "*", "*", "kwargs", ")", "if", "compute", "not", "in", "self", ".", "_project_created_on_compute", ":", "# For a local server we send the project path", "if", "compute", ".", "id", "==", "\"local\"", ":", "yield", "from", "compute", ".", "post", "(", "\"/projects\"", ",", "data", "=", "{", "\"name\"", ":", "self", ".", "_name", ",", "\"project_id\"", ":", "self", ".", "_id", ",", "\"path\"", ":", "self", ".", "_path", "}", ")", "else", ":", "yield", "from", "compute", ".", "post", "(", "\"/projects\"", ",", "data", "=", "{", "\"name\"", ":", "self", ".", "_name", ",", "\"project_id\"", ":", "self", ".", "_id", ",", "}", ")", "self", ".", "_project_created_on_compute", ".", "add", "(", "compute", ")", "yield", "from", "node", ".", "create", "(", ")", "self", ".", "_nodes", "[", "node", ".", "id", "]", "=", "node", "self", ".", "controller", ".", "notification", ".", "emit", "(", "\"node.created\"", ",", "node", ".", "__json__", "(", ")", ")", "if", "dump", ":", "self", ".", "dump", "(", ")", "return", "node" ]
Create a node or return an existing node :param dump: Dump topology to disk :param kwargs: See the documentation of node
[ "Create", "a", "node", "or", "return", "an", "existing", "node" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L429-L461
226,754
GNS3/gns3-server
gns3server/controller/project.py
Project.__delete_node_links
def __delete_node_links(self, node): """ Delete all link connected to this node. The operation use a lock to avoid cleaning links from multiple nodes at the same time. """ for link in list(self._links.values()): if node in link.nodes: yield from self.delete_link(link.id, force_delete=True)
python
def __delete_node_links(self, node): """ Delete all link connected to this node. The operation use a lock to avoid cleaning links from multiple nodes at the same time. """ for link in list(self._links.values()): if node in link.nodes: yield from self.delete_link(link.id, force_delete=True)
[ "def", "__delete_node_links", "(", "self", ",", "node", ")", ":", "for", "link", "in", "list", "(", "self", ".", "_links", ".", "values", "(", ")", ")", ":", "if", "node", "in", "link", ".", "nodes", ":", "yield", "from", "self", ".", "delete_link", "(", "link", ".", "id", ",", "force_delete", "=", "True", ")" ]
Delete all link connected to this node. The operation use a lock to avoid cleaning links from multiple nodes at the same time.
[ "Delete", "all", "link", "connected", "to", "this", "node", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L464-L473
226,755
GNS3/gns3-server
gns3server/controller/project.py
Project.get_node
def get_node(self, node_id): """ Return the node or raise a 404 if the node is unknown """ try: return self._nodes[node_id] except KeyError: raise aiohttp.web.HTTPNotFound(text="Node ID {} doesn't exist".format(node_id))
python
def get_node(self, node_id): """ Return the node or raise a 404 if the node is unknown """ try: return self._nodes[node_id] except KeyError: raise aiohttp.web.HTTPNotFound(text="Node ID {} doesn't exist".format(node_id))
[ "def", "get_node", "(", "self", ",", "node_id", ")", ":", "try", ":", "return", "self", ".", "_nodes", "[", "node_id", "]", "except", "KeyError", ":", "raise", "aiohttp", ".", "web", ".", "HTTPNotFound", "(", "text", "=", "\"Node ID {} doesn't exist\"", ".", "format", "(", "node_id", ")", ")" ]
Return the node or raise a 404 if the node is unknown
[ "Return", "the", "node", "or", "raise", "a", "404", "if", "the", "node", "is", "unknown" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L487-L494
226,756
GNS3/gns3-server
gns3server/controller/project.py
Project.add_drawing
def add_drawing(self, drawing_id=None, dump=True, **kwargs): """ Create an drawing or return an existing drawing :param dump: Dump the topology to disk :param kwargs: See the documentation of drawing """ if drawing_id not in self._drawings: drawing = Drawing(self, drawing_id=drawing_id, **kwargs) self._drawings[drawing.id] = drawing self.controller.notification.emit("drawing.created", drawing.__json__()) if dump: self.dump() return drawing return self._drawings[drawing_id]
python
def add_drawing(self, drawing_id=None, dump=True, **kwargs): """ Create an drawing or return an existing drawing :param dump: Dump the topology to disk :param kwargs: See the documentation of drawing """ if drawing_id not in self._drawings: drawing = Drawing(self, drawing_id=drawing_id, **kwargs) self._drawings[drawing.id] = drawing self.controller.notification.emit("drawing.created", drawing.__json__()) if dump: self.dump() return drawing return self._drawings[drawing_id]
[ "def", "add_drawing", "(", "self", ",", "drawing_id", "=", "None", ",", "dump", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "drawing_id", "not", "in", "self", ".", "_drawings", ":", "drawing", "=", "Drawing", "(", "self", ",", "drawing_id", "=", "drawing_id", ",", "*", "*", "kwargs", ")", "self", ".", "_drawings", "[", "drawing", ".", "id", "]", "=", "drawing", "self", ".", "controller", ".", "notification", ".", "emit", "(", "\"drawing.created\"", ",", "drawing", ".", "__json__", "(", ")", ")", "if", "dump", ":", "self", ".", "dump", "(", ")", "return", "drawing", "return", "self", ".", "_drawings", "[", "drawing_id", "]" ]
Create an drawing or return an existing drawing :param dump: Dump the topology to disk :param kwargs: See the documentation of drawing
[ "Create", "an", "drawing", "or", "return", "an", "existing", "drawing" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L512-L526
226,757
GNS3/gns3-server
gns3server/controller/project.py
Project.get_drawing
def get_drawing(self, drawing_id): """ Return the Drawing or raise a 404 if the drawing is unknown """ try: return self._drawings[drawing_id] except KeyError: raise aiohttp.web.HTTPNotFound(text="Drawing ID {} doesn't exist".format(drawing_id))
python
def get_drawing(self, drawing_id): """ Return the Drawing or raise a 404 if the drawing is unknown """ try: return self._drawings[drawing_id] except KeyError: raise aiohttp.web.HTTPNotFound(text="Drawing ID {} doesn't exist".format(drawing_id))
[ "def", "get_drawing", "(", "self", ",", "drawing_id", ")", ":", "try", ":", "return", "self", ".", "_drawings", "[", "drawing_id", "]", "except", "KeyError", ":", "raise", "aiohttp", ".", "web", ".", "HTTPNotFound", "(", "text", "=", "\"Drawing ID {} doesn't exist\"", ".", "format", "(", "drawing_id", ")", ")" ]
Return the Drawing or raise a 404 if the drawing is unknown
[ "Return", "the", "Drawing", "or", "raise", "a", "404", "if", "the", "drawing", "is", "unknown" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L529-L536
226,758
GNS3/gns3-server
gns3server/controller/project.py
Project.add_link
def add_link(self, link_id=None, dump=True): """ Create a link. By default the link is empty :param dump: Dump topology to disk """ if link_id and link_id in self._links: return self._links[link_id] link = UDPLink(self, link_id=link_id) self._links[link.id] = link if dump: self.dump() return link
python
def add_link(self, link_id=None, dump=True): """ Create a link. By default the link is empty :param dump: Dump topology to disk """ if link_id and link_id in self._links: return self._links[link_id] link = UDPLink(self, link_id=link_id) self._links[link.id] = link if dump: self.dump() return link
[ "def", "add_link", "(", "self", ",", "link_id", "=", "None", ",", "dump", "=", "True", ")", ":", "if", "link_id", "and", "link_id", "in", "self", ".", "_links", ":", "return", "self", ".", "_links", "[", "link_id", "]", "link", "=", "UDPLink", "(", "self", ",", "link_id", "=", "link_id", ")", "self", ".", "_links", "[", "link", ".", "id", "]", "=", "link", "if", "dump", ":", "self", ".", "dump", "(", ")", "return", "link" ]
Create a link. By default the link is empty :param dump: Dump topology to disk
[ "Create", "a", "link", ".", "By", "default", "the", "link", "is", "empty" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L548-L560
226,759
GNS3/gns3-server
gns3server/controller/project.py
Project.get_link
def get_link(self, link_id): """ Return the Link or raise a 404 if the link is unknown """ try: return self._links[link_id] except KeyError: raise aiohttp.web.HTTPNotFound(text="Link ID {} doesn't exist".format(link_id))
python
def get_link(self, link_id): """ Return the Link or raise a 404 if the link is unknown """ try: return self._links[link_id] except KeyError: raise aiohttp.web.HTTPNotFound(text="Link ID {} doesn't exist".format(link_id))
[ "def", "get_link", "(", "self", ",", "link_id", ")", ":", "try", ":", "return", "self", ".", "_links", "[", "link_id", "]", "except", "KeyError", ":", "raise", "aiohttp", ".", "web", ".", "HTTPNotFound", "(", "text", "=", "\"Link ID {} doesn't exist\"", ".", "format", "(", "link_id", ")", ")" ]
Return the Link or raise a 404 if the link is unknown
[ "Return", "the", "Link", "or", "raise", "a", "404", "if", "the", "link", "is", "unknown" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L576-L583
226,760
GNS3/gns3-server
gns3server/controller/project.py
Project.get_snapshot
def get_snapshot(self, snapshot_id): """ Return the snapshot or raise a 404 if the snapshot is unknown """ try: return self._snapshots[snapshot_id] except KeyError: raise aiohttp.web.HTTPNotFound(text="Snapshot ID {} doesn't exist".format(snapshot_id))
python
def get_snapshot(self, snapshot_id): """ Return the snapshot or raise a 404 if the snapshot is unknown """ try: return self._snapshots[snapshot_id] except KeyError: raise aiohttp.web.HTTPNotFound(text="Snapshot ID {} doesn't exist".format(snapshot_id))
[ "def", "get_snapshot", "(", "self", ",", "snapshot_id", ")", ":", "try", ":", "return", "self", ".", "_snapshots", "[", "snapshot_id", "]", "except", "KeyError", ":", "raise", "aiohttp", ".", "web", ".", "HTTPNotFound", "(", "text", "=", "\"Snapshot ID {} doesn't exist\"", ".", "format", "(", "snapshot_id", ")", ")" ]
Return the snapshot or raise a 404 if the snapshot is unknown
[ "Return", "the", "snapshot", "or", "raise", "a", "404", "if", "the", "snapshot", "is", "unknown" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L600-L607
226,761
GNS3/gns3-server
gns3server/controller/project.py
Project.snapshot
def snapshot(self, name): """ Snapshot the project :param name: Name of the snapshot """ if name in [snap.name for snap in self.snapshots.values()]: raise aiohttp.web_exceptions.HTTPConflict(text="The snapshot {} already exist".format(name)) snapshot = Snapshot(self, name=name) try: if os.path.exists(snapshot.path): raise aiohttp.web_exceptions.HTTPConflict(text="The snapshot {} already exist".format(name)) os.makedirs(os.path.join(self.path, "snapshots"), exist_ok=True) with tempfile.TemporaryDirectory() as tmpdir: zipstream = yield from export_project(self, tmpdir, keep_compute_id=True, allow_all_nodes=True) try: with open(snapshot.path, "wb") as f: for data in zipstream: f.write(data) except OSError as e: raise aiohttp.web.HTTPConflict(text="Could not write snapshot file '{}': {}".format(snapshot.path, e)) except OSError as e: raise aiohttp.web.HTTPInternalServerError(text="Could not create project directory: {}".format(e)) self._snapshots[snapshot.id] = snapshot return snapshot
python
def snapshot(self, name): """ Snapshot the project :param name: Name of the snapshot """ if name in [snap.name for snap in self.snapshots.values()]: raise aiohttp.web_exceptions.HTTPConflict(text="The snapshot {} already exist".format(name)) snapshot = Snapshot(self, name=name) try: if os.path.exists(snapshot.path): raise aiohttp.web_exceptions.HTTPConflict(text="The snapshot {} already exist".format(name)) os.makedirs(os.path.join(self.path, "snapshots"), exist_ok=True) with tempfile.TemporaryDirectory() as tmpdir: zipstream = yield from export_project(self, tmpdir, keep_compute_id=True, allow_all_nodes=True) try: with open(snapshot.path, "wb") as f: for data in zipstream: f.write(data) except OSError as e: raise aiohttp.web.HTTPConflict(text="Could not write snapshot file '{}': {}".format(snapshot.path, e)) except OSError as e: raise aiohttp.web.HTTPInternalServerError(text="Could not create project directory: {}".format(e)) self._snapshots[snapshot.id] = snapshot return snapshot
[ "def", "snapshot", "(", "self", ",", "name", ")", ":", "if", "name", "in", "[", "snap", ".", "name", "for", "snap", "in", "self", ".", "snapshots", ".", "values", "(", ")", "]", ":", "raise", "aiohttp", ".", "web_exceptions", ".", "HTTPConflict", "(", "text", "=", "\"The snapshot {} already exist\"", ".", "format", "(", "name", ")", ")", "snapshot", "=", "Snapshot", "(", "self", ",", "name", "=", "name", ")", "try", ":", "if", "os", ".", "path", ".", "exists", "(", "snapshot", ".", "path", ")", ":", "raise", "aiohttp", ".", "web_exceptions", ".", "HTTPConflict", "(", "text", "=", "\"The snapshot {} already exist\"", ".", "format", "(", "name", ")", ")", "os", ".", "makedirs", "(", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "\"snapshots\"", ")", ",", "exist_ok", "=", "True", ")", "with", "tempfile", ".", "TemporaryDirectory", "(", ")", "as", "tmpdir", ":", "zipstream", "=", "yield", "from", "export_project", "(", "self", ",", "tmpdir", ",", "keep_compute_id", "=", "True", ",", "allow_all_nodes", "=", "True", ")", "try", ":", "with", "open", "(", "snapshot", ".", "path", ",", "\"wb\"", ")", "as", "f", ":", "for", "data", "in", "zipstream", ":", "f", ".", "write", "(", "data", ")", "except", "OSError", "as", "e", ":", "raise", "aiohttp", ".", "web", ".", "HTTPConflict", "(", "text", "=", "\"Could not write snapshot file '{}': {}\"", ".", "format", "(", "snapshot", ".", "path", ",", "e", ")", ")", "except", "OSError", "as", "e", ":", "raise", "aiohttp", ".", "web", ".", "HTTPInternalServerError", "(", "text", "=", "\"Could not create project directory: {}\"", ".", "format", "(", "e", ")", ")", "self", ".", "_snapshots", "[", "snapshot", ".", "id", "]", "=", "snapshot", "return", "snapshot" ]
Snapshot the project :param name: Name of the snapshot
[ "Snapshot", "the", "project" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L611-L640
226,762
GNS3/gns3-server
gns3server/controller/project.py
Project._cleanPictures
def _cleanPictures(self): """ Delete unused images """ # Project have been deleted if not os.path.exists(self.path): return try: pictures = set(os.listdir(self.pictures_directory)) for drawing in self._drawings.values(): try: pictures.remove(drawing.ressource_filename) except KeyError: pass for pict in pictures: os.remove(os.path.join(self.pictures_directory, pict)) except OSError as e: log.warning(str(e))
python
def _cleanPictures(self): """ Delete unused images """ # Project have been deleted if not os.path.exists(self.path): return try: pictures = set(os.listdir(self.pictures_directory)) for drawing in self._drawings.values(): try: pictures.remove(drawing.ressource_filename) except KeyError: pass for pict in pictures: os.remove(os.path.join(self.pictures_directory, pict)) except OSError as e: log.warning(str(e))
[ "def", "_cleanPictures", "(", "self", ")", ":", "# Project have been deleted", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "path", ")", ":", "return", "try", ":", "pictures", "=", "set", "(", "os", ".", "listdir", "(", "self", ".", "pictures_directory", ")", ")", "for", "drawing", "in", "self", ".", "_drawings", ".", "values", "(", ")", ":", "try", ":", "pictures", ".", "remove", "(", "drawing", ".", "ressource_filename", ")", "except", "KeyError", ":", "pass", "for", "pict", "in", "pictures", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "self", ".", "pictures_directory", ",", "pict", ")", ")", "except", "OSError", "as", "e", ":", "log", ".", "warning", "(", "str", "(", "e", ")", ")" ]
Delete unused images
[ "Delete", "unused", "images" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L663-L682
226,763
GNS3/gns3-server
gns3server/controller/project.py
Project.delete_on_computes
def delete_on_computes(self): """ Delete the project on computes but not on controller """ for compute in list(self._project_created_on_compute): if compute.id != "local": yield from compute.delete("/projects/{}".format(self._id)) self._project_created_on_compute.remove(compute)
python
def delete_on_computes(self): """ Delete the project on computes but not on controller """ for compute in list(self._project_created_on_compute): if compute.id != "local": yield from compute.delete("/projects/{}".format(self._id)) self._project_created_on_compute.remove(compute)
[ "def", "delete_on_computes", "(", "self", ")", ":", "for", "compute", "in", "list", "(", "self", ".", "_project_created_on_compute", ")", ":", "if", "compute", ".", "id", "!=", "\"local\"", ":", "yield", "from", "compute", ".", "delete", "(", "\"/projects/{}\"", ".", "format", "(", "self", ".", "_id", ")", ")", "self", ".", "_project_created_on_compute", ".", "remove", "(", "compute", ")" ]
Delete the project on computes but not on controller
[ "Delete", "the", "project", "on", "computes", "but", "not", "on", "controller" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L701-L708
226,764
GNS3/gns3-server
gns3server/controller/project.py
Project.duplicate
def duplicate(self, name=None, location=None): """ Duplicate a project It's the save as feature of the 1.X. It's implemented on top of the export / import features. It will generate a gns3p and reimport it. It's a little slower but we have only one implementation to maintain. :param name: Name of the new project. A new one will be generated in case of conflicts :param location: Parent directory of the new project """ # If the project was not open we open it temporary previous_status = self._status if self._status == "closed": yield from self.open() self.dump() try: with tempfile.TemporaryDirectory() as tmpdir: zipstream = yield from export_project(self, tmpdir, keep_compute_id=True, allow_all_nodes=True) with open(os.path.join(tmpdir, "project.gns3p"), "wb") as f: for data in zipstream: f.write(data) with open(os.path.join(tmpdir, "project.gns3p"), "rb") as f: project = yield from import_project(self._controller, str(uuid.uuid4()), f, location=location, name=name, keep_compute_id=True) except (OSError, UnicodeEncodeError) as e: raise aiohttp.web.HTTPConflict(text="Can not duplicate project: {}".format(str(e))) if previous_status == "closed": yield from self.close() return project
python
def duplicate(self, name=None, location=None): """ Duplicate a project It's the save as feature of the 1.X. It's implemented on top of the export / import features. It will generate a gns3p and reimport it. It's a little slower but we have only one implementation to maintain. :param name: Name of the new project. A new one will be generated in case of conflicts :param location: Parent directory of the new project """ # If the project was not open we open it temporary previous_status = self._status if self._status == "closed": yield from self.open() self.dump() try: with tempfile.TemporaryDirectory() as tmpdir: zipstream = yield from export_project(self, tmpdir, keep_compute_id=True, allow_all_nodes=True) with open(os.path.join(tmpdir, "project.gns3p"), "wb") as f: for data in zipstream: f.write(data) with open(os.path.join(tmpdir, "project.gns3p"), "rb") as f: project = yield from import_project(self._controller, str(uuid.uuid4()), f, location=location, name=name, keep_compute_id=True) except (OSError, UnicodeEncodeError) as e: raise aiohttp.web.HTTPConflict(text="Can not duplicate project: {}".format(str(e))) if previous_status == "closed": yield from self.close() return project
[ "def", "duplicate", "(", "self", ",", "name", "=", "None", ",", "location", "=", "None", ")", ":", "# If the project was not open we open it temporary", "previous_status", "=", "self", ".", "_status", "if", "self", ".", "_status", "==", "\"closed\"", ":", "yield", "from", "self", ".", "open", "(", ")", "self", ".", "dump", "(", ")", "try", ":", "with", "tempfile", ".", "TemporaryDirectory", "(", ")", "as", "tmpdir", ":", "zipstream", "=", "yield", "from", "export_project", "(", "self", ",", "tmpdir", ",", "keep_compute_id", "=", "True", ",", "allow_all_nodes", "=", "True", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "\"project.gns3p\"", ")", ",", "\"wb\"", ")", "as", "f", ":", "for", "data", "in", "zipstream", ":", "f", ".", "write", "(", "data", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "\"project.gns3p\"", ")", ",", "\"rb\"", ")", "as", "f", ":", "project", "=", "yield", "from", "import_project", "(", "self", ".", "_controller", ",", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ",", "f", ",", "location", "=", "location", ",", "name", "=", "name", ",", "keep_compute_id", "=", "True", ")", "except", "(", "OSError", ",", "UnicodeEncodeError", ")", "as", "e", ":", "raise", "aiohttp", ".", "web", ".", "HTTPConflict", "(", "text", "=", "\"Can not duplicate project: {}\"", ".", "format", "(", "str", "(", "e", ")", ")", ")", "if", "previous_status", "==", "\"closed\"", ":", "yield", "from", "self", ".", "close", "(", ")", "return", "project" ]
Duplicate a project It's the save as feature of the 1.X. It's implemented on top of the export / import features. It will generate a gns3p and reimport it. It's a little slower but we have only one implementation to maintain. :param name: Name of the new project. A new one will be generated in case of conflicts :param location: Parent directory of the new project
[ "Duplicate", "a", "project" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L844-L875
226,765
GNS3/gns3-server
gns3server/controller/project.py
Project.is_running
def is_running(self): """ If a node is started or paused return True """ for node in self._nodes.values(): # Some node type are always running we ignore them if node.status != "stopped" and not node.is_always_running(): return True return False
python
def is_running(self): """ If a node is started or paused return True """ for node in self._nodes.values(): # Some node type are always running we ignore them if node.status != "stopped" and not node.is_always_running(): return True return False
[ "def", "is_running", "(", "self", ")", ":", "for", "node", "in", "self", ".", "_nodes", ".", "values", "(", ")", ":", "# Some node type are always running we ignore them", "if", "node", ".", "status", "!=", "\"stopped\"", "and", "not", "node", ".", "is_always_running", "(", ")", ":", "return", "True", "return", "False" ]
If a node is started or paused return True
[ "If", "a", "node", "is", "started", "or", "paused", "return", "True" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L877-L885
226,766
GNS3/gns3-server
gns3server/controller/project.py
Project.dump
def dump(self): """ Dump topology to disk """ try: topo = project_to_topology(self) path = self._topology_file() log.debug("Write %s", path) with open(path + ".tmp", "w+", encoding="utf-8") as f: json.dump(topo, f, indent=4, sort_keys=True) shutil.move(path + ".tmp", path) except OSError as e: raise aiohttp.web.HTTPInternalServerError(text="Could not write topology: {}".format(e))
python
def dump(self): """ Dump topology to disk """ try: topo = project_to_topology(self) path = self._topology_file() log.debug("Write %s", path) with open(path + ".tmp", "w+", encoding="utf-8") as f: json.dump(topo, f, indent=4, sort_keys=True) shutil.move(path + ".tmp", path) except OSError as e: raise aiohttp.web.HTTPInternalServerError(text="Could not write topology: {}".format(e))
[ "def", "dump", "(", "self", ")", ":", "try", ":", "topo", "=", "project_to_topology", "(", "self", ")", "path", "=", "self", ".", "_topology_file", "(", ")", "log", ".", "debug", "(", "\"Write %s\"", ",", "path", ")", "with", "open", "(", "path", "+", "\".tmp\"", ",", "\"w+\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "json", ".", "dump", "(", "topo", ",", "f", ",", "indent", "=", "4", ",", "sort_keys", "=", "True", ")", "shutil", ".", "move", "(", "path", "+", "\".tmp\"", ",", "path", ")", "except", "OSError", "as", "e", ":", "raise", "aiohttp", ".", "web", ".", "HTTPInternalServerError", "(", "text", "=", "\"Could not write topology: {}\"", ".", "format", "(", "e", ")", ")" ]
Dump topology to disk
[ "Dump", "topology", "to", "disk" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L887-L899
226,767
GNS3/gns3-server
gns3server/controller/project.py
Project.start_all
def start_all(self): """ Start all nodes """ pool = Pool(concurrency=3) for node in self.nodes.values(): pool.append(node.start) yield from pool.join()
python
def start_all(self): """ Start all nodes """ pool = Pool(concurrency=3) for node in self.nodes.values(): pool.append(node.start) yield from pool.join()
[ "def", "start_all", "(", "self", ")", ":", "pool", "=", "Pool", "(", "concurrency", "=", "3", ")", "for", "node", "in", "self", ".", "nodes", ".", "values", "(", ")", ":", "pool", ".", "append", "(", "node", ".", "start", ")", "yield", "from", "pool", ".", "join", "(", ")" ]
Start all nodes
[ "Start", "all", "nodes" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L902-L909
226,768
GNS3/gns3-server
gns3server/controller/project.py
Project.stop_all
def stop_all(self): """ Stop all nodes """ pool = Pool(concurrency=3) for node in self.nodes.values(): pool.append(node.stop) yield from pool.join()
python
def stop_all(self): """ Stop all nodes """ pool = Pool(concurrency=3) for node in self.nodes.values(): pool.append(node.stop) yield from pool.join()
[ "def", "stop_all", "(", "self", ")", ":", "pool", "=", "Pool", "(", "concurrency", "=", "3", ")", "for", "node", "in", "self", ".", "nodes", ".", "values", "(", ")", ":", "pool", ".", "append", "(", "node", ".", "stop", ")", "yield", "from", "pool", ".", "join", "(", ")" ]
Stop all nodes
[ "Stop", "all", "nodes" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L912-L919
226,769
GNS3/gns3-server
gns3server/controller/project.py
Project.suspend_all
def suspend_all(self): """ Suspend all nodes """ pool = Pool(concurrency=3) for node in self.nodes.values(): pool.append(node.suspend) yield from pool.join()
python
def suspend_all(self): """ Suspend all nodes """ pool = Pool(concurrency=3) for node in self.nodes.values(): pool.append(node.suspend) yield from pool.join()
[ "def", "suspend_all", "(", "self", ")", ":", "pool", "=", "Pool", "(", "concurrency", "=", "3", ")", "for", "node", "in", "self", ".", "nodes", ".", "values", "(", ")", ":", "pool", ".", "append", "(", "node", ".", "suspend", ")", "yield", "from", "pool", ".", "join", "(", ")" ]
Suspend all nodes
[ "Suspend", "all", "nodes" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L922-L929
226,770
GNS3/gns3-server
gns3server/utils/asyncio/input_stream.py
InputStream._get_match
def _get_match(self, prefix): """ Return the key that maps to this prefix. """ # (hard coded) If we match a CPR response, return Keys.CPRResponse. # (This one doesn't fit in the ANSI_SEQUENCES, because it contains # integer variables.) if _cpr_response_re.match(prefix): return Keys.CPRResponse elif _mouse_event_re.match(prefix): return Keys.Vt100MouseEvent # Otherwise, use the mappings. try: return ANSI_SEQUENCES[prefix] except KeyError: return None
python
def _get_match(self, prefix): """ Return the key that maps to this prefix. """ # (hard coded) If we match a CPR response, return Keys.CPRResponse. # (This one doesn't fit in the ANSI_SEQUENCES, because it contains # integer variables.) if _cpr_response_re.match(prefix): return Keys.CPRResponse elif _mouse_event_re.match(prefix): return Keys.Vt100MouseEvent # Otherwise, use the mappings. try: return ANSI_SEQUENCES[prefix] except KeyError: return None
[ "def", "_get_match", "(", "self", ",", "prefix", ")", ":", "# (hard coded) If we match a CPR response, return Keys.CPRResponse.", "# (This one doesn't fit in the ANSI_SEQUENCES, because it contains", "# integer variables.)", "if", "_cpr_response_re", ".", "match", "(", "prefix", ")", ":", "return", "Keys", ".", "CPRResponse", "elif", "_mouse_event_re", ".", "match", "(", "prefix", ")", ":", "return", "Keys", ".", "Vt100MouseEvent", "# Otherwise, use the mappings.", "try", ":", "return", "ANSI_SEQUENCES", "[", "prefix", "]", "except", "KeyError", ":", "return", "None" ]
Return the key that maps to this prefix.
[ "Return", "the", "key", "that", "maps", "to", "this", "prefix", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/input_stream.py#L259-L276
226,771
GNS3/gns3-server
gns3server/utils/asyncio/input_stream.py
InputStream._call_handler
def _call_handler(self, key, insert_text): """ Callback to handler. """ if isinstance(key, tuple): for k in key: self._call_handler(k, insert_text) else: if key == Keys.BracketedPaste: self._in_bracketed_paste = True self._paste_buffer = '' else: self.feed_key_callback(KeyPress(key, insert_text))
python
def _call_handler(self, key, insert_text): """ Callback to handler. """ if isinstance(key, tuple): for k in key: self._call_handler(k, insert_text) else: if key == Keys.BracketedPaste: self._in_bracketed_paste = True self._paste_buffer = '' else: self.feed_key_callback(KeyPress(key, insert_text))
[ "def", "_call_handler", "(", "self", ",", "key", ",", "insert_text", ")", ":", "if", "isinstance", "(", "key", ",", "tuple", ")", ":", "for", "k", "in", "key", ":", "self", ".", "_call_handler", "(", "k", ",", "insert_text", ")", "else", ":", "if", "key", "==", "Keys", ".", "BracketedPaste", ":", "self", ".", "_in_bracketed_paste", "=", "True", "self", ".", "_paste_buffer", "=", "''", "else", ":", "self", ".", "feed_key_callback", "(", "KeyPress", "(", "key", ",", "insert_text", ")", ")" ]
Callback to handler.
[ "Callback", "to", "handler", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/input_stream.py#L328-L340
226,772
GNS3/gns3-server
gns3server/utils/asyncio/input_stream.py
InputStream.feed
def feed(self, data): """ Feed the input stream. :param data: Input string (unicode). """ assert isinstance(data, six.text_type) if _DEBUG_RENDERER_INPUT: self.LOG.write(repr(data).encode('utf-8') + b'\n') self.LOG.flush() # Handle bracketed paste. (We bypass the parser that matches all other # key presses and keep reading input until we see the end mark.) # This is much faster then parsing character by character. if self._in_bracketed_paste: self._paste_buffer += data end_mark = '\x1b[201~' if end_mark in self._paste_buffer: end_index = self._paste_buffer.index(end_mark) # Feed content to key bindings. paste_content = self._paste_buffer[:end_index] self.feed_key_callback(KeyPress(Keys.BracketedPaste, paste_content)) # Quit bracketed paste mode and handle remaining input. self._in_bracketed_paste = False remaining = self._paste_buffer[end_index + len(end_mark):] self._paste_buffer = '' self.feed(remaining) # Handle normal input character by character. else: for i, c in enumerate(data): if self._in_bracketed_paste: # Quit loop and process from this position when the parser # entered bracketed paste. self.feed(data[i:]) break else: # Replace \r by \n. (Some clients send \r instead of \n # when enter is pressed. E.g. telnet and some other # terminals.) # XXX: We should remove this in a future version. It *is* # now possible to recognise the difference. # (We remove ICRNL/INLCR/IGNCR below.) # However, this breaks IPython and maybe other applications, # because they bind ControlJ (\n) for handling the Enter key. # When this is removed, replace Enter=ControlJ by # Enter=ControlM in keys.py. if c == '\r': c = '\n' self._input_parser.send(c)
python
def feed(self, data): """ Feed the input stream. :param data: Input string (unicode). """ assert isinstance(data, six.text_type) if _DEBUG_RENDERER_INPUT: self.LOG.write(repr(data).encode('utf-8') + b'\n') self.LOG.flush() # Handle bracketed paste. (We bypass the parser that matches all other # key presses and keep reading input until we see the end mark.) # This is much faster then parsing character by character. if self._in_bracketed_paste: self._paste_buffer += data end_mark = '\x1b[201~' if end_mark in self._paste_buffer: end_index = self._paste_buffer.index(end_mark) # Feed content to key bindings. paste_content = self._paste_buffer[:end_index] self.feed_key_callback(KeyPress(Keys.BracketedPaste, paste_content)) # Quit bracketed paste mode and handle remaining input. self._in_bracketed_paste = False remaining = self._paste_buffer[end_index + len(end_mark):] self._paste_buffer = '' self.feed(remaining) # Handle normal input character by character. else: for i, c in enumerate(data): if self._in_bracketed_paste: # Quit loop and process from this position when the parser # entered bracketed paste. self.feed(data[i:]) break else: # Replace \r by \n. (Some clients send \r instead of \n # when enter is pressed. E.g. telnet and some other # terminals.) # XXX: We should remove this in a future version. It *is* # now possible to recognise the difference. # (We remove ICRNL/INLCR/IGNCR below.) # However, this breaks IPython and maybe other applications, # because they bind ControlJ (\n) for handling the Enter key. # When this is removed, replace Enter=ControlJ by # Enter=ControlM in keys.py. if c == '\r': c = '\n' self._input_parser.send(c)
[ "def", "feed", "(", "self", ",", "data", ")", ":", "assert", "isinstance", "(", "data", ",", "six", ".", "text_type", ")", "if", "_DEBUG_RENDERER_INPUT", ":", "self", ".", "LOG", ".", "write", "(", "repr", "(", "data", ")", ".", "encode", "(", "'utf-8'", ")", "+", "b'\\n'", ")", "self", ".", "LOG", ".", "flush", "(", ")", "# Handle bracketed paste. (We bypass the parser that matches all other", "# key presses and keep reading input until we see the end mark.)", "# This is much faster then parsing character by character.", "if", "self", ".", "_in_bracketed_paste", ":", "self", ".", "_paste_buffer", "+=", "data", "end_mark", "=", "'\\x1b[201~'", "if", "end_mark", "in", "self", ".", "_paste_buffer", ":", "end_index", "=", "self", ".", "_paste_buffer", ".", "index", "(", "end_mark", ")", "# Feed content to key bindings.", "paste_content", "=", "self", ".", "_paste_buffer", "[", ":", "end_index", "]", "self", ".", "feed_key_callback", "(", "KeyPress", "(", "Keys", ".", "BracketedPaste", ",", "paste_content", ")", ")", "# Quit bracketed paste mode and handle remaining input.", "self", ".", "_in_bracketed_paste", "=", "False", "remaining", "=", "self", ".", "_paste_buffer", "[", "end_index", "+", "len", "(", "end_mark", ")", ":", "]", "self", ".", "_paste_buffer", "=", "''", "self", ".", "feed", "(", "remaining", ")", "# Handle normal input character by character.", "else", ":", "for", "i", ",", "c", "in", "enumerate", "(", "data", ")", ":", "if", "self", ".", "_in_bracketed_paste", ":", "# Quit loop and process from this position when the parser", "# entered bracketed paste.", "self", ".", "feed", "(", "data", "[", "i", ":", "]", ")", "break", "else", ":", "# Replace \\r by \\n. (Some clients send \\r instead of \\n", "# when enter is pressed. E.g. telnet and some other", "# terminals.)", "# XXX: We should remove this in a future version. It *is*", "# now possible to recognise the difference.", "# (We remove ICRNL/INLCR/IGNCR below.)", "# However, this breaks IPython and maybe other applications,", "# because they bind ControlJ (\\n) for handling the Enter key.", "# When this is removed, replace Enter=ControlJ by", "# Enter=ControlM in keys.py.", "if", "c", "==", "'\\r'", ":", "c", "=", "'\\n'", "self", ".", "_input_parser", ".", "send", "(", "c", ")" ]
Feed the input stream. :param data: Input string (unicode).
[ "Feed", "the", "input", "stream", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/input_stream.py#L342-L398
226,773
GNS3/gns3-server
gns3server/compute/docker/__init__.py
Docker.query
def query(self, method, path, data={}, params={}): """ Make a query to the docker daemon and decode the request :param method: HTTP method :param path: Endpoint in API :param data: Dictionary with the body. Will be transformed to a JSON :param params: Parameters added as a query arg """ response = yield from self.http_query(method, path, data=data, params=params) body = yield from response.read() if body and len(body): if response.headers['CONTENT-TYPE'] == 'application/json': body = json.loads(body.decode("utf-8")) else: body = body.decode("utf-8") log.debug("Query Docker %s %s params=%s data=%s Response: %s", method, path, params, data, body) return body
python
def query(self, method, path, data={}, params={}): """ Make a query to the docker daemon and decode the request :param method: HTTP method :param path: Endpoint in API :param data: Dictionary with the body. Will be transformed to a JSON :param params: Parameters added as a query arg """ response = yield from self.http_query(method, path, data=data, params=params) body = yield from response.read() if body and len(body): if response.headers['CONTENT-TYPE'] == 'application/json': body = json.loads(body.decode("utf-8")) else: body = body.decode("utf-8") log.debug("Query Docker %s %s params=%s data=%s Response: %s", method, path, params, data, body) return body
[ "def", "query", "(", "self", ",", "method", ",", "path", ",", "data", "=", "{", "}", ",", "params", "=", "{", "}", ")", ":", "response", "=", "yield", "from", "self", ".", "http_query", "(", "method", ",", "path", ",", "data", "=", "data", ",", "params", "=", "params", ")", "body", "=", "yield", "from", "response", ".", "read", "(", ")", "if", "body", "and", "len", "(", "body", ")", ":", "if", "response", ".", "headers", "[", "'CONTENT-TYPE'", "]", "==", "'application/json'", ":", "body", "=", "json", ".", "loads", "(", "body", ".", "decode", "(", "\"utf-8\"", ")", ")", "else", ":", "body", "=", "body", ".", "decode", "(", "\"utf-8\"", ")", "log", ".", "debug", "(", "\"Query Docker %s %s params=%s data=%s Response: %s\"", ",", "method", ",", "path", ",", "params", ",", "data", ",", "body", ")", "return", "body" ]
Make a query to the docker daemon and decode the request :param method: HTTP method :param path: Endpoint in API :param data: Dictionary with the body. Will be transformed to a JSON :param params: Parameters added as a query arg
[ "Make", "a", "query", "to", "the", "docker", "daemon", "and", "decode", "the", "request" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/__init__.py#L96-L114
226,774
GNS3/gns3-server
gns3server/compute/docker/__init__.py
Docker.http_query
def http_query(self, method, path, data={}, params={}, timeout=300): """ Make a query to the docker daemon :param method: HTTP method :param path: Endpoint in API :param data: Dictionnary with the body. Will be transformed to a JSON :param params: Parameters added as a query arg :param timeout: Timeout :returns: HTTP response """ data = json.dumps(data) if timeout is None: timeout = 60 * 60 * 24 * 31 # One month timeout if path == 'version': url = "http://docker/v1.12/" + path # API of docker v1.0 else: url = "http://docker/v" + DOCKER_MINIMUM_API_VERSION + "/" + path try: if path != "version": # version is use by check connection yield from self._check_connection() if self._session is None or self._session.closed: connector = self.connector() self._session = aiohttp.ClientSession(connector=connector) response = yield from self._session.request( method, url, params=params, data=data, headers={"content-type": "application/json", }, timeout=timeout ) except (aiohttp.ClientResponseError, aiohttp.ClientOSError) as e: raise DockerError("Docker has returned an error: {}".format(str(e))) except (asyncio.TimeoutError): raise DockerError("Docker timeout " + method + " " + path) if response.status >= 300: body = yield from response.read() try: body = json.loads(body.decode("utf-8"))["message"] except ValueError: pass log.debug("Query Docker %s %s params=%s data=%s Response: %s", method, path, params, data, body) if response.status == 304: raise DockerHttp304Error("Docker has returned an error: {} {}".format(response.status, body)) elif response.status == 404: raise DockerHttp404Error("Docker has returned an error: {} {}".format(response.status, body)) else: raise DockerError("Docker has returned an error: {} {}".format(response.status, body)) return response
python
def http_query(self, method, path, data={}, params={}, timeout=300): """ Make a query to the docker daemon :param method: HTTP method :param path: Endpoint in API :param data: Dictionnary with the body. Will be transformed to a JSON :param params: Parameters added as a query arg :param timeout: Timeout :returns: HTTP response """ data = json.dumps(data) if timeout is None: timeout = 60 * 60 * 24 * 31 # One month timeout if path == 'version': url = "http://docker/v1.12/" + path # API of docker v1.0 else: url = "http://docker/v" + DOCKER_MINIMUM_API_VERSION + "/" + path try: if path != "version": # version is use by check connection yield from self._check_connection() if self._session is None or self._session.closed: connector = self.connector() self._session = aiohttp.ClientSession(connector=connector) response = yield from self._session.request( method, url, params=params, data=data, headers={"content-type": "application/json", }, timeout=timeout ) except (aiohttp.ClientResponseError, aiohttp.ClientOSError) as e: raise DockerError("Docker has returned an error: {}".format(str(e))) except (asyncio.TimeoutError): raise DockerError("Docker timeout " + method + " " + path) if response.status >= 300: body = yield from response.read() try: body = json.loads(body.decode("utf-8"))["message"] except ValueError: pass log.debug("Query Docker %s %s params=%s data=%s Response: %s", method, path, params, data, body) if response.status == 304: raise DockerHttp304Error("Docker has returned an error: {} {}".format(response.status, body)) elif response.status == 404: raise DockerHttp404Error("Docker has returned an error: {} {}".format(response.status, body)) else: raise DockerError("Docker has returned an error: {} {}".format(response.status, body)) return response
[ "def", "http_query", "(", "self", ",", "method", ",", "path", ",", "data", "=", "{", "}", ",", "params", "=", "{", "}", ",", "timeout", "=", "300", ")", ":", "data", "=", "json", ".", "dumps", "(", "data", ")", "if", "timeout", "is", "None", ":", "timeout", "=", "60", "*", "60", "*", "24", "*", "31", "# One month timeout", "if", "path", "==", "'version'", ":", "url", "=", "\"http://docker/v1.12/\"", "+", "path", "# API of docker v1.0", "else", ":", "url", "=", "\"http://docker/v\"", "+", "DOCKER_MINIMUM_API_VERSION", "+", "\"/\"", "+", "path", "try", ":", "if", "path", "!=", "\"version\"", ":", "# version is use by check connection", "yield", "from", "self", ".", "_check_connection", "(", ")", "if", "self", ".", "_session", "is", "None", "or", "self", ".", "_session", ".", "closed", ":", "connector", "=", "self", ".", "connector", "(", ")", "self", ".", "_session", "=", "aiohttp", ".", "ClientSession", "(", "connector", "=", "connector", ")", "response", "=", "yield", "from", "self", ".", "_session", ".", "request", "(", "method", ",", "url", ",", "params", "=", "params", ",", "data", "=", "data", ",", "headers", "=", "{", "\"content-type\"", ":", "\"application/json\"", ",", "}", ",", "timeout", "=", "timeout", ")", "except", "(", "aiohttp", ".", "ClientResponseError", ",", "aiohttp", ".", "ClientOSError", ")", "as", "e", ":", "raise", "DockerError", "(", "\"Docker has returned an error: {}\"", ".", "format", "(", "str", "(", "e", ")", ")", ")", "except", "(", "asyncio", ".", "TimeoutError", ")", ":", "raise", "DockerError", "(", "\"Docker timeout \"", "+", "method", "+", "\" \"", "+", "path", ")", "if", "response", ".", "status", ">=", "300", ":", "body", "=", "yield", "from", "response", ".", "read", "(", ")", "try", ":", "body", "=", "json", ".", "loads", "(", "body", ".", "decode", "(", "\"utf-8\"", ")", ")", "[", "\"message\"", "]", "except", "ValueError", ":", "pass", "log", ".", "debug", "(", "\"Query Docker %s %s params=%s data=%s Response: %s\"", ",", "method", ",", "path", ",", "params", ",", "data", ",", "body", ")", "if", "response", ".", "status", "==", "304", ":", "raise", "DockerHttp304Error", "(", "\"Docker has returned an error: {} {}\"", ".", "format", "(", "response", ".", "status", ",", "body", ")", ")", "elif", "response", ".", "status", "==", "404", ":", "raise", "DockerHttp404Error", "(", "\"Docker has returned an error: {} {}\"", ".", "format", "(", "response", ".", "status", ",", "body", ")", ")", "else", ":", "raise", "DockerError", "(", "\"Docker has returned an error: {} {}\"", ".", "format", "(", "response", ".", "status", ",", "body", ")", ")", "return", "response" ]
Make a query to the docker daemon :param method: HTTP method :param path: Endpoint in API :param data: Dictionnary with the body. Will be transformed to a JSON :param params: Parameters added as a query arg :param timeout: Timeout :returns: HTTP response
[ "Make", "a", "query", "to", "the", "docker", "daemon" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/__init__.py#L117-L167
226,775
GNS3/gns3-server
gns3server/compute/docker/__init__.py
Docker.websocket_query
def websocket_query(self, path, params={}): """ Open a websocket connection :param path: Endpoint in API :param params: Parameters added as a query arg :returns: Websocket """ url = "http://docker/v" + self._api_version + "/" + path connection = yield from self._session.ws_connect(url, origin="http://docker", autoping=True) return connection
python
def websocket_query(self, path, params={}): """ Open a websocket connection :param path: Endpoint in API :param params: Parameters added as a query arg :returns: Websocket """ url = "http://docker/v" + self._api_version + "/" + path connection = yield from self._session.ws_connect(url, origin="http://docker", autoping=True) return connection
[ "def", "websocket_query", "(", "self", ",", "path", ",", "params", "=", "{", "}", ")", ":", "url", "=", "\"http://docker/v\"", "+", "self", ".", "_api_version", "+", "\"/\"", "+", "path", "connection", "=", "yield", "from", "self", ".", "_session", ".", "ws_connect", "(", "url", ",", "origin", "=", "\"http://docker\"", ",", "autoping", "=", "True", ")", "return", "connection" ]
Open a websocket connection :param path: Endpoint in API :param params: Parameters added as a query arg :returns: Websocket
[ "Open", "a", "websocket", "connection" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/__init__.py#L170-L183
226,776
GNS3/gns3-server
gns3server/compute/docker/__init__.py
Docker.list_images
def list_images(self): """Gets Docker image list. :returns: list of dicts :rtype: list """ images = [] for image in (yield from self.query("GET", "images/json", params={"all": 0})): if image['RepoTags']: for tag in image['RepoTags']: if tag != "<none>:<none>": images.append({'image': tag}) return sorted(images, key=lambda i: i['image'])
python
def list_images(self): """Gets Docker image list. :returns: list of dicts :rtype: list """ images = [] for image in (yield from self.query("GET", "images/json", params={"all": 0})): if image['RepoTags']: for tag in image['RepoTags']: if tag != "<none>:<none>": images.append({'image': tag}) return sorted(images, key=lambda i: i['image'])
[ "def", "list_images", "(", "self", ")", ":", "images", "=", "[", "]", "for", "image", "in", "(", "yield", "from", "self", ".", "query", "(", "\"GET\"", ",", "\"images/json\"", ",", "params", "=", "{", "\"all\"", ":", "0", "}", ")", ")", ":", "if", "image", "[", "'RepoTags'", "]", ":", "for", "tag", "in", "image", "[", "'RepoTags'", "]", ":", "if", "tag", "!=", "\"<none>:<none>\"", ":", "images", ".", "append", "(", "{", "'image'", ":", "tag", "}", ")", "return", "sorted", "(", "images", ",", "key", "=", "lambda", "i", ":", "i", "[", "'image'", "]", ")" ]
Gets Docker image list. :returns: list of dicts :rtype: list
[ "Gets", "Docker", "image", "list", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/__init__.py#L228-L240
226,777
GNS3/gns3-server
gns3server/compute/qemu/__init__.py
Qemu.get_kvm_archs
def get_kvm_archs(): """ Gets a list of architectures for which KVM is available on this server. :returns: List of architectures for which KVM is available on this server. """ kvm = [] if not os.path.exists("/dev/kvm"): return kvm arch = platform.machine() if arch == "x86_64": kvm.append("x86_64") kvm.append("i386") elif arch == "i386": kvm.append("i386") else: kvm.append(platform.machine()) return kvm
python
def get_kvm_archs(): """ Gets a list of architectures for which KVM is available on this server. :returns: List of architectures for which KVM is available on this server. """ kvm = [] if not os.path.exists("/dev/kvm"): return kvm arch = platform.machine() if arch == "x86_64": kvm.append("x86_64") kvm.append("i386") elif arch == "i386": kvm.append("i386") else: kvm.append(platform.machine()) return kvm
[ "def", "get_kvm_archs", "(", ")", ":", "kvm", "=", "[", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "\"/dev/kvm\"", ")", ":", "return", "kvm", "arch", "=", "platform", ".", "machine", "(", ")", "if", "arch", "==", "\"x86_64\"", ":", "kvm", ".", "append", "(", "\"x86_64\"", ")", "kvm", ".", "append", "(", "\"i386\"", ")", "elif", "arch", "==", "\"i386\"", ":", "kvm", ".", "append", "(", "\"i386\"", ")", "else", ":", "kvm", ".", "append", "(", "platform", ".", "machine", "(", ")", ")", "return", "kvm" ]
Gets a list of architectures for which KVM is available on this server. :returns: List of architectures for which KVM is available on this server.
[ "Gets", "a", "list", "of", "architectures", "for", "which", "KVM", "is", "available", "on", "this", "server", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/__init__.py#L45-L64
226,778
GNS3/gns3-server
gns3server/compute/qemu/__init__.py
Qemu.paths_list
def paths_list(): """ Gets a folder list of possibly available QEMU binaries on the host. :returns: List of folders where Qemu binaries MAY reside. """ paths = set() try: paths.add(os.getcwd()) except FileNotFoundError: log.warning("The current working directory doesn't exist") if "PATH" in os.environ: paths.update(os.environ["PATH"].split(os.pathsep)) else: log.warning("The PATH environment variable doesn't exist") # look for Qemu binaries in the current working directory and $PATH if sys.platform.startswith("win"): # add specific Windows paths if hasattr(sys, "frozen"): # add any qemu dir in the same location as gns3server.exe to the list of paths exec_dir = os.path.dirname(os.path.abspath(sys.executable)) for f in os.listdir(exec_dir): if f.lower().startswith("qemu"): paths.add(os.path.join(exec_dir, f)) if "PROGRAMFILES(X86)" in os.environ and os.path.exists(os.environ["PROGRAMFILES(X86)"]): paths.add(os.path.join(os.environ["PROGRAMFILES(X86)"], "qemu")) if "PROGRAMFILES" in os.environ and os.path.exists(os.environ["PROGRAMFILES"]): paths.add(os.path.join(os.environ["PROGRAMFILES"], "qemu")) elif sys.platform.startswith("darwin"): if hasattr(sys, "frozen"): # add specific locations on Mac OS X regardless of what's in $PATH paths.update(["/usr/bin", "/usr/local/bin", "/opt/local/bin"]) try: exec_dir = os.path.dirname(os.path.abspath(sys.executable)) paths.add(os.path.abspath(os.path.join(exec_dir, "../Resources/qemu/bin/"))) # If the user run the server by hand from outside except FileNotFoundError: paths.add("/Applications/GNS3.app/Contents/Resources/qemu/bin") return paths
python
def paths_list(): """ Gets a folder list of possibly available QEMU binaries on the host. :returns: List of folders where Qemu binaries MAY reside. """ paths = set() try: paths.add(os.getcwd()) except FileNotFoundError: log.warning("The current working directory doesn't exist") if "PATH" in os.environ: paths.update(os.environ["PATH"].split(os.pathsep)) else: log.warning("The PATH environment variable doesn't exist") # look for Qemu binaries in the current working directory and $PATH if sys.platform.startswith("win"): # add specific Windows paths if hasattr(sys, "frozen"): # add any qemu dir in the same location as gns3server.exe to the list of paths exec_dir = os.path.dirname(os.path.abspath(sys.executable)) for f in os.listdir(exec_dir): if f.lower().startswith("qemu"): paths.add(os.path.join(exec_dir, f)) if "PROGRAMFILES(X86)" in os.environ and os.path.exists(os.environ["PROGRAMFILES(X86)"]): paths.add(os.path.join(os.environ["PROGRAMFILES(X86)"], "qemu")) if "PROGRAMFILES" in os.environ and os.path.exists(os.environ["PROGRAMFILES"]): paths.add(os.path.join(os.environ["PROGRAMFILES"], "qemu")) elif sys.platform.startswith("darwin"): if hasattr(sys, "frozen"): # add specific locations on Mac OS X regardless of what's in $PATH paths.update(["/usr/bin", "/usr/local/bin", "/opt/local/bin"]) try: exec_dir = os.path.dirname(os.path.abspath(sys.executable)) paths.add(os.path.abspath(os.path.join(exec_dir, "../Resources/qemu/bin/"))) # If the user run the server by hand from outside except FileNotFoundError: paths.add("/Applications/GNS3.app/Contents/Resources/qemu/bin") return paths
[ "def", "paths_list", "(", ")", ":", "paths", "=", "set", "(", ")", "try", ":", "paths", ".", "add", "(", "os", ".", "getcwd", "(", ")", ")", "except", "FileNotFoundError", ":", "log", ".", "warning", "(", "\"The current working directory doesn't exist\"", ")", "if", "\"PATH\"", "in", "os", ".", "environ", ":", "paths", ".", "update", "(", "os", ".", "environ", "[", "\"PATH\"", "]", ".", "split", "(", "os", ".", "pathsep", ")", ")", "else", ":", "log", ".", "warning", "(", "\"The PATH environment variable doesn't exist\"", ")", "# look for Qemu binaries in the current working directory and $PATH", "if", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", ":", "# add specific Windows paths", "if", "hasattr", "(", "sys", ",", "\"frozen\"", ")", ":", "# add any qemu dir in the same location as gns3server.exe to the list of paths", "exec_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "sys", ".", "executable", ")", ")", "for", "f", "in", "os", ".", "listdir", "(", "exec_dir", ")", ":", "if", "f", ".", "lower", "(", ")", ".", "startswith", "(", "\"qemu\"", ")", ":", "paths", ".", "add", "(", "os", ".", "path", ".", "join", "(", "exec_dir", ",", "f", ")", ")", "if", "\"PROGRAMFILES(X86)\"", "in", "os", ".", "environ", "and", "os", ".", "path", ".", "exists", "(", "os", ".", "environ", "[", "\"PROGRAMFILES(X86)\"", "]", ")", ":", "paths", ".", "add", "(", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "\"PROGRAMFILES(X86)\"", "]", ",", "\"qemu\"", ")", ")", "if", "\"PROGRAMFILES\"", "in", "os", ".", "environ", "and", "os", ".", "path", ".", "exists", "(", "os", ".", "environ", "[", "\"PROGRAMFILES\"", "]", ")", ":", "paths", ".", "add", "(", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "\"PROGRAMFILES\"", "]", ",", "\"qemu\"", ")", ")", "elif", "sys", ".", "platform", ".", "startswith", "(", "\"darwin\"", ")", ":", "if", "hasattr", "(", "sys", ",", "\"frozen\"", ")", ":", "# add specific locations on Mac OS X regardless of what's in $PATH", "paths", ".", "update", "(", "[", "\"/usr/bin\"", ",", "\"/usr/local/bin\"", ",", "\"/opt/local/bin\"", "]", ")", "try", ":", "exec_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "sys", ".", "executable", ")", ")", "paths", ".", "add", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "exec_dir", ",", "\"../Resources/qemu/bin/\"", ")", ")", ")", "# If the user run the server by hand from outside", "except", "FileNotFoundError", ":", "paths", ".", "add", "(", "\"/Applications/GNS3.app/Contents/Resources/qemu/bin\"", ")", "return", "paths" ]
Gets a folder list of possibly available QEMU binaries on the host. :returns: List of folders where Qemu binaries MAY reside.
[ "Gets", "a", "folder", "list", "of", "possibly", "available", "QEMU", "binaries", "on", "the", "host", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/__init__.py#L67-L107
226,779
GNS3/gns3-server
gns3server/compute/qemu/__init__.py
Qemu.binary_list
def binary_list(archs=None): """ Gets QEMU binaries list available on the host. :returns: Array of dictionary {"path": Qemu binary path, "version": version of Qemu} """ qemus = [] for path in Qemu.paths_list(): try: for f in os.listdir(path): if f.endswith("-spice"): continue if (f.startswith("qemu-system") or f.startswith("qemu-kvm") or f == "qemu" or f == "qemu.exe") and \ os.access(os.path.join(path, f), os.X_OK) and \ os.path.isfile(os.path.join(path, f)): if archs is not None: for arch in archs: if f.endswith(arch) or f.endswith("{}.exe".format(arch)) or f.endswith("{}w.exe".format(arch)): qemu_path = os.path.join(path, f) version = yield from Qemu.get_qemu_version(qemu_path) qemus.append({"path": qemu_path, "version": version}) else: qemu_path = os.path.join(path, f) version = yield from Qemu.get_qemu_version(qemu_path) qemus.append({"path": qemu_path, "version": version}) except OSError: continue return qemus
python
def binary_list(archs=None): """ Gets QEMU binaries list available on the host. :returns: Array of dictionary {"path": Qemu binary path, "version": version of Qemu} """ qemus = [] for path in Qemu.paths_list(): try: for f in os.listdir(path): if f.endswith("-spice"): continue if (f.startswith("qemu-system") or f.startswith("qemu-kvm") or f == "qemu" or f == "qemu.exe") and \ os.access(os.path.join(path, f), os.X_OK) and \ os.path.isfile(os.path.join(path, f)): if archs is not None: for arch in archs: if f.endswith(arch) or f.endswith("{}.exe".format(arch)) or f.endswith("{}w.exe".format(arch)): qemu_path = os.path.join(path, f) version = yield from Qemu.get_qemu_version(qemu_path) qemus.append({"path": qemu_path, "version": version}) else: qemu_path = os.path.join(path, f) version = yield from Qemu.get_qemu_version(qemu_path) qemus.append({"path": qemu_path, "version": version}) except OSError: continue return qemus
[ "def", "binary_list", "(", "archs", "=", "None", ")", ":", "qemus", "=", "[", "]", "for", "path", "in", "Qemu", ".", "paths_list", "(", ")", ":", "try", ":", "for", "f", "in", "os", ".", "listdir", "(", "path", ")", ":", "if", "f", ".", "endswith", "(", "\"-spice\"", ")", ":", "continue", "if", "(", "f", ".", "startswith", "(", "\"qemu-system\"", ")", "or", "f", ".", "startswith", "(", "\"qemu-kvm\"", ")", "or", "f", "==", "\"qemu\"", "or", "f", "==", "\"qemu.exe\"", ")", "and", "os", ".", "access", "(", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")", ",", "os", ".", "X_OK", ")", "and", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")", ")", ":", "if", "archs", "is", "not", "None", ":", "for", "arch", "in", "archs", ":", "if", "f", ".", "endswith", "(", "arch", ")", "or", "f", ".", "endswith", "(", "\"{}.exe\"", ".", "format", "(", "arch", ")", ")", "or", "f", ".", "endswith", "(", "\"{}w.exe\"", ".", "format", "(", "arch", ")", ")", ":", "qemu_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")", "version", "=", "yield", "from", "Qemu", ".", "get_qemu_version", "(", "qemu_path", ")", "qemus", ".", "append", "(", "{", "\"path\"", ":", "qemu_path", ",", "\"version\"", ":", "version", "}", ")", "else", ":", "qemu_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")", "version", "=", "yield", "from", "Qemu", ".", "get_qemu_version", "(", "qemu_path", ")", "qemus", ".", "append", "(", "{", "\"path\"", ":", "qemu_path", ",", "\"version\"", ":", "version", "}", ")", "except", "OSError", ":", "continue", "return", "qemus" ]
Gets QEMU binaries list available on the host. :returns: Array of dictionary {"path": Qemu binary path, "version": version of Qemu}
[ "Gets", "QEMU", "binaries", "list", "available", "on", "the", "host", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/__init__.py#L110-L140
226,780
GNS3/gns3-server
gns3server/compute/qemu/__init__.py
Qemu.img_binary_list
def img_binary_list(): """ Gets QEMU-img binaries list available on the host. :returns: Array of dictionary {"path": Qemu-img binary path, "version": version of Qemu-img} """ qemu_imgs = [] for path in Qemu.paths_list(): try: for f in os.listdir(path): if (f == "qemu-img" or f == "qemu-img.exe") and \ os.access(os.path.join(path, f), os.X_OK) and \ os.path.isfile(os.path.join(path, f)): qemu_path = os.path.join(path, f) version = yield from Qemu._get_qemu_img_version(qemu_path) qemu_imgs.append({"path": qemu_path, "version": version}) except OSError: continue return qemu_imgs
python
def img_binary_list(): """ Gets QEMU-img binaries list available on the host. :returns: Array of dictionary {"path": Qemu-img binary path, "version": version of Qemu-img} """ qemu_imgs = [] for path in Qemu.paths_list(): try: for f in os.listdir(path): if (f == "qemu-img" or f == "qemu-img.exe") and \ os.access(os.path.join(path, f), os.X_OK) and \ os.path.isfile(os.path.join(path, f)): qemu_path = os.path.join(path, f) version = yield from Qemu._get_qemu_img_version(qemu_path) qemu_imgs.append({"path": qemu_path, "version": version}) except OSError: continue return qemu_imgs
[ "def", "img_binary_list", "(", ")", ":", "qemu_imgs", "=", "[", "]", "for", "path", "in", "Qemu", ".", "paths_list", "(", ")", ":", "try", ":", "for", "f", "in", "os", ".", "listdir", "(", "path", ")", ":", "if", "(", "f", "==", "\"qemu-img\"", "or", "f", "==", "\"qemu-img.exe\"", ")", "and", "os", ".", "access", "(", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")", ",", "os", ".", "X_OK", ")", "and", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")", ")", ":", "qemu_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")", "version", "=", "yield", "from", "Qemu", ".", "_get_qemu_img_version", "(", "qemu_path", ")", "qemu_imgs", ".", "append", "(", "{", "\"path\"", ":", "qemu_path", ",", "\"version\"", ":", "version", "}", ")", "except", "OSError", ":", "continue", "return", "qemu_imgs" ]
Gets QEMU-img binaries list available on the host. :returns: Array of dictionary {"path": Qemu-img binary path, "version": version of Qemu-img}
[ "Gets", "QEMU", "-", "img", "binaries", "list", "available", "on", "the", "host", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/__init__.py#L143-L162
226,781
GNS3/gns3-server
gns3server/compute/qemu/__init__.py
Qemu.get_qemu_version
def get_qemu_version(qemu_path): """ Gets the Qemu version. :param qemu_path: path to Qemu executable. """ if sys.platform.startswith("win"): # Qemu on Windows doesn't return anything with parameter -version # look for a version number in version.txt file in the same directory instead version_file = os.path.join(os.path.dirname(qemu_path), "version.txt") if os.path.isfile(version_file): try: with open(version_file, "rb") as file: version = file.read().decode("utf-8").strip() match = re.search("[0-9\.]+", version) if match: return version except (UnicodeDecodeError, OSError) as e: log.warn("could not read {}: {}".format(version_file, e)) return "" else: try: output = yield from subprocess_check_output(qemu_path, "-version") match = re.search("version\s+([0-9a-z\-\.]+)", output) if match: version = match.group(1) return version else: raise QemuError("Could not determine the Qemu version for {}".format(qemu_path)) except subprocess.SubprocessError as e: raise QemuError("Error while looking for the Qemu version: {}".format(e))
python
def get_qemu_version(qemu_path): """ Gets the Qemu version. :param qemu_path: path to Qemu executable. """ if sys.platform.startswith("win"): # Qemu on Windows doesn't return anything with parameter -version # look for a version number in version.txt file in the same directory instead version_file = os.path.join(os.path.dirname(qemu_path), "version.txt") if os.path.isfile(version_file): try: with open(version_file, "rb") as file: version = file.read().decode("utf-8").strip() match = re.search("[0-9\.]+", version) if match: return version except (UnicodeDecodeError, OSError) as e: log.warn("could not read {}: {}".format(version_file, e)) return "" else: try: output = yield from subprocess_check_output(qemu_path, "-version") match = re.search("version\s+([0-9a-z\-\.]+)", output) if match: version = match.group(1) return version else: raise QemuError("Could not determine the Qemu version for {}".format(qemu_path)) except subprocess.SubprocessError as e: raise QemuError("Error while looking for the Qemu version: {}".format(e))
[ "def", "get_qemu_version", "(", "qemu_path", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", ":", "# Qemu on Windows doesn't return anything with parameter -version", "# look for a version number in version.txt file in the same directory instead", "version_file", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "qemu_path", ")", ",", "\"version.txt\"", ")", "if", "os", ".", "path", ".", "isfile", "(", "version_file", ")", ":", "try", ":", "with", "open", "(", "version_file", ",", "\"rb\"", ")", "as", "file", ":", "version", "=", "file", ".", "read", "(", ")", ".", "decode", "(", "\"utf-8\"", ")", ".", "strip", "(", ")", "match", "=", "re", ".", "search", "(", "\"[0-9\\.]+\"", ",", "version", ")", "if", "match", ":", "return", "version", "except", "(", "UnicodeDecodeError", ",", "OSError", ")", "as", "e", ":", "log", ".", "warn", "(", "\"could not read {}: {}\"", ".", "format", "(", "version_file", ",", "e", ")", ")", "return", "\"\"", "else", ":", "try", ":", "output", "=", "yield", "from", "subprocess_check_output", "(", "qemu_path", ",", "\"-version\"", ")", "match", "=", "re", ".", "search", "(", "\"version\\s+([0-9a-z\\-\\.]+)\"", ",", "output", ")", "if", "match", ":", "version", "=", "match", ".", "group", "(", "1", ")", "return", "version", "else", ":", "raise", "QemuError", "(", "\"Could not determine the Qemu version for {}\"", ".", "format", "(", "qemu_path", ")", ")", "except", "subprocess", ".", "SubprocessError", "as", "e", ":", "raise", "QemuError", "(", "\"Error while looking for the Qemu version: {}\"", ".", "format", "(", "e", ")", ")" ]
Gets the Qemu version. :param qemu_path: path to Qemu executable.
[ "Gets", "the", "Qemu", "version", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/__init__.py#L166-L197
226,782
GNS3/gns3-server
gns3server/compute/qemu/__init__.py
Qemu._get_qemu_img_version
def _get_qemu_img_version(qemu_img_path): """ Gets the Qemu-img version. :param qemu_img_path: path to Qemu-img executable. """ try: output = yield from subprocess_check_output(qemu_img_path, "--version") match = re.search("version\s+([0-9a-z\-\.]+)", output) if match: version = match.group(1) return version else: raise QemuError("Could not determine the Qemu-img version for {}".format(qemu_img_path)) except subprocess.SubprocessError as e: raise QemuError("Error while looking for the Qemu-img version: {}".format(e))
python
def _get_qemu_img_version(qemu_img_path): """ Gets the Qemu-img version. :param qemu_img_path: path to Qemu-img executable. """ try: output = yield from subprocess_check_output(qemu_img_path, "--version") match = re.search("version\s+([0-9a-z\-\.]+)", output) if match: version = match.group(1) return version else: raise QemuError("Could not determine the Qemu-img version for {}".format(qemu_img_path)) except subprocess.SubprocessError as e: raise QemuError("Error while looking for the Qemu-img version: {}".format(e))
[ "def", "_get_qemu_img_version", "(", "qemu_img_path", ")", ":", "try", ":", "output", "=", "yield", "from", "subprocess_check_output", "(", "qemu_img_path", ",", "\"--version\"", ")", "match", "=", "re", ".", "search", "(", "\"version\\s+([0-9a-z\\-\\.]+)\"", ",", "output", ")", "if", "match", ":", "version", "=", "match", ".", "group", "(", "1", ")", "return", "version", "else", ":", "raise", "QemuError", "(", "\"Could not determine the Qemu-img version for {}\"", ".", "format", "(", "qemu_img_path", ")", ")", "except", "subprocess", ".", "SubprocessError", "as", "e", ":", "raise", "QemuError", "(", "\"Error while looking for the Qemu-img version: {}\"", ".", "format", "(", "e", ")", ")" ]
Gets the Qemu-img version. :param qemu_img_path: path to Qemu-img executable.
[ "Gets", "the", "Qemu", "-", "img", "version", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/__init__.py#L201-L217
226,783
GNS3/gns3-server
gns3server/compute/qemu/__init__.py
Qemu.create_disk
def create_disk(self, qemu_img, path, options): """ Create a qemu disk with qemu-img :param qemu_img: qemu-img binary path :param path: Image path :param options: Disk image creation options """ try: img_format = options.pop("format") img_size = options.pop("size") if not os.path.isabs(path): directory = self.get_images_directory() os.makedirs(directory, exist_ok=True) path = os.path.join(directory, os.path.basename(path)) try: if os.path.exists(path): raise QemuError("Could not create disk image {} already exist".format(path)) except UnicodeEncodeError: raise QemuError("Could not create disk image {}, " "path contains characters not supported by filesystem".format(path)) command = [qemu_img, "create", "-f", img_format] for option in sorted(options.keys()): command.extend(["-o", "{}={}".format(option, options[option])]) command.append(path) command.append("{}M".format(img_size)) process = yield from asyncio.create_subprocess_exec(*command) yield from process.wait() except (OSError, subprocess.SubprocessError) as e: raise QemuError("Could not create disk image {}:{}".format(path, e))
python
def create_disk(self, qemu_img, path, options): """ Create a qemu disk with qemu-img :param qemu_img: qemu-img binary path :param path: Image path :param options: Disk image creation options """ try: img_format = options.pop("format") img_size = options.pop("size") if not os.path.isabs(path): directory = self.get_images_directory() os.makedirs(directory, exist_ok=True) path = os.path.join(directory, os.path.basename(path)) try: if os.path.exists(path): raise QemuError("Could not create disk image {} already exist".format(path)) except UnicodeEncodeError: raise QemuError("Could not create disk image {}, " "path contains characters not supported by filesystem".format(path)) command = [qemu_img, "create", "-f", img_format] for option in sorted(options.keys()): command.extend(["-o", "{}={}".format(option, options[option])]) command.append(path) command.append("{}M".format(img_size)) process = yield from asyncio.create_subprocess_exec(*command) yield from process.wait() except (OSError, subprocess.SubprocessError) as e: raise QemuError("Could not create disk image {}:{}".format(path, e))
[ "def", "create_disk", "(", "self", ",", "qemu_img", ",", "path", ",", "options", ")", ":", "try", ":", "img_format", "=", "options", ".", "pop", "(", "\"format\"", ")", "img_size", "=", "options", ".", "pop", "(", "\"size\"", ")", "if", "not", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "directory", "=", "self", ".", "get_images_directory", "(", ")", "os", ".", "makedirs", "(", "directory", ",", "exist_ok", "=", "True", ")", "path", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "os", ".", "path", ".", "basename", "(", "path", ")", ")", "try", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "QemuError", "(", "\"Could not create disk image {} already exist\"", ".", "format", "(", "path", ")", ")", "except", "UnicodeEncodeError", ":", "raise", "QemuError", "(", "\"Could not create disk image {}, \"", "\"path contains characters not supported by filesystem\"", ".", "format", "(", "path", ")", ")", "command", "=", "[", "qemu_img", ",", "\"create\"", ",", "\"-f\"", ",", "img_format", "]", "for", "option", "in", "sorted", "(", "options", ".", "keys", "(", ")", ")", ":", "command", ".", "extend", "(", "[", "\"-o\"", ",", "\"{}={}\"", ".", "format", "(", "option", ",", "options", "[", "option", "]", ")", "]", ")", "command", ".", "append", "(", "path", ")", "command", ".", "append", "(", "\"{}M\"", ".", "format", "(", "img_size", ")", ")", "process", "=", "yield", "from", "asyncio", ".", "create_subprocess_exec", "(", "*", "command", ")", "yield", "from", "process", ".", "wait", "(", ")", "except", "(", "OSError", ",", "subprocess", ".", "SubprocessError", ")", "as", "e", ":", "raise", "QemuError", "(", "\"Could not create disk image {}:{}\"", ".", "format", "(", "path", ",", "e", ")", ")" ]
Create a qemu disk with qemu-img :param qemu_img: qemu-img binary path :param path: Image path :param options: Disk image creation options
[ "Create", "a", "qemu", "disk", "with", "qemu", "-", "img" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/__init__.py#L233-L267
226,784
jmcarpenter2/swifter
swifter/swifter.py
_SwifterObject.set_npartitions
def set_npartitions(self, npartitions=None): """ Set the number of partitions to use for dask """ if npartitions is None: self._npartitions = cpu_count() * 2 else: self._npartitions = npartitions return self
python
def set_npartitions(self, npartitions=None): """ Set the number of partitions to use for dask """ if npartitions is None: self._npartitions = cpu_count() * 2 else: self._npartitions = npartitions return self
[ "def", "set_npartitions", "(", "self", ",", "npartitions", "=", "None", ")", ":", "if", "npartitions", "is", "None", ":", "self", ".", "_npartitions", "=", "cpu_count", "(", ")", "*", "2", "else", ":", "self", ".", "_npartitions", "=", "npartitions", "return", "self" ]
Set the number of partitions to use for dask
[ "Set", "the", "number", "of", "partitions", "to", "use", "for", "dask" ]
ed5fc3235b43f981fa58ac9bc982c8209d4e3df3
https://github.com/jmcarpenter2/swifter/blob/ed5fc3235b43f981fa58ac9bc982c8209d4e3df3/swifter/swifter.py#L39-L47
226,785
jmcarpenter2/swifter
swifter/swifter.py
_SwifterObject.rolling
def rolling(self, window, min_periods=None, center=False, win_type=None, on=None, axis=0, closed=None): """ Create a swifter rolling object """ kwds = { "window": window, "min_periods": min_periods, "center": center, "win_type": win_type, "on": on, "axis": axis, "closed": closed, } return Rolling(self._obj, self._npartitions, self._dask_threshold, self._scheduler, self._progress_bar, **kwds)
python
def rolling(self, window, min_periods=None, center=False, win_type=None, on=None, axis=0, closed=None): """ Create a swifter rolling object """ kwds = { "window": window, "min_periods": min_periods, "center": center, "win_type": win_type, "on": on, "axis": axis, "closed": closed, } return Rolling(self._obj, self._npartitions, self._dask_threshold, self._scheduler, self._progress_bar, **kwds)
[ "def", "rolling", "(", "self", ",", "window", ",", "min_periods", "=", "None", ",", "center", "=", "False", ",", "win_type", "=", "None", ",", "on", "=", "None", ",", "axis", "=", "0", ",", "closed", "=", "None", ")", ":", "kwds", "=", "{", "\"window\"", ":", "window", ",", "\"min_periods\"", ":", "min_periods", ",", "\"center\"", ":", "center", ",", "\"win_type\"", ":", "win_type", ",", "\"on\"", ":", "on", ",", "\"axis\"", ":", "axis", ",", "\"closed\"", ":", "closed", ",", "}", "return", "Rolling", "(", "self", ".", "_obj", ",", "self", ".", "_npartitions", ",", "self", ".", "_dask_threshold", ",", "self", ".", "_scheduler", ",", "self", ".", "_progress_bar", ",", "*", "*", "kwds", ")" ]
Create a swifter rolling object
[ "Create", "a", "swifter", "rolling", "object" ]
ed5fc3235b43f981fa58ac9bc982c8209d4e3df3
https://github.com/jmcarpenter2/swifter/blob/ed5fc3235b43f981fa58ac9bc982c8209d4e3df3/swifter/swifter.py#L78-L91
226,786
jmcarpenter2/swifter
swifter/swifter.py
Transformation.apply
def apply(self, func, *args, **kwds): """ Apply the function to the transformed swifter object """ # estimate time to pandas apply wrapped = self._wrapped_apply(func, *args, **kwds) n_repeats = 3 timed = timeit.timeit(wrapped, number=n_repeats) samp_proc_est = timed / n_repeats est_apply_duration = samp_proc_est / self._SAMP_SIZE * self._nrows # if pandas apply takes too long, use dask if est_apply_duration > self._dask_threshold: return self._dask_apply(func, *args, **kwds) else: # use pandas if self._progress_bar: tqdm.pandas(desc="Pandas Apply") return self._obj_pd.progress_apply(func, *args, **kwds) else: return self._obj_pd.apply(func, *args, **kwds)
python
def apply(self, func, *args, **kwds): """ Apply the function to the transformed swifter object """ # estimate time to pandas apply wrapped = self._wrapped_apply(func, *args, **kwds) n_repeats = 3 timed = timeit.timeit(wrapped, number=n_repeats) samp_proc_est = timed / n_repeats est_apply_duration = samp_proc_est / self._SAMP_SIZE * self._nrows # if pandas apply takes too long, use dask if est_apply_duration > self._dask_threshold: return self._dask_apply(func, *args, **kwds) else: # use pandas if self._progress_bar: tqdm.pandas(desc="Pandas Apply") return self._obj_pd.progress_apply(func, *args, **kwds) else: return self._obj_pd.apply(func, *args, **kwds)
[ "def", "apply", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "# estimate time to pandas apply", "wrapped", "=", "self", ".", "_wrapped_apply", "(", "func", ",", "*", "args", ",", "*", "*", "kwds", ")", "n_repeats", "=", "3", "timed", "=", "timeit", ".", "timeit", "(", "wrapped", ",", "number", "=", "n_repeats", ")", "samp_proc_est", "=", "timed", "/", "n_repeats", "est_apply_duration", "=", "samp_proc_est", "/", "self", ".", "_SAMP_SIZE", "*", "self", ".", "_nrows", "# if pandas apply takes too long, use dask", "if", "est_apply_duration", ">", "self", ".", "_dask_threshold", ":", "return", "self", ".", "_dask_apply", "(", "func", ",", "*", "args", ",", "*", "*", "kwds", ")", "else", ":", "# use pandas", "if", "self", ".", "_progress_bar", ":", "tqdm", ".", "pandas", "(", "desc", "=", "\"Pandas Apply\"", ")", "return", "self", ".", "_obj_pd", ".", "progress_apply", "(", "func", ",", "*", "args", ",", "*", "*", "kwds", ")", "else", ":", "return", "self", ".", "_obj_pd", ".", "apply", "(", "func", ",", "*", "args", ",", "*", "*", "kwds", ")" ]
Apply the function to the transformed swifter object
[ "Apply", "the", "function", "to", "the", "transformed", "swifter", "object" ]
ed5fc3235b43f981fa58ac9bc982c8209d4e3df3
https://github.com/jmcarpenter2/swifter/blob/ed5fc3235b43f981fa58ac9bc982c8209d4e3df3/swifter/swifter.py#L338-L357
226,787
summernote/django-summernote
django_summernote/utils.py
using_config
def using_config(_func=None): """ This allows a function to use Summernote configuration as a global variable, temporarily. """ def decorator(func): @wraps(func) def inner_dec(*args, **kwargs): g = func.__globals__ var_name = 'config' sentinel = object() oldvalue = g.get(var_name, sentinel) g[var_name] = apps.get_app_config('django_summernote').config try: res = func(*args, **kwargs) finally: if oldvalue is sentinel: del g[var_name] else: g[var_name] = oldvalue return res return inner_dec if _func is None: return decorator else: return decorator(_func)
python
def using_config(_func=None): """ This allows a function to use Summernote configuration as a global variable, temporarily. """ def decorator(func): @wraps(func) def inner_dec(*args, **kwargs): g = func.__globals__ var_name = 'config' sentinel = object() oldvalue = g.get(var_name, sentinel) g[var_name] = apps.get_app_config('django_summernote').config try: res = func(*args, **kwargs) finally: if oldvalue is sentinel: del g[var_name] else: g[var_name] = oldvalue return res return inner_dec if _func is None: return decorator else: return decorator(_func)
[ "def", "using_config", "(", "_func", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "inner_dec", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "g", "=", "func", ".", "__globals__", "var_name", "=", "'config'", "sentinel", "=", "object", "(", ")", "oldvalue", "=", "g", ".", "get", "(", "var_name", ",", "sentinel", ")", "g", "[", "var_name", "]", "=", "apps", ".", "get_app_config", "(", "'django_summernote'", ")", ".", "config", "try", ":", "res", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "finally", ":", "if", "oldvalue", "is", "sentinel", ":", "del", "g", "[", "var_name", "]", "else", ":", "g", "[", "var_name", "]", "=", "oldvalue", "return", "res", "return", "inner_dec", "if", "_func", "is", "None", ":", "return", "decorator", "else", ":", "return", "decorator", "(", "_func", ")" ]
This allows a function to use Summernote configuration as a global variable, temporarily.
[ "This", "allows", "a", "function", "to", "use", "Summernote", "configuration", "as", "a", "global", "variable", "temporarily", "." ]
bc7fbbf065d88a909fe3e1533c84110e0dd132bc
https://github.com/summernote/django-summernote/blob/bc7fbbf065d88a909fe3e1533c84110e0dd132bc/django_summernote/utils.py#L117-L146
226,788
summernote/django-summernote
django_summernote/utils.py
uploaded_filepath
def uploaded_filepath(instance, filename): """ Returns default filepath for uploaded files. """ ext = filename.split('.')[-1] filename = "%s.%s" % (uuid.uuid4(), ext) today = datetime.now().strftime('%Y-%m-%d') return os.path.join('django-summernote', today, filename)
python
def uploaded_filepath(instance, filename): """ Returns default filepath for uploaded files. """ ext = filename.split('.')[-1] filename = "%s.%s" % (uuid.uuid4(), ext) today = datetime.now().strftime('%Y-%m-%d') return os.path.join('django-summernote', today, filename)
[ "def", "uploaded_filepath", "(", "instance", ",", "filename", ")", ":", "ext", "=", "filename", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "filename", "=", "\"%s.%s\"", "%", "(", "uuid", ".", "uuid4", "(", ")", ",", "ext", ")", "today", "=", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%Y-%m-%d'", ")", "return", "os", ".", "path", ".", "join", "(", "'django-summernote'", ",", "today", ",", "filename", ")" ]
Returns default filepath for uploaded files.
[ "Returns", "default", "filepath", "for", "uploaded", "files", "." ]
bc7fbbf065d88a909fe3e1533c84110e0dd132bc
https://github.com/summernote/django-summernote/blob/bc7fbbf065d88a909fe3e1533c84110e0dd132bc/django_summernote/utils.py#L149-L156
226,789
summernote/django-summernote
django_summernote/utils.py
get_attachment_model
def get_attachment_model(): """ Returns the Attachment model that is active in this project. """ try: from .models import AbstractAttachment klass = apps.get_model(config["attachment_model"]) if not issubclass(klass, AbstractAttachment): raise ImproperlyConfigured( "SUMMERNOTE_CONFIG['attachment_model'] refers to model '%s' that is not " "inherited from 'django_summernote.models.AbstractAttachment'" % config["attachment_model"] ) return klass except ValueError: raise ImproperlyConfigured("SUMMERNOTE_CONFIG['attachment_model'] must be of the form 'app_label.model_name'") except LookupError: raise ImproperlyConfigured( "SUMMERNOTE_CONFIG['attachment_model'] refers to model '%s' that has not been installed" % config["attachment_model"] )
python
def get_attachment_model(): """ Returns the Attachment model that is active in this project. """ try: from .models import AbstractAttachment klass = apps.get_model(config["attachment_model"]) if not issubclass(klass, AbstractAttachment): raise ImproperlyConfigured( "SUMMERNOTE_CONFIG['attachment_model'] refers to model '%s' that is not " "inherited from 'django_summernote.models.AbstractAttachment'" % config["attachment_model"] ) return klass except ValueError: raise ImproperlyConfigured("SUMMERNOTE_CONFIG['attachment_model'] must be of the form 'app_label.model_name'") except LookupError: raise ImproperlyConfigured( "SUMMERNOTE_CONFIG['attachment_model'] refers to model '%s' that has not been installed" % config["attachment_model"] )
[ "def", "get_attachment_model", "(", ")", ":", "try", ":", "from", ".", "models", "import", "AbstractAttachment", "klass", "=", "apps", ".", "get_model", "(", "config", "[", "\"attachment_model\"", "]", ")", "if", "not", "issubclass", "(", "klass", ",", "AbstractAttachment", ")", ":", "raise", "ImproperlyConfigured", "(", "\"SUMMERNOTE_CONFIG['attachment_model'] refers to model '%s' that is not \"", "\"inherited from 'django_summernote.models.AbstractAttachment'\"", "%", "config", "[", "\"attachment_model\"", "]", ")", "return", "klass", "except", "ValueError", ":", "raise", "ImproperlyConfigured", "(", "\"SUMMERNOTE_CONFIG['attachment_model'] must be of the form 'app_label.model_name'\"", ")", "except", "LookupError", ":", "raise", "ImproperlyConfigured", "(", "\"SUMMERNOTE_CONFIG['attachment_model'] refers to model '%s' that has not been installed\"", "%", "config", "[", "\"attachment_model\"", "]", ")" ]
Returns the Attachment model that is active in this project.
[ "Returns", "the", "Attachment", "model", "that", "is", "active", "in", "this", "project", "." ]
bc7fbbf065d88a909fe3e1533c84110e0dd132bc
https://github.com/summernote/django-summernote/blob/bc7fbbf065d88a909fe3e1533c84110e0dd132bc/django_summernote/utils.py#L180-L199
226,790
PyMySQL/mysqlclient-python
MySQLdb/connections.py
numeric_part
def numeric_part(s): """Returns the leading numeric part of a string. >>> numeric_part("20-alpha") 20 >>> numeric_part("foo") >>> numeric_part("16b") 16 """ m = re_numeric_part.match(s) if m: return int(m.group(1)) return None
python
def numeric_part(s): """Returns the leading numeric part of a string. >>> numeric_part("20-alpha") 20 >>> numeric_part("foo") >>> numeric_part("16b") 16 """ m = re_numeric_part.match(s) if m: return int(m.group(1)) return None
[ "def", "numeric_part", "(", "s", ")", ":", "m", "=", "re_numeric_part", ".", "match", "(", "s", ")", "if", "m", ":", "return", "int", "(", "m", ".", "group", "(", "1", ")", ")", "return", "None" ]
Returns the leading numeric part of a string. >>> numeric_part("20-alpha") 20 >>> numeric_part("foo") >>> numeric_part("16b") 16
[ "Returns", "the", "leading", "numeric", "part", "of", "a", "string", "." ]
b66971ee36be96b772ae7fdec79ccc1611376f3c
https://github.com/PyMySQL/mysqlclient-python/blob/b66971ee36be96b772ae7fdec79ccc1611376f3c/MySQLdb/connections.py#L21-L34
226,791
PyMySQL/mysqlclient-python
MySQLdb/connections.py
Connection.literal
def literal(self, o): """If o is a single object, returns an SQL literal as a string. If o is a non-string sequence, the items of the sequence are converted and returned as a sequence. Non-standard. For internal use; do not use this in your applications. """ if isinstance(o, unicode): s = self.string_literal(o.encode(self.encoding)) elif isinstance(o, bytearray): s = self._bytes_literal(o) elif isinstance(o, bytes): if PY2: s = self.string_literal(o) else: s = self._bytes_literal(o) elif isinstance(o, (tuple, list)): s = self._tuple_literal(o) else: s = self.escape(o, self.encoders) if isinstance(s, unicode): s = s.encode(self.encoding) assert isinstance(s, bytes) return s
python
def literal(self, o): """If o is a single object, returns an SQL literal as a string. If o is a non-string sequence, the items of the sequence are converted and returned as a sequence. Non-standard. For internal use; do not use this in your applications. """ if isinstance(o, unicode): s = self.string_literal(o.encode(self.encoding)) elif isinstance(o, bytearray): s = self._bytes_literal(o) elif isinstance(o, bytes): if PY2: s = self.string_literal(o) else: s = self._bytes_literal(o) elif isinstance(o, (tuple, list)): s = self._tuple_literal(o) else: s = self.escape(o, self.encoders) if isinstance(s, unicode): s = s.encode(self.encoding) assert isinstance(s, bytes) return s
[ "def", "literal", "(", "self", ",", "o", ")", ":", "if", "isinstance", "(", "o", ",", "unicode", ")", ":", "s", "=", "self", ".", "string_literal", "(", "o", ".", "encode", "(", "self", ".", "encoding", ")", ")", "elif", "isinstance", "(", "o", ",", "bytearray", ")", ":", "s", "=", "self", ".", "_bytes_literal", "(", "o", ")", "elif", "isinstance", "(", "o", ",", "bytes", ")", ":", "if", "PY2", ":", "s", "=", "self", ".", "string_literal", "(", "o", ")", "else", ":", "s", "=", "self", ".", "_bytes_literal", "(", "o", ")", "elif", "isinstance", "(", "o", ",", "(", "tuple", ",", "list", ")", ")", ":", "s", "=", "self", ".", "_tuple_literal", "(", "o", ")", "else", ":", "s", "=", "self", ".", "escape", "(", "o", ",", "self", ".", "encoders", ")", "if", "isinstance", "(", "s", ",", "unicode", ")", ":", "s", "=", "s", ".", "encode", "(", "self", ".", "encoding", ")", "assert", "isinstance", "(", "s", ",", "bytes", ")", "return", "s" ]
If o is a single object, returns an SQL literal as a string. If o is a non-string sequence, the items of the sequence are converted and returned as a sequence. Non-standard. For internal use; do not use this in your applications.
[ "If", "o", "is", "a", "single", "object", "returns", "an", "SQL", "literal", "as", "a", "string", ".", "If", "o", "is", "a", "non", "-", "string", "sequence", "the", "items", "of", "the", "sequence", "are", "converted", "and", "returned", "as", "a", "sequence", "." ]
b66971ee36be96b772ae7fdec79ccc1611376f3c
https://github.com/PyMySQL/mysqlclient-python/blob/b66971ee36be96b772ae7fdec79ccc1611376f3c/MySQLdb/connections.py#L238-L262
226,792
PyMySQL/mysqlclient-python
MySQLdb/connections.py
Connection.set_character_set
def set_character_set(self, charset): """Set the connection character set to charset. The character set can only be changed in MySQL-4.1 and newer. If you try to change the character set from the current value in an older version, NotSupportedError will be raised.""" if charset in ("utf8mb4", "utf8mb3"): py_charset = "utf8" else: py_charset = charset if self.character_set_name() != charset: try: super(Connection, self).set_character_set(charset) except AttributeError: if self._server_version < (4, 1): raise NotSupportedError("server is too old to set charset") self.query('SET NAMES %s' % charset) self.store_result() self.encoding = py_charset
python
def set_character_set(self, charset): """Set the connection character set to charset. The character set can only be changed in MySQL-4.1 and newer. If you try to change the character set from the current value in an older version, NotSupportedError will be raised.""" if charset in ("utf8mb4", "utf8mb3"): py_charset = "utf8" else: py_charset = charset if self.character_set_name() != charset: try: super(Connection, self).set_character_set(charset) except AttributeError: if self._server_version < (4, 1): raise NotSupportedError("server is too old to set charset") self.query('SET NAMES %s' % charset) self.store_result() self.encoding = py_charset
[ "def", "set_character_set", "(", "self", ",", "charset", ")", ":", "if", "charset", "in", "(", "\"utf8mb4\"", ",", "\"utf8mb3\"", ")", ":", "py_charset", "=", "\"utf8\"", "else", ":", "py_charset", "=", "charset", "if", "self", ".", "character_set_name", "(", ")", "!=", "charset", ":", "try", ":", "super", "(", "Connection", ",", "self", ")", ".", "set_character_set", "(", "charset", ")", "except", "AttributeError", ":", "if", "self", ".", "_server_version", "<", "(", "4", ",", "1", ")", ":", "raise", "NotSupportedError", "(", "\"server is too old to set charset\"", ")", "self", ".", "query", "(", "'SET NAMES %s'", "%", "charset", ")", "self", ".", "store_result", "(", ")", "self", ".", "encoding", "=", "py_charset" ]
Set the connection character set to charset. The character set can only be changed in MySQL-4.1 and newer. If you try to change the character set from the current value in an older version, NotSupportedError will be raised.
[ "Set", "the", "connection", "character", "set", "to", "charset", ".", "The", "character", "set", "can", "only", "be", "changed", "in", "MySQL", "-", "4", ".", "1", "and", "newer", ".", "If", "you", "try", "to", "change", "the", "character", "set", "from", "the", "current", "value", "in", "an", "older", "version", "NotSupportedError", "will", "be", "raised", "." ]
b66971ee36be96b772ae7fdec79ccc1611376f3c
https://github.com/PyMySQL/mysqlclient-python/blob/b66971ee36be96b772ae7fdec79ccc1611376f3c/MySQLdb/connections.py#L282-L299
226,793
PyMySQL/mysqlclient-python
MySQLdb/connections.py
Connection.set_sql_mode
def set_sql_mode(self, sql_mode): """Set the connection sql_mode. See MySQL documentation for legal values.""" if self._server_version < (4, 1): raise NotSupportedError("server is too old to set sql_mode") self.query("SET SESSION sql_mode='%s'" % sql_mode) self.store_result()
python
def set_sql_mode(self, sql_mode): """Set the connection sql_mode. See MySQL documentation for legal values.""" if self._server_version < (4, 1): raise NotSupportedError("server is too old to set sql_mode") self.query("SET SESSION sql_mode='%s'" % sql_mode) self.store_result()
[ "def", "set_sql_mode", "(", "self", ",", "sql_mode", ")", ":", "if", "self", ".", "_server_version", "<", "(", "4", ",", "1", ")", ":", "raise", "NotSupportedError", "(", "\"server is too old to set sql_mode\"", ")", "self", ".", "query", "(", "\"SET SESSION sql_mode='%s'\"", "%", "sql_mode", ")", "self", ".", "store_result", "(", ")" ]
Set the connection sql_mode. See MySQL documentation for legal values.
[ "Set", "the", "connection", "sql_mode", ".", "See", "MySQL", "documentation", "for", "legal", "values", "." ]
b66971ee36be96b772ae7fdec79ccc1611376f3c
https://github.com/PyMySQL/mysqlclient-python/blob/b66971ee36be96b772ae7fdec79ccc1611376f3c/MySQLdb/connections.py#L301-L307
226,794
PyMySQL/mysqlclient-python
MySQLdb/cursors.py
BaseCursor.close
def close(self): """Close the cursor. No further queries will be possible.""" try: if self.connection is None: return while self.nextset(): pass finally: self.connection = None self._result = None
python
def close(self): """Close the cursor. No further queries will be possible.""" try: if self.connection is None: return while self.nextset(): pass finally: self.connection = None self._result = None
[ "def", "close", "(", "self", ")", ":", "try", ":", "if", "self", ".", "connection", "is", "None", ":", "return", "while", "self", ".", "nextset", "(", ")", ":", "pass", "finally", ":", "self", ".", "connection", "=", "None", "self", ".", "_result", "=", "None" ]
Close the cursor. No further queries will be possible.
[ "Close", "the", "cursor", ".", "No", "further", "queries", "will", "be", "possible", "." ]
b66971ee36be96b772ae7fdec79ccc1611376f3c
https://github.com/PyMySQL/mysqlclient-python/blob/b66971ee36be96b772ae7fdec79ccc1611376f3c/MySQLdb/cursors.py#L81-L90
226,795
MagicStack/asyncpg
asyncpg/cursor.py
Cursor.fetchrow
async def fetchrow(self, *, timeout=None): r"""Return the next row. :param float timeout: Optional timeout value in seconds. :return: A :class:`Record` instance. """ self._check_ready() if self._exhausted: return None recs = await self._exec(1, timeout) if len(recs) < 1: self._exhausted = True return None return recs[0]
python
async def fetchrow(self, *, timeout=None): r"""Return the next row. :param float timeout: Optional timeout value in seconds. :return: A :class:`Record` instance. """ self._check_ready() if self._exhausted: return None recs = await self._exec(1, timeout) if len(recs) < 1: self._exhausted = True return None return recs[0]
[ "async", "def", "fetchrow", "(", "self", ",", "*", ",", "timeout", "=", "None", ")", ":", "self", ".", "_check_ready", "(", ")", "if", "self", ".", "_exhausted", ":", "return", "None", "recs", "=", "await", "self", ".", "_exec", "(", "1", ",", "timeout", ")", "if", "len", "(", "recs", ")", "<", "1", ":", "self", ".", "_exhausted", "=", "True", "return", "None", "return", "recs", "[", "0", "]" ]
r"""Return the next row. :param float timeout: Optional timeout value in seconds. :return: A :class:`Record` instance.
[ "r", "Return", "the", "next", "row", "." ]
92c2d81256a1efd8cab12c0118d74ccd1c18131b
https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/cursor.py#L224-L238
226,796
MagicStack/asyncpg
asyncpg/connresource.py
guarded
def guarded(meth): """A decorator to add a sanity check to ConnectionResource methods.""" @functools.wraps(meth) def _check(self, *args, **kwargs): self._check_conn_validity(meth.__name__) return meth(self, *args, **kwargs) return _check
python
def guarded(meth): """A decorator to add a sanity check to ConnectionResource methods.""" @functools.wraps(meth) def _check(self, *args, **kwargs): self._check_conn_validity(meth.__name__) return meth(self, *args, **kwargs) return _check
[ "def", "guarded", "(", "meth", ")", ":", "@", "functools", ".", "wraps", "(", "meth", ")", "def", "_check", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_conn_validity", "(", "meth", ".", "__name__", ")", "return", "meth", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "_check" ]
A decorator to add a sanity check to ConnectionResource methods.
[ "A", "decorator", "to", "add", "a", "sanity", "check", "to", "ConnectionResource", "methods", "." ]
92c2d81256a1efd8cab12c0118d74ccd1c18131b
https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/connresource.py#L14-L22
226,797
MagicStack/asyncpg
asyncpg/cluster.py
Cluster.start
def start(self, wait=60, *, server_settings={}, **opts): """Start the cluster.""" status = self.get_status() if status == 'running': return elif status == 'not-initialized': raise ClusterError( 'cluster in {!r} has not been initialized'.format( self._data_dir)) port = opts.pop('port', None) if port == 'dynamic': port = find_available_port() extra_args = ['--{}={}'.format(k, v) for k, v in opts.items()] extra_args.append('--port={}'.format(port)) sockdir = server_settings.get('unix_socket_directories') if sockdir is None: sockdir = server_settings.get('unix_socket_directory') if sockdir is None: sockdir = '/tmp' ssl_key = server_settings.get('ssl_key_file') if ssl_key: # Make sure server certificate key file has correct permissions. keyfile = os.path.join(self._data_dir, 'srvkey.pem') shutil.copy(ssl_key, keyfile) os.chmod(keyfile, 0o600) server_settings = server_settings.copy() server_settings['ssl_key_file'] = keyfile if self._pg_version < (9, 3): sockdir_opt = 'unix_socket_directory' else: sockdir_opt = 'unix_socket_directories' server_settings[sockdir_opt] = sockdir for k, v in server_settings.items(): extra_args.extend(['-c', '{}={}'.format(k, v)]) if _system == 'Windows': # On Windows we have to use pg_ctl as direct execution # of postgres daemon under an Administrative account # is not permitted and there is no easy way to drop # privileges. if os.getenv('ASYNCPG_DEBUG_SERVER'): stdout = sys.stdout else: stdout = subprocess.DEVNULL process = subprocess.run( [self._pg_ctl, 'start', '-D', self._data_dir, '-o', ' '.join(extra_args)], stdout=stdout, stderr=subprocess.STDOUT) if process.returncode != 0: if process.stderr: stderr = ':\n{}'.format(process.stderr.decode()) else: stderr = '' raise ClusterError( 'pg_ctl start exited with status {:d}{}'.format( process.returncode, stderr)) else: if os.getenv('ASYNCPG_DEBUG_SERVER'): stdout = sys.stdout else: stdout = subprocess.DEVNULL self._daemon_process = \ subprocess.Popen( [self._postgres, '-D', self._data_dir, *extra_args], stdout=stdout, stderr=subprocess.STDOUT) self._daemon_pid = self._daemon_process.pid self._test_connection(timeout=wait)
python
def start(self, wait=60, *, server_settings={}, **opts): """Start the cluster.""" status = self.get_status() if status == 'running': return elif status == 'not-initialized': raise ClusterError( 'cluster in {!r} has not been initialized'.format( self._data_dir)) port = opts.pop('port', None) if port == 'dynamic': port = find_available_port() extra_args = ['--{}={}'.format(k, v) for k, v in opts.items()] extra_args.append('--port={}'.format(port)) sockdir = server_settings.get('unix_socket_directories') if sockdir is None: sockdir = server_settings.get('unix_socket_directory') if sockdir is None: sockdir = '/tmp' ssl_key = server_settings.get('ssl_key_file') if ssl_key: # Make sure server certificate key file has correct permissions. keyfile = os.path.join(self._data_dir, 'srvkey.pem') shutil.copy(ssl_key, keyfile) os.chmod(keyfile, 0o600) server_settings = server_settings.copy() server_settings['ssl_key_file'] = keyfile if self._pg_version < (9, 3): sockdir_opt = 'unix_socket_directory' else: sockdir_opt = 'unix_socket_directories' server_settings[sockdir_opt] = sockdir for k, v in server_settings.items(): extra_args.extend(['-c', '{}={}'.format(k, v)]) if _system == 'Windows': # On Windows we have to use pg_ctl as direct execution # of postgres daemon under an Administrative account # is not permitted and there is no easy way to drop # privileges. if os.getenv('ASYNCPG_DEBUG_SERVER'): stdout = sys.stdout else: stdout = subprocess.DEVNULL process = subprocess.run( [self._pg_ctl, 'start', '-D', self._data_dir, '-o', ' '.join(extra_args)], stdout=stdout, stderr=subprocess.STDOUT) if process.returncode != 0: if process.stderr: stderr = ':\n{}'.format(process.stderr.decode()) else: stderr = '' raise ClusterError( 'pg_ctl start exited with status {:d}{}'.format( process.returncode, stderr)) else: if os.getenv('ASYNCPG_DEBUG_SERVER'): stdout = sys.stdout else: stdout = subprocess.DEVNULL self._daemon_process = \ subprocess.Popen( [self._postgres, '-D', self._data_dir, *extra_args], stdout=stdout, stderr=subprocess.STDOUT) self._daemon_pid = self._daemon_process.pid self._test_connection(timeout=wait)
[ "def", "start", "(", "self", ",", "wait", "=", "60", ",", "*", ",", "server_settings", "=", "{", "}", ",", "*", "*", "opts", ")", ":", "status", "=", "self", ".", "get_status", "(", ")", "if", "status", "==", "'running'", ":", "return", "elif", "status", "==", "'not-initialized'", ":", "raise", "ClusterError", "(", "'cluster in {!r} has not been initialized'", ".", "format", "(", "self", ".", "_data_dir", ")", ")", "port", "=", "opts", ".", "pop", "(", "'port'", ",", "None", ")", "if", "port", "==", "'dynamic'", ":", "port", "=", "find_available_port", "(", ")", "extra_args", "=", "[", "'--{}={}'", ".", "format", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "opts", ".", "items", "(", ")", "]", "extra_args", ".", "append", "(", "'--port={}'", ".", "format", "(", "port", ")", ")", "sockdir", "=", "server_settings", ".", "get", "(", "'unix_socket_directories'", ")", "if", "sockdir", "is", "None", ":", "sockdir", "=", "server_settings", ".", "get", "(", "'unix_socket_directory'", ")", "if", "sockdir", "is", "None", ":", "sockdir", "=", "'/tmp'", "ssl_key", "=", "server_settings", ".", "get", "(", "'ssl_key_file'", ")", "if", "ssl_key", ":", "# Make sure server certificate key file has correct permissions.", "keyfile", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_data_dir", ",", "'srvkey.pem'", ")", "shutil", ".", "copy", "(", "ssl_key", ",", "keyfile", ")", "os", ".", "chmod", "(", "keyfile", ",", "0o600", ")", "server_settings", "=", "server_settings", ".", "copy", "(", ")", "server_settings", "[", "'ssl_key_file'", "]", "=", "keyfile", "if", "self", ".", "_pg_version", "<", "(", "9", ",", "3", ")", ":", "sockdir_opt", "=", "'unix_socket_directory'", "else", ":", "sockdir_opt", "=", "'unix_socket_directories'", "server_settings", "[", "sockdir_opt", "]", "=", "sockdir", "for", "k", ",", "v", "in", "server_settings", ".", "items", "(", ")", ":", "extra_args", ".", "extend", "(", "[", "'-c'", ",", "'{}={}'", ".", "format", "(", "k", ",", "v", ")", "]", ")", "if", "_system", "==", "'Windows'", ":", "# On Windows we have to use pg_ctl as direct execution", "# of postgres daemon under an Administrative account", "# is not permitted and there is no easy way to drop", "# privileges.", "if", "os", ".", "getenv", "(", "'ASYNCPG_DEBUG_SERVER'", ")", ":", "stdout", "=", "sys", ".", "stdout", "else", ":", "stdout", "=", "subprocess", ".", "DEVNULL", "process", "=", "subprocess", ".", "run", "(", "[", "self", ".", "_pg_ctl", ",", "'start'", ",", "'-D'", ",", "self", ".", "_data_dir", ",", "'-o'", ",", "' '", ".", "join", "(", "extra_args", ")", "]", ",", "stdout", "=", "stdout", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "if", "process", ".", "returncode", "!=", "0", ":", "if", "process", ".", "stderr", ":", "stderr", "=", "':\\n{}'", ".", "format", "(", "process", ".", "stderr", ".", "decode", "(", ")", ")", "else", ":", "stderr", "=", "''", "raise", "ClusterError", "(", "'pg_ctl start exited with status {:d}{}'", ".", "format", "(", "process", ".", "returncode", ",", "stderr", ")", ")", "else", ":", "if", "os", ".", "getenv", "(", "'ASYNCPG_DEBUG_SERVER'", ")", ":", "stdout", "=", "sys", ".", "stdout", "else", ":", "stdout", "=", "subprocess", ".", "DEVNULL", "self", ".", "_daemon_process", "=", "subprocess", ".", "Popen", "(", "[", "self", ".", "_postgres", ",", "'-D'", ",", "self", ".", "_data_dir", ",", "*", "extra_args", "]", ",", "stdout", "=", "stdout", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "self", ".", "_daemon_pid", "=", "self", ".", "_daemon_process", ".", "pid", "self", ".", "_test_connection", "(", "timeout", "=", "wait", ")" ]
Start the cluster.
[ "Start", "the", "cluster", "." ]
92c2d81256a1efd8cab12c0118d74ccd1c18131b
https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/cluster.py#L144-L222
226,798
MagicStack/asyncpg
asyncpg/cluster.py
Cluster.reload
def reload(self): """Reload server configuration.""" status = self.get_status() if status != 'running': raise ClusterError('cannot reload: cluster is not running') process = subprocess.run( [self._pg_ctl, 'reload', '-D', self._data_dir], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stderr = process.stderr if process.returncode != 0: raise ClusterError( 'pg_ctl stop exited with status {:d}: {}'.format( process.returncode, stderr.decode()))
python
def reload(self): """Reload server configuration.""" status = self.get_status() if status != 'running': raise ClusterError('cannot reload: cluster is not running') process = subprocess.run( [self._pg_ctl, 'reload', '-D', self._data_dir], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stderr = process.stderr if process.returncode != 0: raise ClusterError( 'pg_ctl stop exited with status {:d}: {}'.format( process.returncode, stderr.decode()))
[ "def", "reload", "(", "self", ")", ":", "status", "=", "self", ".", "get_status", "(", ")", "if", "status", "!=", "'running'", ":", "raise", "ClusterError", "(", "'cannot reload: cluster is not running'", ")", "process", "=", "subprocess", ".", "run", "(", "[", "self", ".", "_pg_ctl", ",", "'reload'", ",", "'-D'", ",", "self", ".", "_data_dir", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "stderr", "=", "process", ".", "stderr", "if", "process", ".", "returncode", "!=", "0", ":", "raise", "ClusterError", "(", "'pg_ctl stop exited with status {:d}: {}'", ".", "format", "(", "process", ".", "returncode", ",", "stderr", ".", "decode", "(", ")", ")", ")" ]
Reload server configuration.
[ "Reload", "server", "configuration", "." ]
92c2d81256a1efd8cab12c0118d74ccd1c18131b
https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/cluster.py#L224-L239
226,799
MagicStack/asyncpg
asyncpg/cluster.py
Cluster.reset_hba
def reset_hba(self): """Remove all records from pg_hba.conf.""" status = self.get_status() if status == 'not-initialized': raise ClusterError( 'cannot modify HBA records: cluster is not initialized') pg_hba = os.path.join(self._data_dir, 'pg_hba.conf') try: with open(pg_hba, 'w'): pass except IOError as e: raise ClusterError( 'cannot modify HBA records: {}'.format(e)) from e
python
def reset_hba(self): """Remove all records from pg_hba.conf.""" status = self.get_status() if status == 'not-initialized': raise ClusterError( 'cannot modify HBA records: cluster is not initialized') pg_hba = os.path.join(self._data_dir, 'pg_hba.conf') try: with open(pg_hba, 'w'): pass except IOError as e: raise ClusterError( 'cannot modify HBA records: {}'.format(e)) from e
[ "def", "reset_hba", "(", "self", ")", ":", "status", "=", "self", ".", "get_status", "(", ")", "if", "status", "==", "'not-initialized'", ":", "raise", "ClusterError", "(", "'cannot modify HBA records: cluster is not initialized'", ")", "pg_hba", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_data_dir", ",", "'pg_hba.conf'", ")", "try", ":", "with", "open", "(", "pg_hba", ",", "'w'", ")", ":", "pass", "except", "IOError", "as", "e", ":", "raise", "ClusterError", "(", "'cannot modify HBA records: {}'", ".", "format", "(", "e", ")", ")", "from", "e" ]
Remove all records from pg_hba.conf.
[ "Remove", "all", "records", "from", "pg_hba", ".", "conf", "." ]
92c2d81256a1efd8cab12c0118d74ccd1c18131b
https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/cluster.py#L323-L337