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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM._control_vm
def _control_vm(self, command, expected=None): """ Executes a command with QEMU monitor when this VM is running. :param command: QEMU monitor command (e.g. info status, stop etc.) :param expected: An array of expected strings :returns: result of the command (matched object or None) """ result = None if self.is_running() and self._monitor: log.debug("Execute QEMU monitor command: {}".format(command)) try: log.info("Connecting to Qemu monitor on {}:{}".format(self._monitor_host, self._monitor)) reader, writer = yield from asyncio.open_connection(self._monitor_host, self._monitor) except OSError as e: log.warn("Could not connect to QEMU monitor: {}".format(e)) return result try: writer.write(command.encode('ascii') + b"\n") except OSError as e: log.warn("Could not write to QEMU monitor: {}".format(e)) writer.close() return result if expected: try: while result is None: line = yield from reader.readline() if not line: break for expect in expected: if expect in line: result = line.decode("utf-8").strip() break except EOFError as e: log.warn("Could not read from QEMU monitor: {}".format(e)) writer.close() return result
python
def _control_vm(self, command, expected=None): """ Executes a command with QEMU monitor when this VM is running. :param command: QEMU monitor command (e.g. info status, stop etc.) :param expected: An array of expected strings :returns: result of the command (matched object or None) """ result = None if self.is_running() and self._monitor: log.debug("Execute QEMU monitor command: {}".format(command)) try: log.info("Connecting to Qemu monitor on {}:{}".format(self._monitor_host, self._monitor)) reader, writer = yield from asyncio.open_connection(self._monitor_host, self._monitor) except OSError as e: log.warn("Could not connect to QEMU monitor: {}".format(e)) return result try: writer.write(command.encode('ascii') + b"\n") except OSError as e: log.warn("Could not write to QEMU monitor: {}".format(e)) writer.close() return result if expected: try: while result is None: line = yield from reader.readline() if not line: break for expect in expected: if expect in line: result = line.decode("utf-8").strip() break except EOFError as e: log.warn("Could not read from QEMU monitor: {}".format(e)) writer.close() return result
[ "def", "_control_vm", "(", "self", ",", "command", ",", "expected", "=", "None", ")", ":", "result", "=", "None", "if", "self", ".", "is_running", "(", ")", "and", "self", ".", "_monitor", ":", "log", ".", "debug", "(", "\"Execute QEMU monitor command: {}\...
Executes a command with QEMU monitor when this VM is running. :param command: QEMU monitor command (e.g. info status, stop etc.) :param expected: An array of expected strings :returns: result of the command (matched object or None)
[ "Executes", "a", "command", "with", "QEMU", "monitor", "when", "this", "VM", "is", "running", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L995-L1033
train
221,300
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.close
def close(self): """ Closes this QEMU VM. """ if not (yield from super().close()): return False self.acpi_shutdown = False yield from self.stop() for adapter in self._ethernet_adapters: if adapter is not None: for nio in adapter.ports.values(): if nio and isinstance(nio, NIOUDP): self.manager.port_manager.release_udp_port(nio.lport, self._project) for udp_tunnel in self._local_udp_tunnels.values(): self.manager.port_manager.release_udp_port(udp_tunnel[0].lport, self._project) self.manager.port_manager.release_udp_port(udp_tunnel[1].lport, self._project) self._local_udp_tunnels = {}
python
def close(self): """ Closes this QEMU VM. """ if not (yield from super().close()): return False self.acpi_shutdown = False yield from self.stop() for adapter in self._ethernet_adapters: if adapter is not None: for nio in adapter.ports.values(): if nio and isinstance(nio, NIOUDP): self.manager.port_manager.release_udp_port(nio.lport, self._project) for udp_tunnel in self._local_udp_tunnels.values(): self.manager.port_manager.release_udp_port(udp_tunnel[0].lport, self._project) self.manager.port_manager.release_udp_port(udp_tunnel[1].lport, self._project) self._local_udp_tunnels = {}
[ "def", "close", "(", "self", ")", ":", "if", "not", "(", "yield", "from", "super", "(", ")", ".", "close", "(", ")", ")", ":", "return", "False", "self", ".", "acpi_shutdown", "=", "False", "yield", "from", "self", ".", "stop", "(", ")", "for", "...
Closes this QEMU VM.
[ "Closes", "this", "QEMU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L1036-L1056
train
221,301
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM._get_vm_status
def _get_vm_status(self): """ Returns this VM suspend status. Status are extracted from: https://github.com/qemu/qemu/blob/master/qapi-schema.json#L152 :returns: status (string) """ result = yield from self._control_vm("info status", [ b"debug", b"inmigrate", b"internal-error", b"io-error", b"paused", b"postmigrate", b"prelaunch", b"finish-migrate", b"restore-vm", b"running", b"save-vm", b"shutdown", b"suspended", b"watchdog", b"guest-panicked" ]) if result is None: return result status = result.rsplit(' ', 1)[1] if status == "running" or status == "prelaunch": self.status = "started" elif status == "suspended": self.status = "suspended" elif status == "shutdown": self.status = "stopped" return status
python
def _get_vm_status(self): """ Returns this VM suspend status. Status are extracted from: https://github.com/qemu/qemu/blob/master/qapi-schema.json#L152 :returns: status (string) """ result = yield from self._control_vm("info status", [ b"debug", b"inmigrate", b"internal-error", b"io-error", b"paused", b"postmigrate", b"prelaunch", b"finish-migrate", b"restore-vm", b"running", b"save-vm", b"shutdown", b"suspended", b"watchdog", b"guest-panicked" ]) if result is None: return result status = result.rsplit(' ', 1)[1] if status == "running" or status == "prelaunch": self.status = "started" elif status == "suspended": self.status = "suspended" elif status == "shutdown": self.status = "stopped" return status
[ "def", "_get_vm_status", "(", "self", ")", ":", "result", "=", "yield", "from", "self", ".", "_control_vm", "(", "\"info status\"", ",", "[", "b\"debug\"", ",", "b\"inmigrate\"", ",", "b\"internal-error\"", ",", "b\"io-error\"", ",", "b\"paused\"", ",", "b\"post...
Returns this VM suspend status. Status are extracted from: https://github.com/qemu/qemu/blob/master/qapi-schema.json#L152 :returns: status (string)
[ "Returns", "this", "VM", "suspend", "status", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L1059-L1084
train
221,302
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.suspend
def suspend(self): """ Suspends this QEMU VM. """ if self.is_running(): vm_status = yield from self._get_vm_status() if vm_status is None: raise QemuError("Suspending a QEMU VM is not supported") elif vm_status == "running" or vm_status == "prelaunch": yield from self._control_vm("stop") self.status = "suspended" log.debug("QEMU VM has been suspended") else: log.info("QEMU VM is not running to be suspended, current status is {}".format(vm_status))
python
def suspend(self): """ Suspends this QEMU VM. """ if self.is_running(): vm_status = yield from self._get_vm_status() if vm_status is None: raise QemuError("Suspending a QEMU VM is not supported") elif vm_status == "running" or vm_status == "prelaunch": yield from self._control_vm("stop") self.status = "suspended" log.debug("QEMU VM has been suspended") else: log.info("QEMU VM is not running to be suspended, current status is {}".format(vm_status))
[ "def", "suspend", "(", "self", ")", ":", "if", "self", ".", "is_running", "(", ")", ":", "vm_status", "=", "yield", "from", "self", ".", "_get_vm_status", "(", ")", "if", "vm_status", "is", "None", ":", "raise", "QemuError", "(", "\"Suspending a QEMU VM is...
Suspends this QEMU VM.
[ "Suspends", "this", "QEMU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L1087-L1101
train
221,303
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.resume
def resume(self): """ Resumes this QEMU VM. """ vm_status = yield from self._get_vm_status() if vm_status is None: raise QemuError("Resuming a QEMU VM is not supported") elif vm_status == "paused": yield from self._control_vm("cont") log.debug("QEMU VM has been resumed") else: log.info("QEMU VM is not paused to be resumed, current status is {}".format(vm_status))
python
def resume(self): """ Resumes this QEMU VM. """ vm_status = yield from self._get_vm_status() if vm_status is None: raise QemuError("Resuming a QEMU VM is not supported") elif vm_status == "paused": yield from self._control_vm("cont") log.debug("QEMU VM has been resumed") else: log.info("QEMU VM is not paused to be resumed, current status is {}".format(vm_status))
[ "def", "resume", "(", "self", ")", ":", "vm_status", "=", "yield", "from", "self", ".", "_get_vm_status", "(", ")", "if", "vm_status", "is", "None", ":", "raise", "QemuError", "(", "\"Resuming a QEMU VM is not supported\"", ")", "elif", "vm_status", "==", "\"p...
Resumes this QEMU VM.
[ "Resumes", "this", "QEMU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L1113-L1125
train
221,304
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.read_stdout
def read_stdout(self): """ Reads the standard output of the QEMU process. Only use when the process has been stopped or has crashed. """ output = "" if self._stdout_file: try: with open(self._stdout_file, "rb") as file: output = file.read().decode("utf-8", errors="replace") except OSError as e: log.warning("Could not read {}: {}".format(self._stdout_file, e)) return output
python
def read_stdout(self): """ Reads the standard output of the QEMU process. Only use when the process has been stopped or has crashed. """ output = "" if self._stdout_file: try: with open(self._stdout_file, "rb") as file: output = file.read().decode("utf-8", errors="replace") except OSError as e: log.warning("Could not read {}: {}".format(self._stdout_file, e)) return output
[ "def", "read_stdout", "(", "self", ")", ":", "output", "=", "\"\"", "if", "self", ".", "_stdout_file", ":", "try", ":", "with", "open", "(", "self", ".", "_stdout_file", ",", "\"rb\"", ")", "as", "file", ":", "output", "=", "file", ".", "read", "(", ...
Reads the standard output of the QEMU process. Only use when the process has been stopped or has crashed.
[ "Reads", "the", "standard", "output", "of", "the", "QEMU", "process", ".", "Only", "use", "when", "the", "process", "has", "been", "stopped", "or", "has", "crashed", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L1275-L1288
train
221,305
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.read_qemu_img_stdout
def read_qemu_img_stdout(self): """ Reads the standard output of the QEMU-IMG process. """ output = "" if self._qemu_img_stdout_file: try: with open(self._qemu_img_stdout_file, "rb") as file: output = file.read().decode("utf-8", errors="replace") except OSError as e: log.warning("Could not read {}: {}".format(self._qemu_img_stdout_file, e)) return output
python
def read_qemu_img_stdout(self): """ Reads the standard output of the QEMU-IMG process. """ output = "" if self._qemu_img_stdout_file: try: with open(self._qemu_img_stdout_file, "rb") as file: output = file.read().decode("utf-8", errors="replace") except OSError as e: log.warning("Could not read {}: {}".format(self._qemu_img_stdout_file, e)) return output
[ "def", "read_qemu_img_stdout", "(", "self", ")", ":", "output", "=", "\"\"", "if", "self", ".", "_qemu_img_stdout_file", ":", "try", ":", "with", "open", "(", "self", ".", "_qemu_img_stdout_file", ",", "\"rb\"", ")", "as", "file", ":", "output", "=", "file...
Reads the standard output of the QEMU-IMG process.
[ "Reads", "the", "standard", "output", "of", "the", "QEMU", "-", "IMG", "process", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L1290-L1302
train
221,306
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.is_running
def is_running(self): """ Checks if the QEMU process is running :returns: True or False """ if self._process: if self._process.returncode is None: return True else: self._process = None return False
python
def is_running(self): """ Checks if the QEMU process is running :returns: True or False """ if self._process: if self._process.returncode is None: return True else: self._process = None return False
[ "def", "is_running", "(", "self", ")", ":", "if", "self", ".", "_process", ":", "if", "self", ".", "_process", ".", "returncode", "is", "None", ":", "return", "True", "else", ":", "self", ".", "_process", "=", "None", "return", "False" ]
Checks if the QEMU process is running :returns: True or False
[ "Checks", "if", "the", "QEMU", "process", "is", "running" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L1304-L1316
train
221,307
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM._get_qemu_img
def _get_qemu_img(self): """ Search the qemu-img binary in the same binary of the qemu binary for avoiding version incompatibily. :returns: qemu-img path or raise an error """ qemu_img_path = "" qemu_path_dir = os.path.dirname(self.qemu_path) try: for f in os.listdir(qemu_path_dir): if f.startswith("qemu-img"): qemu_img_path = os.path.join(qemu_path_dir, f) except OSError as e: raise QemuError("Error while looking for qemu-img in {}: {}".format(qemu_path_dir, e)) if not qemu_img_path: raise QemuError("Could not find qemu-img in {}".format(qemu_path_dir)) return qemu_img_path
python
def _get_qemu_img(self): """ Search the qemu-img binary in the same binary of the qemu binary for avoiding version incompatibily. :returns: qemu-img path or raise an error """ qemu_img_path = "" qemu_path_dir = os.path.dirname(self.qemu_path) try: for f in os.listdir(qemu_path_dir): if f.startswith("qemu-img"): qemu_img_path = os.path.join(qemu_path_dir, f) except OSError as e: raise QemuError("Error while looking for qemu-img in {}: {}".format(qemu_path_dir, e)) if not qemu_img_path: raise QemuError("Could not find qemu-img in {}".format(qemu_path_dir)) return qemu_img_path
[ "def", "_get_qemu_img", "(", "self", ")", ":", "qemu_img_path", "=", "\"\"", "qemu_path_dir", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "qemu_path", ")", "try", ":", "for", "f", "in", "os", ".", "listdir", "(", "qemu_path_dir", ")", ":"...
Search the qemu-img binary in the same binary of the qemu binary for avoiding version incompatibily. :returns: qemu-img path or raise an error
[ "Search", "the", "qemu", "-", "img", "binary", "in", "the", "same", "binary", "of", "the", "qemu", "binary", "for", "avoiding", "version", "incompatibily", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L1364-L1383
train
221,308
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM._graphic
def _graphic(self): """ Adds the correct graphic options depending of the OS """ if sys.platform.startswith("win"): return [] if len(os.environ.get("DISPLAY", "")) > 0: return [] if "-nographic" not in self._options: return ["-nographic"] return []
python
def _graphic(self): """ Adds the correct graphic options depending of the OS """ if sys.platform.startswith("win"): return [] if len(os.environ.get("DISPLAY", "")) > 0: return [] if "-nographic" not in self._options: return ["-nographic"] return []
[ "def", "_graphic", "(", "self", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", ":", "return", "[", "]", "if", "len", "(", "os", ".", "environ", ".", "get", "(", "\"DISPLAY\"", ",", "\"\"", ")", ")", ">", "0", ":",...
Adds the correct graphic options depending of the OS
[ "Adds", "the", "correct", "graphic", "options", "depending", "of", "the", "OS" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L1603-L1614
train
221,309
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM._run_with_kvm
def _run_with_kvm(self, qemu_path, options): """ Check if we could run qemu with KVM :param qemu_path: Path to qemu :param options: String of qemu user options :returns: Boolean True if we need to enable KVM """ if sys.platform.startswith("linux") and self.manager.config.get_section_config("Qemu").getboolean("enable_kvm", True) \ and "-no-kvm" not in options: # Turn OFF kvm for non x86 architectures if os.path.basename(qemu_path) not in ["qemu-system-x86_64", "qemu-system-i386", "qemu-kvm"]: return False if not os.path.exists("/dev/kvm"): if self.manager.config.get_section_config("Qemu").getboolean("require_kvm", True): raise QemuError("KVM acceleration cannot be used (/dev/kvm doesn't exist). You can turn off KVM support in the gns3_server.conf by adding enable_kvm = false to the [Qemu] section.") else: return False return True return False
python
def _run_with_kvm(self, qemu_path, options): """ Check if we could run qemu with KVM :param qemu_path: Path to qemu :param options: String of qemu user options :returns: Boolean True if we need to enable KVM """ if sys.platform.startswith("linux") and self.manager.config.get_section_config("Qemu").getboolean("enable_kvm", True) \ and "-no-kvm" not in options: # Turn OFF kvm for non x86 architectures if os.path.basename(qemu_path) not in ["qemu-system-x86_64", "qemu-system-i386", "qemu-kvm"]: return False if not os.path.exists("/dev/kvm"): if self.manager.config.get_section_config("Qemu").getboolean("require_kvm", True): raise QemuError("KVM acceleration cannot be used (/dev/kvm doesn't exist). You can turn off KVM support in the gns3_server.conf by adding enable_kvm = false to the [Qemu] section.") else: return False return True return False
[ "def", "_run_with_kvm", "(", "self", ",", "qemu_path", ",", "options", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "\"linux\"", ")", "and", "self", ".", "manager", ".", "config", ".", "get_section_config", "(", "\"Qemu\"", ")", ".", "...
Check if we could run qemu with KVM :param qemu_path: Path to qemu :param options: String of qemu user options :returns: Boolean True if we need to enable KVM
[ "Check", "if", "we", "could", "run", "qemu", "with", "KVM" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L1616-L1638
train
221,310
GNS3/gns3-server
gns3server/controller/gns3vm/__init__.py
GNS3VM.update_settings
def update_settings(self, settings): """ Update settings and will restart the VM if require """ new_settings = copy.copy(self._settings) new_settings.update(settings) if self.settings != new_settings: yield from self._stop() self._settings = settings self._controller.save() if self.enable: yield from self.start() else: # When user fix something on his system and try again if self.enable and not self.current_engine().running: yield from self.start()
python
def update_settings(self, settings): """ Update settings and will restart the VM if require """ new_settings = copy.copy(self._settings) new_settings.update(settings) if self.settings != new_settings: yield from self._stop() self._settings = settings self._controller.save() if self.enable: yield from self.start() else: # When user fix something on his system and try again if self.enable and not self.current_engine().running: yield from self.start()
[ "def", "update_settings", "(", "self", ",", "settings", ")", ":", "new_settings", "=", "copy", ".", "copy", "(", "self", ".", "_settings", ")", "new_settings", ".", "update", "(", "settings", ")", "if", "self", ".", "settings", "!=", "new_settings", ":", ...
Update settings and will restart the VM if require
[ "Update", "settings", "and", "will", "restart", "the", "VM", "if", "require" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/__init__.py#L183-L198
train
221,311
GNS3/gns3-server
gns3server/controller/gns3vm/__init__.py
GNS3VM._get_engine
def _get_engine(self, engine): """ Load an engine """ if engine in self._engines: return self._engines[engine] if engine == "vmware": self._engines["vmware"] = VMwareGNS3VM(self._controller) return self._engines["vmware"] elif engine == "virtualbox": self._engines["virtualbox"] = VirtualBoxGNS3VM(self._controller) return self._engines["virtualbox"] elif engine == "remote": self._engines["remote"] = RemoteGNS3VM(self._controller) return self._engines["remote"] raise NotImplementedError("The engine {} for the GNS3 VM is not supported".format(engine))
python
def _get_engine(self, engine): """ Load an engine """ if engine in self._engines: return self._engines[engine] if engine == "vmware": self._engines["vmware"] = VMwareGNS3VM(self._controller) return self._engines["vmware"] elif engine == "virtualbox": self._engines["virtualbox"] = VirtualBoxGNS3VM(self._controller) return self._engines["virtualbox"] elif engine == "remote": self._engines["remote"] = RemoteGNS3VM(self._controller) return self._engines["remote"] raise NotImplementedError("The engine {} for the GNS3 VM is not supported".format(engine))
[ "def", "_get_engine", "(", "self", ",", "engine", ")", ":", "if", "engine", "in", "self", ".", "_engines", ":", "return", "self", ".", "_engines", "[", "engine", "]", "if", "engine", "==", "\"vmware\"", ":", "self", ".", "_engines", "[", "\"vmware\"", ...
Load an engine
[ "Load", "an", "engine" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/__init__.py#L200-L216
train
221,312
GNS3/gns3-server
gns3server/controller/gns3vm/__init__.py
GNS3VM.list
def list(self, engine): """ List VMS for an engine """ engine = self._get_engine(engine) vms = [] try: for vm in (yield from engine.list()): vms.append({"vmname": vm["vmname"]}) except GNS3VMError as e: # We raise error only if user activated the GNS3 VM # otherwise you have noise when VMware is not installed if self.enable: raise e return vms
python
def list(self, engine): """ List VMS for an engine """ engine = self._get_engine(engine) vms = [] try: for vm in (yield from engine.list()): vms.append({"vmname": vm["vmname"]}) except GNS3VMError as e: # We raise error only if user activated the GNS3 VM # otherwise you have noise when VMware is not installed if self.enable: raise e return vms
[ "def", "list", "(", "self", ",", "engine", ")", ":", "engine", "=", "self", ".", "_get_engine", "(", "engine", ")", "vms", "=", "[", "]", "try", ":", "for", "vm", "in", "(", "yield", "from", "engine", ".", "list", "(", ")", ")", ":", "vms", "."...
List VMS for an engine
[ "List", "VMS", "for", "an", "engine" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/__init__.py#L222-L236
train
221,313
GNS3/gns3-server
gns3server/controller/gns3vm/__init__.py
GNS3VM.auto_start_vm
def auto_start_vm(self): """ Auto start the GNS3 VM if require """ if self.enable: try: yield from self.start() except GNS3VMError as e: # User will receive the error later when they will try to use the node try: yield from self._controller.add_compute(compute_id="vm", name="GNS3 VM ({})".format(self.current_engine().vmname), host=None, force=True) except aiohttp.web.HTTPConflict: pass log.error("Can't start the GNS3 VM: %s", str(e))
python
def auto_start_vm(self): """ Auto start the GNS3 VM if require """ if self.enable: try: yield from self.start() except GNS3VMError as e: # User will receive the error later when they will try to use the node try: yield from self._controller.add_compute(compute_id="vm", name="GNS3 VM ({})".format(self.current_engine().vmname), host=None, force=True) except aiohttp.web.HTTPConflict: pass log.error("Can't start the GNS3 VM: %s", str(e))
[ "def", "auto_start_vm", "(", "self", ")", ":", "if", "self", ".", "enable", ":", "try", ":", "yield", "from", "self", ".", "start", "(", ")", "except", "GNS3VMError", "as", "e", ":", "# User will receive the error later when they will try to use the node", "try", ...
Auto start the GNS3 VM if require
[ "Auto", "start", "the", "GNS3", "VM", "if", "require" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/__init__.py#L239-L255
train
221,314
GNS3/gns3-server
gns3server/controller/gns3vm/__init__.py
GNS3VM.start
def start(self): """ Start the GNS3 VM """ engine = self.current_engine() if not engine.running: if self._settings["vmname"] is None: return log.info("Start the GNS3 VM") engine.vmname = self._settings["vmname"] engine.ram = self._settings["ram"] engine.vcpus = self._settings["vcpus"] engine.headless = self._settings["headless"] compute = yield from self._controller.add_compute(compute_id="vm", name="GNS3 VM is starting ({})".format(engine.vmname), host=None, force=True, connect=False) try: yield from engine.start() except Exception as e: yield from self._controller.delete_compute("vm") log.error("Can't start the GNS3 VM: {}".format(str(e))) yield from compute.update(name="GNS3 VM ({})".format(engine.vmname)) raise e yield from compute.connect() # we can connect now that the VM has started yield from compute.update(name="GNS3 VM ({})".format(engine.vmname), protocol=self.protocol, host=self.ip_address, port=self.port, user=self.user, password=self.password) # check if the VM is in the same subnet as the local server, start 10 seconds later to give # some time for the compute in the VM to be ready for requests asyncio.get_event_loop().call_later(10, lambda: asyncio.async(self._check_network(compute)))
python
def start(self): """ Start the GNS3 VM """ engine = self.current_engine() if not engine.running: if self._settings["vmname"] is None: return log.info("Start the GNS3 VM") engine.vmname = self._settings["vmname"] engine.ram = self._settings["ram"] engine.vcpus = self._settings["vcpus"] engine.headless = self._settings["headless"] compute = yield from self._controller.add_compute(compute_id="vm", name="GNS3 VM is starting ({})".format(engine.vmname), host=None, force=True, connect=False) try: yield from engine.start() except Exception as e: yield from self._controller.delete_compute("vm") log.error("Can't start the GNS3 VM: {}".format(str(e))) yield from compute.update(name="GNS3 VM ({})".format(engine.vmname)) raise e yield from compute.connect() # we can connect now that the VM has started yield from compute.update(name="GNS3 VM ({})".format(engine.vmname), protocol=self.protocol, host=self.ip_address, port=self.port, user=self.user, password=self.password) # check if the VM is in the same subnet as the local server, start 10 seconds later to give # some time for the compute in the VM to be ready for requests asyncio.get_event_loop().call_later(10, lambda: asyncio.async(self._check_network(compute)))
[ "def", "start", "(", "self", ")", ":", "engine", "=", "self", ".", "current_engine", "(", ")", "if", "not", "engine", ".", "running", ":", "if", "self", ".", "_settings", "[", "\"vmname\"", "]", "is", "None", ":", "return", "log", ".", "info", "(", ...
Start the GNS3 VM
[ "Start", "the", "GNS3", "VM" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/__init__.py#L269-L305
train
221,315
GNS3/gns3-server
gns3server/controller/gns3vm/__init__.py
GNS3VM._check_network
def _check_network(self, compute): """ Check that the VM is in the same subnet as the local server """ try: vm_interfaces = yield from compute.interfaces() vm_interface_netmask = None for interface in vm_interfaces: if interface["ip_address"] == self.ip_address: vm_interface_netmask = interface["netmask"] break if vm_interface_netmask: vm_network = ipaddress.ip_interface("{}/{}".format(compute.host_ip, vm_interface_netmask)).network for compute_id in self._controller.computes: if compute_id == "local": compute = self._controller.get_compute(compute_id) interfaces = yield from compute.interfaces() netmask = None for interface in interfaces: if interface["ip_address"] == compute.host_ip: netmask = interface["netmask"] break if netmask: compute_network = ipaddress.ip_interface("{}/{}".format(compute.host_ip, netmask)).network if vm_network.compare_networks(compute_network) != 0: msg = "The GNS3 VM ({}) is not on the same network as the {} server ({}), please make sure the local server binding is in the same network as the GNS3 VM".format( vm_network, compute_id, compute_network) self._controller.notification.emit("log.warning", {"message": msg}) except ComputeError as e: log.warning("Could not check the VM is in the same subnet as the local server: {}".format(e))
python
def _check_network(self, compute): """ Check that the VM is in the same subnet as the local server """ try: vm_interfaces = yield from compute.interfaces() vm_interface_netmask = None for interface in vm_interfaces: if interface["ip_address"] == self.ip_address: vm_interface_netmask = interface["netmask"] break if vm_interface_netmask: vm_network = ipaddress.ip_interface("{}/{}".format(compute.host_ip, vm_interface_netmask)).network for compute_id in self._controller.computes: if compute_id == "local": compute = self._controller.get_compute(compute_id) interfaces = yield from compute.interfaces() netmask = None for interface in interfaces: if interface["ip_address"] == compute.host_ip: netmask = interface["netmask"] break if netmask: compute_network = ipaddress.ip_interface("{}/{}".format(compute.host_ip, netmask)).network if vm_network.compare_networks(compute_network) != 0: msg = "The GNS3 VM ({}) is not on the same network as the {} server ({}), please make sure the local server binding is in the same network as the GNS3 VM".format( vm_network, compute_id, compute_network) self._controller.notification.emit("log.warning", {"message": msg}) except ComputeError as e: log.warning("Could not check the VM is in the same subnet as the local server: {}".format(e))
[ "def", "_check_network", "(", "self", ",", "compute", ")", ":", "try", ":", "vm_interfaces", "=", "yield", "from", "compute", ".", "interfaces", "(", ")", "vm_interface_netmask", "=", "None", "for", "interface", "in", "vm_interfaces", ":", "if", "interface", ...
Check that the VM is in the same subnet as the local server
[ "Check", "that", "the", "VM", "is", "in", "the", "same", "subnet", "as", "the", "local", "server" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/__init__.py#L308-L338
train
221,316
GNS3/gns3-server
gns3server/controller/gns3vm/__init__.py
GNS3VM._suspend
def _suspend(self): """ Suspend the GNS3 VM """ engine = self.current_engine() if "vm" in self._controller.computes: yield from self._controller.delete_compute("vm") if engine.running: log.info("Suspend the GNS3 VM") yield from engine.suspend()
python
def _suspend(self): """ Suspend the GNS3 VM """ engine = self.current_engine() if "vm" in self._controller.computes: yield from self._controller.delete_compute("vm") if engine.running: log.info("Suspend the GNS3 VM") yield from engine.suspend()
[ "def", "_suspend", "(", "self", ")", ":", "engine", "=", "self", ".", "current_engine", "(", ")", "if", "\"vm\"", "in", "self", ".", "_controller", ".", "computes", ":", "yield", "from", "self", ".", "_controller", ".", "delete_compute", "(", "\"vm\"", "...
Suspend the GNS3 VM
[ "Suspend", "the", "GNS3", "VM" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/__init__.py#L341-L350
train
221,317
GNS3/gns3-server
gns3server/controller/gns3vm/__init__.py
GNS3VM._stop
def _stop(self): """ Stop the GNS3 VM """ engine = self.current_engine() if "vm" in self._controller.computes: yield from self._controller.delete_compute("vm") if engine.running: log.info("Stop the GNS3 VM") yield from engine.stop()
python
def _stop(self): """ Stop the GNS3 VM """ engine = self.current_engine() if "vm" in self._controller.computes: yield from self._controller.delete_compute("vm") if engine.running: log.info("Stop the GNS3 VM") yield from engine.stop()
[ "def", "_stop", "(", "self", ")", ":", "engine", "=", "self", ".", "current_engine", "(", ")", "if", "\"vm\"", "in", "self", ".", "_controller", ".", "computes", ":", "yield", "from", "self", ".", "_controller", ".", "delete_compute", "(", "\"vm\"", ")",...
Stop the GNS3 VM
[ "Stop", "the", "GNS3", "VM" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/__init__.py#L353-L362
train
221,318
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router._convert_before_2_0_0_b3
def _convert_before_2_0_0_b3(self, dynamips_id): """ Before 2.0.0 beta3 the node didn't have a folder by node when we start we move the file, we can't do it in the topology conversion due to case of remote servers """ dynamips_dir = self.project.module_working_directory(self.manager.module_name.lower()) for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "configs", "i{}_*".format(dynamips_id))): dst = os.path.join(self._working_directory, "configs", os.path.basename(path)) if not os.path.exists(dst): try: shutil.move(path, dst) except OSError as e: raise DynamipsError("Can't move {}: {}".format(path, str(e))) for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "*_i{}_*".format(dynamips_id))): dst = os.path.join(self._working_directory, os.path.basename(path)) if not os.path.exists(dst): try: shutil.move(path, dst) except OSError as e: raise DynamipsError("Can't move {}: {}".format(path, str(e)))
python
def _convert_before_2_0_0_b3(self, dynamips_id): """ Before 2.0.0 beta3 the node didn't have a folder by node when we start we move the file, we can't do it in the topology conversion due to case of remote servers """ dynamips_dir = self.project.module_working_directory(self.manager.module_name.lower()) for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "configs", "i{}_*".format(dynamips_id))): dst = os.path.join(self._working_directory, "configs", os.path.basename(path)) if not os.path.exists(dst): try: shutil.move(path, dst) except OSError as e: raise DynamipsError("Can't move {}: {}".format(path, str(e))) for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "*_i{}_*".format(dynamips_id))): dst = os.path.join(self._working_directory, os.path.basename(path)) if not os.path.exists(dst): try: shutil.move(path, dst) except OSError as e: raise DynamipsError("Can't move {}: {}".format(path, str(e)))
[ "def", "_convert_before_2_0_0_b3", "(", "self", ",", "dynamips_id", ")", ":", "dynamips_dir", "=", "self", ".", "project", ".", "module_working_directory", "(", "self", ".", "manager", ".", "module_name", ".", "lower", "(", ")", ")", "for", "path", "in", "gl...
Before 2.0.0 beta3 the node didn't have a folder by node when we start we move the file, we can't do it in the topology conversion due to case of remote servers
[ "Before", "2", ".", "0", ".", "0", "beta3", "the", "node", "didn", "t", "have", "a", "folder", "by", "node", "when", "we", "start", "we", "move", "the", "file", "we", "can", "t", "do", "it", "in", "the", "topology", "conversion", "due", "to", "case...
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L121-L141
train
221,319
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.get_status
def get_status(self): """ Returns the status of this router :returns: inactive, shutting down, running or suspended. """ status = yield from self._hypervisor.send('vm get_status "{name}"'.format(name=self._name)) if len(status) == 0: raise DynamipsError("Can't get vm {name} status".format(name=self._name)) return self._status[int(status[0])]
python
def get_status(self): """ Returns the status of this router :returns: inactive, shutting down, running or suspended. """ status = yield from self._hypervisor.send('vm get_status "{name}"'.format(name=self._name)) if len(status) == 0: raise DynamipsError("Can't get vm {name} status".format(name=self._name)) return self._status[int(status[0])]
[ "def", "get_status", "(", "self", ")", ":", "status", "=", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'vm get_status \"{name}\"'", ".", "format", "(", "name", "=", "self", ".", "_name", ")", ")", "if", "len", "(", "status", ")", "=...
Returns the status of this router :returns: inactive, shutting down, running or suspended.
[ "Returns", "the", "status", "of", "this", "router" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L241-L251
train
221,320
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.start
def start(self): """ Starts this router. At least the IOS image must be set before it can start. """ status = yield from self.get_status() if status == "suspended": yield from self.resume() elif status == "inactive": if not os.path.isfile(self._image) or not os.path.exists(self._image): if os.path.islink(self._image): raise DynamipsError('IOS image "{}" linked to "{}" is not accessible'.format(self._image, os.path.realpath(self._image))) else: raise DynamipsError('IOS image "{}" is not accessible'.format(self._image)) try: with open(self._image, "rb") as f: # read the first 7 bytes of the file. elf_header_start = f.read(7) except OSError as e: raise DynamipsError('Cannot read ELF header for IOS image "{}": {}'.format(self._image, e)) # IOS images must start with the ELF magic number, be 32-bit, big endian and have an ELF version of 1 if elf_header_start != b'\x7fELF\x01\x02\x01': raise DynamipsError('"{}" is not a valid IOS image'.format(self._image)) # check if there is enough RAM to run if not self._ghost_flag: self.check_available_ram(self.ram) # config paths are relative to the working directory configured on Dynamips hypervisor startup_config_path = os.path.join("configs", "i{}_startup-config.cfg".format(self._dynamips_id)) private_config_path = os.path.join("configs", "i{}_private-config.cfg".format(self._dynamips_id)) if not os.path.exists(os.path.join(self._working_directory, private_config_path)) or \ not os.path.getsize(os.path.join(self._working_directory, private_config_path)): # an empty private-config can prevent a router to boot. private_config_path = '' yield from self._hypervisor.send('vm set_config "{name}" "{startup}" "{private}"'.format( name=self._name, startup=startup_config_path, private=private_config_path)) yield from self._hypervisor.send('vm start "{name}"'.format(name=self._name)) self.status = "started" log.info('router "{name}" [{id}] has been started'.format(name=self._name, id=self._id)) self._memory_watcher = FileWatcher(self._memory_files(), self._memory_changed, strategy='hash', delay=30) monitor_process(self._hypervisor.process, self._termination_callback)
python
def start(self): """ Starts this router. At least the IOS image must be set before it can start. """ status = yield from self.get_status() if status == "suspended": yield from self.resume() elif status == "inactive": if not os.path.isfile(self._image) or not os.path.exists(self._image): if os.path.islink(self._image): raise DynamipsError('IOS image "{}" linked to "{}" is not accessible'.format(self._image, os.path.realpath(self._image))) else: raise DynamipsError('IOS image "{}" is not accessible'.format(self._image)) try: with open(self._image, "rb") as f: # read the first 7 bytes of the file. elf_header_start = f.read(7) except OSError as e: raise DynamipsError('Cannot read ELF header for IOS image "{}": {}'.format(self._image, e)) # IOS images must start with the ELF magic number, be 32-bit, big endian and have an ELF version of 1 if elf_header_start != b'\x7fELF\x01\x02\x01': raise DynamipsError('"{}" is not a valid IOS image'.format(self._image)) # check if there is enough RAM to run if not self._ghost_flag: self.check_available_ram(self.ram) # config paths are relative to the working directory configured on Dynamips hypervisor startup_config_path = os.path.join("configs", "i{}_startup-config.cfg".format(self._dynamips_id)) private_config_path = os.path.join("configs", "i{}_private-config.cfg".format(self._dynamips_id)) if not os.path.exists(os.path.join(self._working_directory, private_config_path)) or \ not os.path.getsize(os.path.join(self._working_directory, private_config_path)): # an empty private-config can prevent a router to boot. private_config_path = '' yield from self._hypervisor.send('vm set_config "{name}" "{startup}" "{private}"'.format( name=self._name, startup=startup_config_path, private=private_config_path)) yield from self._hypervisor.send('vm start "{name}"'.format(name=self._name)) self.status = "started" log.info('router "{name}" [{id}] has been started'.format(name=self._name, id=self._id)) self._memory_watcher = FileWatcher(self._memory_files(), self._memory_changed, strategy='hash', delay=30) monitor_process(self._hypervisor.process, self._termination_callback)
[ "def", "start", "(", "self", ")", ":", "status", "=", "yield", "from", "self", ".", "get_status", "(", ")", "if", "status", "==", "\"suspended\"", ":", "yield", "from", "self", ".", "resume", "(", ")", "elif", "status", "==", "\"inactive\"", ":", "if",...
Starts this router. At least the IOS image must be set before it can start.
[ "Starts", "this", "router", ".", "At", "least", "the", "IOS", "image", "must", "be", "set", "before", "it", "can", "start", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L254-L304
train
221,321
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.stop
def stop(self): """ Stops this router. """ status = yield from self.get_status() if status != "inactive": try: yield from self._hypervisor.send('vm stop "{name}"'.format(name=self._name)) except DynamipsError as e: log.warn("Could not stop {}: {}".format(self._name, e)) self.status = "stopped" log.info('Router "{name}" [{id}] has been stopped'.format(name=self._name, id=self._id)) if self._memory_watcher: self._memory_watcher.close() self._memory_watcher = None yield from self.save_configs()
python
def stop(self): """ Stops this router. """ status = yield from self.get_status() if status != "inactive": try: yield from self._hypervisor.send('vm stop "{name}"'.format(name=self._name)) except DynamipsError as e: log.warn("Could not stop {}: {}".format(self._name, e)) self.status = "stopped" log.info('Router "{name}" [{id}] has been stopped'.format(name=self._name, id=self._id)) if self._memory_watcher: self._memory_watcher.close() self._memory_watcher = None yield from self.save_configs()
[ "def", "stop", "(", "self", ")", ":", "status", "=", "yield", "from", "self", ".", "get_status", "(", ")", "if", "status", "!=", "\"inactive\"", ":", "try", ":", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'vm stop \"{name}\"'", ".", ...
Stops this router.
[ "Stops", "this", "router", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L321-L337
train
221,322
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.suspend
def suspend(self): """ Suspends this router. """ status = yield from self.get_status() if status == "running": yield from self._hypervisor.send('vm suspend "{name}"'.format(name=self._name)) self.status = "suspended" log.info('Router "{name}" [{id}] has been suspended'.format(name=self._name, id=self._id))
python
def suspend(self): """ Suspends this router. """ status = yield from self.get_status() if status == "running": yield from self._hypervisor.send('vm suspend "{name}"'.format(name=self._name)) self.status = "suspended" log.info('Router "{name}" [{id}] has been suspended'.format(name=self._name, id=self._id))
[ "def", "suspend", "(", "self", ")", ":", "status", "=", "yield", "from", "self", ".", "get_status", "(", ")", "if", "status", "==", "\"running\"", ":", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'vm suspend \"{name}\"'", ".", "format",...
Suspends this router.
[ "Suspends", "this", "router", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L349-L358
train
221,323
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.set_image
def set_image(self, image): """ Sets the IOS image for this router. There is no default. :param image: path to IOS image file """ image = self.manager.get_abs_image_path(image) yield from self._hypervisor.send('vm set_ios "{name}" "{image}"'.format(name=self._name, image=image)) log.info('Router "{name}" [{id}]: has a new IOS image set: "{image}"'.format(name=self._name, id=self._id, image=image)) self._image = image
python
def set_image(self, image): """ Sets the IOS image for this router. There is no default. :param image: path to IOS image file """ image = self.manager.get_abs_image_path(image) yield from self._hypervisor.send('vm set_ios "{name}" "{image}"'.format(name=self._name, image=image)) log.info('Router "{name}" [{id}]: has a new IOS image set: "{image}"'.format(name=self._name, id=self._id, image=image)) self._image = image
[ "def", "set_image", "(", "self", ",", "image", ")", ":", "image", "=", "self", ".", "manager", ".", "get_abs_image_path", "(", "image", ")", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'vm set_ios \"{name}\" \"{image}\"'", ".", "format", ...
Sets the IOS image for this router. There is no default. :param image: path to IOS image file
[ "Sets", "the", "IOS", "image", "for", "this", "router", ".", "There", "is", "no", "default", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L491-L507
train
221,324
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.set_ram
def set_ram(self, ram): """ Sets amount of RAM allocated to this router :param ram: amount of RAM in Mbytes (integer) """ if self._ram == ram: return yield from self._hypervisor.send('vm set_ram "{name}" {ram}'.format(name=self._name, ram=ram)) log.info('Router "{name}" [{id}]: RAM updated from {old_ram}MB to {new_ram}MB'.format(name=self._name, id=self._id, old_ram=self._ram, new_ram=ram)) self._ram = ram
python
def set_ram(self, ram): """ Sets amount of RAM allocated to this router :param ram: amount of RAM in Mbytes (integer) """ if self._ram == ram: return yield from self._hypervisor.send('vm set_ram "{name}" {ram}'.format(name=self._name, ram=ram)) log.info('Router "{name}" [{id}]: RAM updated from {old_ram}MB to {new_ram}MB'.format(name=self._name, id=self._id, old_ram=self._ram, new_ram=ram)) self._ram = ram
[ "def", "set_ram", "(", "self", ",", "ram", ")", ":", "if", "self", ".", "_ram", "==", "ram", ":", "return", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'vm set_ram \"{name}\" {ram}'", ".", "format", "(", "name", "=", "self", ".", "_...
Sets amount of RAM allocated to this router :param ram: amount of RAM in Mbytes (integer)
[ "Sets", "amount", "of", "RAM", "allocated", "to", "this", "router" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L520-L535
train
221,325
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.set_nvram
def set_nvram(self, nvram): """ Sets amount of NVRAM allocated to this router :param nvram: amount of NVRAM in Kbytes (integer) """ if self._nvram == nvram: return yield from self._hypervisor.send('vm set_nvram "{name}" {nvram}'.format(name=self._name, nvram=nvram)) log.info('Router "{name}" [{id}]: NVRAM updated from {old_nvram}KB to {new_nvram}KB'.format(name=self._name, id=self._id, old_nvram=self._nvram, new_nvram=nvram)) self._nvram = nvram
python
def set_nvram(self, nvram): """ Sets amount of NVRAM allocated to this router :param nvram: amount of NVRAM in Kbytes (integer) """ if self._nvram == nvram: return yield from self._hypervisor.send('vm set_nvram "{name}" {nvram}'.format(name=self._name, nvram=nvram)) log.info('Router "{name}" [{id}]: NVRAM updated from {old_nvram}KB to {new_nvram}KB'.format(name=self._name, id=self._id, old_nvram=self._nvram, new_nvram=nvram)) self._nvram = nvram
[ "def", "set_nvram", "(", "self", ",", "nvram", ")", ":", "if", "self", ".", "_nvram", "==", "nvram", ":", "return", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'vm set_nvram \"{name}\" {nvram}'", ".", "format", "(", "name", "=", "self",...
Sets amount of NVRAM allocated to this router :param nvram: amount of NVRAM in Kbytes (integer)
[ "Sets", "amount", "of", "NVRAM", "allocated", "to", "this", "router" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L548-L563
train
221,326
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.set_clock_divisor
def set_clock_divisor(self, clock_divisor): """ Sets the clock divisor value. The higher is the value, the faster is the clock in the virtual machine. The default is 4, but it is often required to adjust it. :param clock_divisor: clock divisor value (integer) """ yield from self._hypervisor.send('vm set_clock_divisor "{name}" {clock}'.format(name=self._name, clock=clock_divisor)) log.info('Router "{name}" [{id}]: clock divisor updated from {old_clock} to {new_clock}'.format(name=self._name, id=self._id, old_clock=self._clock_divisor, new_clock=clock_divisor)) self._clock_divisor = clock_divisor
python
def set_clock_divisor(self, clock_divisor): """ Sets the clock divisor value. The higher is the value, the faster is the clock in the virtual machine. The default is 4, but it is often required to adjust it. :param clock_divisor: clock divisor value (integer) """ yield from self._hypervisor.send('vm set_clock_divisor "{name}" {clock}'.format(name=self._name, clock=clock_divisor)) log.info('Router "{name}" [{id}]: clock divisor updated from {old_clock} to {new_clock}'.format(name=self._name, id=self._id, old_clock=self._clock_divisor, new_clock=clock_divisor)) self._clock_divisor = clock_divisor
[ "def", "set_clock_divisor", "(", "self", ",", "clock_divisor", ")", ":", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'vm set_clock_divisor \"{name}\" {clock}'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "clock", "=", "cloc...
Sets the clock divisor value. The higher is the value, the faster is the clock in the virtual machine. The default is 4, but it is often required to adjust it. :param clock_divisor: clock divisor value (integer)
[ "Sets", "the", "clock", "divisor", "value", ".", "The", "higher", "is", "the", "value", "the", "faster", "is", "the", "clock", "in", "the", "virtual", "machine", ".", "The", "default", "is", "4", "but", "it", "is", "often", "required", "to", "adjust", ...
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L638-L651
train
221,327
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.get_idle_pc_prop
def get_idle_pc_prop(self): """ Gets the idle PC proposals. Takes 1000 measurements and records up to 10 idle PC proposals. There is a 10ms wait between each measurement. :returns: list of idle PC proposal """ is_running = yield from self.is_running() was_auto_started = False if not is_running: yield from self.start() was_auto_started = True yield from asyncio.sleep(20) # leave time to the router to boot log.info('Router "{name}" [{id}] has started calculating Idle-PC values'.format(name=self._name, id=self._id)) begin = time.time() idlepcs = yield from self._hypervisor.send('vm get_idle_pc_prop "{}" 0'.format(self._name)) log.info('Router "{name}" [{id}] has finished calculating Idle-PC values after {time:.4f} seconds'.format(name=self._name, id=self._id, time=time.time() - begin)) if was_auto_started: yield from self.stop() return idlepcs
python
def get_idle_pc_prop(self): """ Gets the idle PC proposals. Takes 1000 measurements and records up to 10 idle PC proposals. There is a 10ms wait between each measurement. :returns: list of idle PC proposal """ is_running = yield from self.is_running() was_auto_started = False if not is_running: yield from self.start() was_auto_started = True yield from asyncio.sleep(20) # leave time to the router to boot log.info('Router "{name}" [{id}] has started calculating Idle-PC values'.format(name=self._name, id=self._id)) begin = time.time() idlepcs = yield from self._hypervisor.send('vm get_idle_pc_prop "{}" 0'.format(self._name)) log.info('Router "{name}" [{id}] has finished calculating Idle-PC values after {time:.4f} seconds'.format(name=self._name, id=self._id, time=time.time() - begin)) if was_auto_started: yield from self.stop() return idlepcs
[ "def", "get_idle_pc_prop", "(", "self", ")", ":", "is_running", "=", "yield", "from", "self", ".", "is_running", "(", ")", "was_auto_started", "=", "False", "if", "not", "is_running", ":", "yield", "from", "self", ".", "start", "(", ")", "was_auto_started", ...
Gets the idle PC proposals. Takes 1000 measurements and records up to 10 idle PC proposals. There is a 10ms wait between each measurement. :returns: list of idle PC proposal
[ "Gets", "the", "idle", "PC", "proposals", ".", "Takes", "1000", "measurements", "and", "records", "up", "to", "10", "idle", "PC", "proposals", ".", "There", "is", "a", "10ms", "wait", "between", "each", "measurement", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L685-L709
train
221,328
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.set_idlemax
def set_idlemax(self, idlemax): """ Sets CPU idle max value :param idlemax: idle max value (integer) """ is_running = yield from self.is_running() if is_running: # router is running yield from self._hypervisor.send('vm set_idle_max "{name}" 0 {idlemax}'.format(name=self._name, idlemax=idlemax)) log.info('Router "{name}" [{id}]: idlemax updated from {old_idlemax} to {new_idlemax}'.format(name=self._name, id=self._id, old_idlemax=self._idlemax, new_idlemax=idlemax)) self._idlemax = idlemax
python
def set_idlemax(self, idlemax): """ Sets CPU idle max value :param idlemax: idle max value (integer) """ is_running = yield from self.is_running() if is_running: # router is running yield from self._hypervisor.send('vm set_idle_max "{name}" 0 {idlemax}'.format(name=self._name, idlemax=idlemax)) log.info('Router "{name}" [{id}]: idlemax updated from {old_idlemax} to {new_idlemax}'.format(name=self._name, id=self._id, old_idlemax=self._idlemax, new_idlemax=idlemax)) self._idlemax = idlemax
[ "def", "set_idlemax", "(", "self", ",", "idlemax", ")", ":", "is_running", "=", "yield", "from", "self", ".", "is_running", "(", ")", "if", "is_running", ":", "# router is running", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'vm set_idle...
Sets CPU idle max value :param idlemax: idle max value (integer)
[ "Sets", "CPU", "idle", "max", "value" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L738-L754
train
221,329
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.set_idlesleep
def set_idlesleep(self, idlesleep): """ Sets CPU idle sleep time value. :param idlesleep: idle sleep value (integer) """ is_running = yield from self.is_running() if is_running: # router is running yield from self._hypervisor.send('vm set_idle_sleep_time "{name}" 0 {idlesleep}'.format(name=self._name, idlesleep=idlesleep)) log.info('Router "{name}" [{id}]: idlesleep updated from {old_idlesleep} to {new_idlesleep}'.format(name=self._name, id=self._id, old_idlesleep=self._idlesleep, new_idlesleep=idlesleep)) self._idlesleep = idlesleep
python
def set_idlesleep(self, idlesleep): """ Sets CPU idle sleep time value. :param idlesleep: idle sleep value (integer) """ is_running = yield from self.is_running() if is_running: # router is running yield from self._hypervisor.send('vm set_idle_sleep_time "{name}" 0 {idlesleep}'.format(name=self._name, idlesleep=idlesleep)) log.info('Router "{name}" [{id}]: idlesleep updated from {old_idlesleep} to {new_idlesleep}'.format(name=self._name, id=self._id, old_idlesleep=self._idlesleep, new_idlesleep=idlesleep)) self._idlesleep = idlesleep
[ "def", "set_idlesleep", "(", "self", ",", "idlesleep", ")", ":", "is_running", "=", "yield", "from", "self", ".", "is_running", "(", ")", "if", "is_running", ":", "# router is running", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'vm set_...
Sets CPU idle sleep time value. :param idlesleep: idle sleep value (integer)
[ "Sets", "CPU", "idle", "sleep", "time", "value", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L767-L784
train
221,330
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.set_ghost_file
def set_ghost_file(self, ghost_file): """ Sets ghost RAM file :ghost_file: path to ghost file """ yield from self._hypervisor.send('vm set_ghost_file "{name}" {ghost_file}'.format(name=self._name, ghost_file=shlex.quote(ghost_file))) log.info('Router "{name}" [{id}]: ghost file set to {ghost_file}'.format(name=self._name, id=self._id, ghost_file=ghost_file)) self._ghost_file = ghost_file
python
def set_ghost_file(self, ghost_file): """ Sets ghost RAM file :ghost_file: path to ghost file """ yield from self._hypervisor.send('vm set_ghost_file "{name}" {ghost_file}'.format(name=self._name, ghost_file=shlex.quote(ghost_file))) log.info('Router "{name}" [{id}]: ghost file set to {ghost_file}'.format(name=self._name, id=self._id, ghost_file=ghost_file)) self._ghost_file = ghost_file
[ "def", "set_ghost_file", "(", "self", ",", "ghost_file", ")", ":", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'vm set_ghost_file \"{name}\" {ghost_file}'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "ghost_file", "=", "shl...
Sets ghost RAM file :ghost_file: path to ghost file
[ "Sets", "ghost", "RAM", "file" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L797-L811
train
221,331
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.formatted_ghost_file
def formatted_ghost_file(self): """ Returns a properly formatted ghost file name. :returns: formatted ghost_file name (string) """ # replace specials characters in 'drive:\filename' in Linux and Dynamips in MS Windows or viceversa. ghost_file = "{}-{}.ghost".format(os.path.basename(self._image), self._ram) ghost_file = ghost_file.replace('\\', '-').replace('/', '-').replace(':', '-') return ghost_file
python
def formatted_ghost_file(self): """ Returns a properly formatted ghost file name. :returns: formatted ghost_file name (string) """ # replace specials characters in 'drive:\filename' in Linux and Dynamips in MS Windows or viceversa. ghost_file = "{}-{}.ghost".format(os.path.basename(self._image), self._ram) ghost_file = ghost_file.replace('\\', '-').replace('/', '-').replace(':', '-') return ghost_file
[ "def", "formatted_ghost_file", "(", "self", ")", ":", "# replace specials characters in 'drive:\\filename' in Linux and Dynamips in MS Windows or viceversa.", "ghost_file", "=", "\"{}-{}.ghost\"", ".", "format", "(", "os", ".", "path", ".", "basename", "(", "self", ".", "_i...
Returns a properly formatted ghost file name. :returns: formatted ghost_file name (string)
[ "Returns", "a", "properly", "formatted", "ghost", "file", "name", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L813-L823
train
221,332
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.set_ghost_status
def set_ghost_status(self, ghost_status): """ Sets ghost RAM status :param ghost_status: state flag indicating status 0 => Do not use IOS ghosting 1 => This is a ghost instance 2 => Use an existing ghost instance """ yield from self._hypervisor.send('vm set_ghost_status "{name}" {ghost_status}'.format(name=self._name, ghost_status=ghost_status)) log.info('Router "{name}" [{id}]: ghost status set to {ghost_status}'.format(name=self._name, id=self._id, ghost_status=ghost_status)) self._ghost_status = ghost_status
python
def set_ghost_status(self, ghost_status): """ Sets ghost RAM status :param ghost_status: state flag indicating status 0 => Do not use IOS ghosting 1 => This is a ghost instance 2 => Use an existing ghost instance """ yield from self._hypervisor.send('vm set_ghost_status "{name}" {ghost_status}'.format(name=self._name, ghost_status=ghost_status)) log.info('Router "{name}" [{id}]: ghost status set to {ghost_status}'.format(name=self._name, id=self._id, ghost_status=ghost_status)) self._ghost_status = ghost_status
[ "def", "set_ghost_status", "(", "self", ",", "ghost_status", ")", ":", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'vm set_ghost_status \"{name}\" {ghost_status}'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "ghost_status", "...
Sets ghost RAM status :param ghost_status: state flag indicating status 0 => Do not use IOS ghosting 1 => This is a ghost instance 2 => Use an existing ghost instance
[ "Sets", "ghost", "RAM", "status" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L835-L851
train
221,333
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.set_console
def set_console(self, console): """ Sets the TCP console port. :param console: console port (integer) """ self.console = console yield from self._hypervisor.send('vm set_con_tcp_port "{name}" {console}'.format(name=self._name, console=self.console))
python
def set_console(self, console): """ Sets the TCP console port. :param console: console port (integer) """ self.console = console yield from self._hypervisor.send('vm set_con_tcp_port "{name}" {console}'.format(name=self._name, console=self.console))
[ "def", "set_console", "(", "self", ",", "console", ")", ":", "self", ".", "console", "=", "console", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'vm set_con_tcp_port \"{name}\" {console}'", ".", "format", "(", "name", "=", "self", ".", "_...
Sets the TCP console port. :param console: console port (integer)
[ "Sets", "the", "TCP", "console", "port", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L960-L968
train
221,334
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.set_aux
def set_aux(self, aux): """ Sets the TCP auxiliary port. :param aux: console auxiliary port (integer) """ self.aux = aux yield from self._hypervisor.send('vm set_aux_tcp_port "{name}" {aux}'.format(name=self._name, aux=aux))
python
def set_aux(self, aux): """ Sets the TCP auxiliary port. :param aux: console auxiliary port (integer) """ self.aux = aux yield from self._hypervisor.send('vm set_aux_tcp_port "{name}" {aux}'.format(name=self._name, aux=aux))
[ "def", "set_aux", "(", "self", ",", "aux", ")", ":", "self", ".", "aux", "=", "aux", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'vm set_aux_tcp_port \"{name}\" {aux}'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "aux...
Sets the TCP auxiliary port. :param aux: console auxiliary port (integer)
[ "Sets", "the", "TCP", "auxiliary", "port", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L971-L979
train
221,335
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.get_cpu_usage
def get_cpu_usage(self, cpu_id=0): """ Shows cpu usage in seconds, "cpu_id" is ignored. :returns: cpu usage in seconds """ cpu_usage = yield from self._hypervisor.send('vm cpu_usage "{name}" {cpu_id}'.format(name=self._name, cpu_id=cpu_id)) return int(cpu_usage[0])
python
def get_cpu_usage(self, cpu_id=0): """ Shows cpu usage in seconds, "cpu_id" is ignored. :returns: cpu usage in seconds """ cpu_usage = yield from self._hypervisor.send('vm cpu_usage "{name}" {cpu_id}'.format(name=self._name, cpu_id=cpu_id)) return int(cpu_usage[0])
[ "def", "get_cpu_usage", "(", "self", ",", "cpu_id", "=", "0", ")", ":", "cpu_usage", "=", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'vm cpu_usage \"{name}\" {cpu_id}'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "cpu_...
Shows cpu usage in seconds, "cpu_id" is ignored. :returns: cpu usage in seconds
[ "Shows", "cpu", "usage", "in", "seconds", "cpu_id", "is", "ignored", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L982-L990
train
221,336
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.set_mac_addr
def set_mac_addr(self, mac_addr): """ Sets the MAC address. :param mac_addr: a MAC address (hexadecimal format: hh:hh:hh:hh:hh:hh) """ yield from self._hypervisor.send('{platform} set_mac_addr "{name}" {mac_addr}'.format(platform=self._platform, name=self._name, mac_addr=mac_addr)) log.info('Router "{name}" [{id}]: MAC address updated from {old_mac} to {new_mac}'.format(name=self._name, id=self._id, old_mac=self._mac_addr, new_mac=mac_addr)) self._mac_addr = mac_addr
python
def set_mac_addr(self, mac_addr): """ Sets the MAC address. :param mac_addr: a MAC address (hexadecimal format: hh:hh:hh:hh:hh:hh) """ yield from self._hypervisor.send('{platform} set_mac_addr "{name}" {mac_addr}'.format(platform=self._platform, name=self._name, mac_addr=mac_addr)) log.info('Router "{name}" [{id}]: MAC address updated from {old_mac} to {new_mac}'.format(name=self._name, id=self._id, old_mac=self._mac_addr, new_mac=mac_addr)) self._mac_addr = mac_addr
[ "def", "set_mac_addr", "(", "self", ",", "mac_addr", ")", ":", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'{platform} set_mac_addr \"{name}\" {mac_addr}'", ".", "format", "(", "platform", "=", "self", ".", "_platform", ",", "name", "=", "s...
Sets the MAC address. :param mac_addr: a MAC address (hexadecimal format: hh:hh:hh:hh:hh:hh)
[ "Sets", "the", "MAC", "address", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L1003-L1018
train
221,337
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.set_system_id
def set_system_id(self, system_id): """ Sets the system ID. :param system_id: a system ID (also called board processor ID) """ yield from self._hypervisor.send('{platform} set_system_id "{name}" {system_id}'.format(platform=self._platform, name=self._name, system_id=system_id)) log.info('Router "{name}" [{id}]: system ID updated from {old_id} to {new_id}'.format(name=self._name, id=self._id, old_id=self._system_id, new_id=system_id)) self._system_id = system_id
python
def set_system_id(self, system_id): """ Sets the system ID. :param system_id: a system ID (also called board processor ID) """ yield from self._hypervisor.send('{platform} set_system_id "{name}" {system_id}'.format(platform=self._platform, name=self._name, system_id=system_id)) log.info('Router "{name}" [{id}]: system ID updated from {old_id} to {new_id}'.format(name=self._name, id=self._id, old_id=self._system_id, new_id=system_id)) self._system_id = system_id
[ "def", "set_system_id", "(", "self", ",", "system_id", ")", ":", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'{platform} set_system_id \"{name}\" {system_id}'", ".", "format", "(", "platform", "=", "self", ".", "_platform", ",", "name", "=", ...
Sets the system ID. :param system_id: a system ID (also called board processor ID)
[ "Sets", "the", "system", "ID", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L1031-L1046
train
221,338
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.get_slot_bindings
def get_slot_bindings(self): """ Returns slot bindings. :returns: slot bindings (adapter names) list """ slot_bindings = yield from self._hypervisor.send('vm slot_bindings "{}"'.format(self._name)) return slot_bindings
python
def get_slot_bindings(self): """ Returns slot bindings. :returns: slot bindings (adapter names) list """ slot_bindings = yield from self._hypervisor.send('vm slot_bindings "{}"'.format(self._name)) return slot_bindings
[ "def", "get_slot_bindings", "(", "self", ")", ":", "slot_bindings", "=", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'vm slot_bindings \"{}\"'", ".", "format", "(", "self", ".", "_name", ")", ")", "return", "slot_bindings" ]
Returns slot bindings. :returns: slot bindings (adapter names) list
[ "Returns", "slot", "bindings", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L1049-L1057
train
221,339
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.uninstall_wic
def uninstall_wic(self, wic_slot_number): """ Uninstalls a WIC adapter from this router. :param wic_slot_number: WIC slot number """ # WICs are always installed on adapters in slot 0 slot_number = 0 # Do not check if slot has an adapter because adapters with WICs interfaces # must be inserted by default in the router and cannot be removed. adapter = self._slots[slot_number] if wic_slot_number > len(adapter.wics) - 1: raise DynamipsError("WIC slot {wic_slot_number} doesn't exist".format(wic_slot_number=wic_slot_number)) if adapter.wic_slot_available(wic_slot_number): raise DynamipsError("No WIC is installed in WIC slot {wic_slot_number}".format(wic_slot_number=wic_slot_number)) # Dynamips WICs slot IDs start on a multiple of 16 # WIC1 = 16, WIC2 = 32 and WIC3 = 48 internal_wic_slot_number = 16 * (wic_slot_number + 1) yield from self._hypervisor.send('vm slot_remove_binding "{name}" {slot_number} {wic_slot_number}'.format(name=self._name, slot_number=slot_number, wic_slot_number=internal_wic_slot_number)) log.info('Router "{name}" [{id}]: {wic} removed from WIC slot {wic_slot_number}'.format(name=self._name, id=self._id, wic=adapter.wics[wic_slot_number], wic_slot_number=wic_slot_number)) adapter.uninstall_wic(wic_slot_number)
python
def uninstall_wic(self, wic_slot_number): """ Uninstalls a WIC adapter from this router. :param wic_slot_number: WIC slot number """ # WICs are always installed on adapters in slot 0 slot_number = 0 # Do not check if slot has an adapter because adapters with WICs interfaces # must be inserted by default in the router and cannot be removed. adapter = self._slots[slot_number] if wic_slot_number > len(adapter.wics) - 1: raise DynamipsError("WIC slot {wic_slot_number} doesn't exist".format(wic_slot_number=wic_slot_number)) if adapter.wic_slot_available(wic_slot_number): raise DynamipsError("No WIC is installed in WIC slot {wic_slot_number}".format(wic_slot_number=wic_slot_number)) # Dynamips WICs slot IDs start on a multiple of 16 # WIC1 = 16, WIC2 = 32 and WIC3 = 48 internal_wic_slot_number = 16 * (wic_slot_number + 1) yield from self._hypervisor.send('vm slot_remove_binding "{name}" {slot_number} {wic_slot_number}'.format(name=self._name, slot_number=slot_number, wic_slot_number=internal_wic_slot_number)) log.info('Router "{name}" [{id}]: {wic} removed from WIC slot {wic_slot_number}'.format(name=self._name, id=self._id, wic=adapter.wics[wic_slot_number], wic_slot_number=wic_slot_number)) adapter.uninstall_wic(wic_slot_number)
[ "def", "uninstall_wic", "(", "self", ",", "wic_slot_number", ")", ":", "# WICs are always installed on adapters in slot 0", "slot_number", "=", "0", "# Do not check if slot has an adapter because adapters with WICs interfaces", "# must be inserted by default in the router and cannot be rem...
Uninstalls a WIC adapter from this router. :param wic_slot_number: WIC slot number
[ "Uninstalls", "a", "WIC", "adapter", "from", "this", "router", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L1193-L1224
train
221,340
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.get_slot_nio_bindings
def get_slot_nio_bindings(self, slot_number): """ Returns slot NIO bindings. :param slot_number: slot number :returns: list of NIO bindings """ nio_bindings = yield from self._hypervisor.send('vm slot_nio_bindings "{name}" {slot_number}'.format(name=self._name, slot_number=slot_number)) return nio_bindings
python
def get_slot_nio_bindings(self, slot_number): """ Returns slot NIO bindings. :param slot_number: slot number :returns: list of NIO bindings """ nio_bindings = yield from self._hypervisor.send('vm slot_nio_bindings "{name}" {slot_number}'.format(name=self._name, slot_number=slot_number)) return nio_bindings
[ "def", "get_slot_nio_bindings", "(", "self", ",", "slot_number", ")", ":", "nio_bindings", "=", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'vm slot_nio_bindings \"{name}\" {slot_number}'", ".", "format", "(", "name", "=", "self", ".", "_name",...
Returns slot NIO bindings. :param slot_number: slot number :returns: list of NIO bindings
[ "Returns", "slot", "NIO", "bindings", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L1227-L1238
train
221,341
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.slot_add_nio_binding
def slot_add_nio_binding(self, slot_number, port_number, nio): """ Adds a slot NIO binding. :param slot_number: slot number :param port_number: port number :param nio: NIO instance to add to the slot/port """ try: adapter = self._slots[slot_number] except IndexError: raise DynamipsError('Slot {slot_number} does not exist on router "{name}"'.format(name=self._name, slot_number=slot_number)) if adapter is None: raise DynamipsError("Adapter is missing in slot {slot_number}".format(slot_number=slot_number)) if not adapter.port_exists(port_number): raise DynamipsError("Port {port_number} does not exist in adapter {adapter}".format(adapter=adapter, port_number=port_number)) try: yield from self._hypervisor.send('vm slot_add_nio_binding "{name}" {slot_number} {port_number} {nio}'.format(name=self._name, slot_number=slot_number, port_number=port_number, nio=nio)) except DynamipsError: # in case of error try to remove and add the nio binding yield from self._hypervisor.send('vm slot_remove_nio_binding "{name}" {slot_number} {port_number}'.format(name=self._name, slot_number=slot_number, port_number=port_number)) yield from self._hypervisor.send('vm slot_add_nio_binding "{name}" {slot_number} {port_number} {nio}'.format(name=self._name, slot_number=slot_number, port_number=port_number, nio=nio)) log.info('Router "{name}" [{id}]: NIO {nio_name} bound to port {slot_number}/{port_number}'.format(name=self._name, id=self._id, nio_name=nio.name, slot_number=slot_number, port_number=port_number)) yield from self.slot_enable_nio(slot_number, port_number) adapter.add_nio(port_number, nio)
python
def slot_add_nio_binding(self, slot_number, port_number, nio): """ Adds a slot NIO binding. :param slot_number: slot number :param port_number: port number :param nio: NIO instance to add to the slot/port """ try: adapter = self._slots[slot_number] except IndexError: raise DynamipsError('Slot {slot_number} does not exist on router "{name}"'.format(name=self._name, slot_number=slot_number)) if adapter is None: raise DynamipsError("Adapter is missing in slot {slot_number}".format(slot_number=slot_number)) if not adapter.port_exists(port_number): raise DynamipsError("Port {port_number} does not exist in adapter {adapter}".format(adapter=adapter, port_number=port_number)) try: yield from self._hypervisor.send('vm slot_add_nio_binding "{name}" {slot_number} {port_number} {nio}'.format(name=self._name, slot_number=slot_number, port_number=port_number, nio=nio)) except DynamipsError: # in case of error try to remove and add the nio binding yield from self._hypervisor.send('vm slot_remove_nio_binding "{name}" {slot_number} {port_number}'.format(name=self._name, slot_number=slot_number, port_number=port_number)) yield from self._hypervisor.send('vm slot_add_nio_binding "{name}" {slot_number} {port_number} {nio}'.format(name=self._name, slot_number=slot_number, port_number=port_number, nio=nio)) log.info('Router "{name}" [{id}]: NIO {nio_name} bound to port {slot_number}/{port_number}'.format(name=self._name, id=self._id, nio_name=nio.name, slot_number=slot_number, port_number=port_number)) yield from self.slot_enable_nio(slot_number, port_number) adapter.add_nio(port_number, nio)
[ "def", "slot_add_nio_binding", "(", "self", ",", "slot_number", ",", "port_number", ",", "nio", ")", ":", "try", ":", "adapter", "=", "self", ".", "_slots", "[", "slot_number", "]", "except", "IndexError", ":", "raise", "DynamipsError", "(", "'Slot {slot_numbe...
Adds a slot NIO binding. :param slot_number: slot number :param port_number: port number :param nio: NIO instance to add to the slot/port
[ "Adds", "a", "slot", "NIO", "binding", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L1241-L1285
train
221,342
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.slot_remove_nio_binding
def slot_remove_nio_binding(self, slot_number, port_number): """ Removes a slot NIO binding. :param slot_number: slot number :param port_number: port number :returns: removed NIO instance """ try: adapter = self._slots[slot_number] except IndexError: raise DynamipsError('Slot {slot_number} does not exist on router "{name}"'.format(name=self._name, slot_number=slot_number)) if adapter is None: raise DynamipsError("Adapter is missing in slot {slot_number}".format(slot_number=slot_number)) if not adapter.port_exists(port_number): raise DynamipsError("Port {port_number} does not exist in adapter {adapter}".format(adapter=adapter, port_number=port_number)) yield from self.slot_disable_nio(slot_number, port_number) yield from self._hypervisor.send('vm slot_remove_nio_binding "{name}" {slot_number} {port_number}'.format(name=self._name, slot_number=slot_number, port_number=port_number)) nio = adapter.get_nio(port_number) if nio is None: return yield from nio.close() adapter.remove_nio(port_number) log.info('Router "{name}" [{id}]: NIO {nio_name} removed from port {slot_number}/{port_number}'.format(name=self._name, id=self._id, nio_name=nio.name, slot_number=slot_number, port_number=port_number)) return nio
python
def slot_remove_nio_binding(self, slot_number, port_number): """ Removes a slot NIO binding. :param slot_number: slot number :param port_number: port number :returns: removed NIO instance """ try: adapter = self._slots[slot_number] except IndexError: raise DynamipsError('Slot {slot_number} does not exist on router "{name}"'.format(name=self._name, slot_number=slot_number)) if adapter is None: raise DynamipsError("Adapter is missing in slot {slot_number}".format(slot_number=slot_number)) if not adapter.port_exists(port_number): raise DynamipsError("Port {port_number} does not exist in adapter {adapter}".format(adapter=adapter, port_number=port_number)) yield from self.slot_disable_nio(slot_number, port_number) yield from self._hypervisor.send('vm slot_remove_nio_binding "{name}" {slot_number} {port_number}'.format(name=self._name, slot_number=slot_number, port_number=port_number)) nio = adapter.get_nio(port_number) if nio is None: return yield from nio.close() adapter.remove_nio(port_number) log.info('Router "{name}" [{id}]: NIO {nio_name} removed from port {slot_number}/{port_number}'.format(name=self._name, id=self._id, nio_name=nio.name, slot_number=slot_number, port_number=port_number)) return nio
[ "def", "slot_remove_nio_binding", "(", "self", ",", "slot_number", ",", "port_number", ")", ":", "try", ":", "adapter", "=", "self", ".", "_slots", "[", "slot_number", "]", "except", "IndexError", ":", "raise", "DynamipsError", "(", "'Slot {slot_number} does not e...
Removes a slot NIO binding. :param slot_number: slot number :param port_number: port number :returns: removed NIO instance
[ "Removes", "a", "slot", "NIO", "binding", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L1299-L1339
train
221,343
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.slot_enable_nio
def slot_enable_nio(self, slot_number, port_number): """ Enables a slot NIO binding. :param slot_number: slot number :param port_number: port number """ is_running = yield from self.is_running() if is_running: # running router yield from self._hypervisor.send('vm slot_enable_nio "{name}" {slot_number} {port_number}'.format(name=self._name, slot_number=slot_number, port_number=port_number)) log.info('Router "{name}" [{id}]: NIO enabled on port {slot_number}/{port_number}'.format(name=self._name, id=self._id, slot_number=slot_number, port_number=port_number))
python
def slot_enable_nio(self, slot_number, port_number): """ Enables a slot NIO binding. :param slot_number: slot number :param port_number: port number """ is_running = yield from self.is_running() if is_running: # running router yield from self._hypervisor.send('vm slot_enable_nio "{name}" {slot_number} {port_number}'.format(name=self._name, slot_number=slot_number, port_number=port_number)) log.info('Router "{name}" [{id}]: NIO enabled on port {slot_number}/{port_number}'.format(name=self._name, id=self._id, slot_number=slot_number, port_number=port_number))
[ "def", "slot_enable_nio", "(", "self", ",", "slot_number", ",", "port_number", ")", ":", "is_running", "=", "yield", "from", "self", ".", "is_running", "(", ")", "if", "is_running", ":", "# running router", "yield", "from", "self", ".", "_hypervisor", ".", "...
Enables a slot NIO binding. :param slot_number: slot number :param port_number: port number
[ "Enables", "a", "slot", "NIO", "binding", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L1342-L1359
train
221,344
GNS3/gns3-server
gns3server/compute/dynamips/nodes/router.py
Router.set_name
def set_name(self, new_name): """ Renames this router. :param new_name: new name string """ # change the hostname in the startup-config if os.path.isfile(self.startup_config_path): try: with open(self.startup_config_path, "r+", encoding="utf-8", errors="replace") as f: old_config = f.read() new_config = re.sub(r"^hostname .+$", "hostname " + new_name, old_config, flags=re.MULTILINE) f.seek(0) f.write(new_config) except OSError as e: raise DynamipsError("Could not amend the configuration {}: {}".format(self.startup_config_path, e)) # change the hostname in the private-config if os.path.isfile(self.private_config_path): try: with open(self.private_config_path, "r+", encoding="utf-8", errors="replace") as f: old_config = f.read() new_config = old_config.replace(self.name, new_name) f.seek(0) f.write(new_config) except OSError as e: raise DynamipsError("Could not amend the configuration {}: {}".format(self.private_config_path, e)) yield from self._hypervisor.send('vm rename "{name}" "{new_name}"'.format(name=self._name, new_name=new_name)) log.info('Router "{name}" [{id}]: renamed to "{new_name}"'.format(name=self._name, id=self._id, new_name=new_name)) self._name = new_name
python
def set_name(self, new_name): """ Renames this router. :param new_name: new name string """ # change the hostname in the startup-config if os.path.isfile(self.startup_config_path): try: with open(self.startup_config_path, "r+", encoding="utf-8", errors="replace") as f: old_config = f.read() new_config = re.sub(r"^hostname .+$", "hostname " + new_name, old_config, flags=re.MULTILINE) f.seek(0) f.write(new_config) except OSError as e: raise DynamipsError("Could not amend the configuration {}: {}".format(self.startup_config_path, e)) # change the hostname in the private-config if os.path.isfile(self.private_config_path): try: with open(self.private_config_path, "r+", encoding="utf-8", errors="replace") as f: old_config = f.read() new_config = old_config.replace(self.name, new_name) f.seek(0) f.write(new_config) except OSError as e: raise DynamipsError("Could not amend the configuration {}: {}".format(self.private_config_path, e)) yield from self._hypervisor.send('vm rename "{name}" "{new_name}"'.format(name=self._name, new_name=new_name)) log.info('Router "{name}" [{id}]: renamed to "{new_name}"'.format(name=self._name, id=self._id, new_name=new_name)) self._name = new_name
[ "def", "set_name", "(", "self", ",", "new_name", ")", ":", "# change the hostname in the startup-config", "if", "os", ".", "path", ".", "isfile", "(", "self", ".", "startup_config_path", ")", ":", "try", ":", "with", "open", "(", "self", ".", "startup_config_p...
Renames this router. :param new_name: new name string
[ "Renames", "this", "router", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L1495-L1526
train
221,345
GNS3/gns3-server
gns3server/utils/__init__.py
parse_version
def parse_version(version): """ Return a comparable tuple from a version string. We try to force tuple to semver with version like 1.2.0 Replace pkg_resources.parse_version which now display a warning when use for comparing version with tuple :returns: Version string as comparable tuple """ release_type_found = False version_infos = re.split('(\.|[a-z]+)', version) version = [] for info in version_infos: if info == '.' or len(info) == 0: continue try: info = int(info) # We pad with zero to compare only on string # This avoid issue when comparing version with different length version.append("%06d" % (info,)) except ValueError: # Force to a version with three number if len(version) == 1: version.append("00000") if len(version) == 2: version.append("000000") # We want rc to be at lower level than dev version if info == 'rc': info = 'c' version.append(info) release_type_found = True if release_type_found is False: # Force to a version with three number if len(version) == 1: version.append("00000") if len(version) == 2: version.append("000000") version.append("final") return tuple(version)
python
def parse_version(version): """ Return a comparable tuple from a version string. We try to force tuple to semver with version like 1.2.0 Replace pkg_resources.parse_version which now display a warning when use for comparing version with tuple :returns: Version string as comparable tuple """ release_type_found = False version_infos = re.split('(\.|[a-z]+)', version) version = [] for info in version_infos: if info == '.' or len(info) == 0: continue try: info = int(info) # We pad with zero to compare only on string # This avoid issue when comparing version with different length version.append("%06d" % (info,)) except ValueError: # Force to a version with three number if len(version) == 1: version.append("00000") if len(version) == 2: version.append("000000") # We want rc to be at lower level than dev version if info == 'rc': info = 'c' version.append(info) release_type_found = True if release_type_found is False: # Force to a version with three number if len(version) == 1: version.append("00000") if len(version) == 2: version.append("000000") version.append("final") return tuple(version)
[ "def", "parse_version", "(", "version", ")", ":", "release_type_found", "=", "False", "version_infos", "=", "re", ".", "split", "(", "'(\\.|[a-z]+)'", ",", "version", ")", "version", "=", "[", "]", "for", "info", "in", "version_infos", ":", "if", "info", "...
Return a comparable tuple from a version string. We try to force tuple to semver with version like 1.2.0 Replace pkg_resources.parse_version which now display a warning when use for comparing version with tuple :returns: Version string as comparable tuple
[ "Return", "a", "comparable", "tuple", "from", "a", "version", "string", ".", "We", "try", "to", "force", "tuple", "to", "semver", "with", "version", "like", "1", ".", "2", ".", "0" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/__init__.py#L52-L90
train
221,346
GNS3/gns3-server
gns3server/controller/gns3vm/virtualbox_gns3_vm.py
VirtualBoxGNS3VM._look_for_interface
def _look_for_interface(self, network_backend): """ Look for an interface with a specific network backend. :returns: interface number or -1 if none is found """ result = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"]) interface = -1 for info in result.splitlines(): if '=' in info: name, value = info.split('=', 1) if name.startswith("nic") and value.strip('"') == network_backend: try: interface = int(name[3:]) break except ValueError: continue return interface
python
def _look_for_interface(self, network_backend): """ Look for an interface with a specific network backend. :returns: interface number or -1 if none is found """ result = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"]) interface = -1 for info in result.splitlines(): if '=' in info: name, value = info.split('=', 1) if name.startswith("nic") and value.strip('"') == network_backend: try: interface = int(name[3:]) break except ValueError: continue return interface
[ "def", "_look_for_interface", "(", "self", ",", "network_backend", ")", ":", "result", "=", "yield", "from", "self", ".", "_execute", "(", "\"showvminfo\"", ",", "[", "self", ".", "_vmname", ",", "\"--machinereadable\"", "]", ")", "interface", "=", "-", "1",...
Look for an interface with a specific network backend. :returns: interface number or -1 if none is found
[ "Look", "for", "an", "interface", "with", "a", "specific", "network", "backend", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/virtualbox_gns3_vm.py#L68-L86
train
221,347
GNS3/gns3-server
gns3server/controller/gns3vm/virtualbox_gns3_vm.py
VirtualBoxGNS3VM._look_for_vboxnet
def _look_for_vboxnet(self, interface_number): """ Look for the VirtualBox network name associated with a host only interface. :returns: None or vboxnet name """ result = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"]) for info in result.splitlines(): if '=' in info: name, value = info.split('=', 1) if name == "hostonlyadapter{}".format(interface_number): return value.strip('"') return None
python
def _look_for_vboxnet(self, interface_number): """ Look for the VirtualBox network name associated with a host only interface. :returns: None or vboxnet name """ result = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"]) for info in result.splitlines(): if '=' in info: name, value = info.split('=', 1) if name == "hostonlyadapter{}".format(interface_number): return value.strip('"') return None
[ "def", "_look_for_vboxnet", "(", "self", ",", "interface_number", ")", ":", "result", "=", "yield", "from", "self", ".", "_execute", "(", "\"showvminfo\"", ",", "[", "self", ".", "_vmname", ",", "\"--machinereadable\"", "]", ")", "for", "info", "in", "result...
Look for the VirtualBox network name associated with a host only interface. :returns: None or vboxnet name
[ "Look", "for", "the", "VirtualBox", "network", "name", "associated", "with", "a", "host", "only", "interface", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/virtualbox_gns3_vm.py#L89-L102
train
221,348
GNS3/gns3-server
gns3server/controller/gns3vm/virtualbox_gns3_vm.py
VirtualBoxGNS3VM._check_dhcp_server
def _check_dhcp_server(self, vboxnet): """ Check if the DHCP server associated with a vboxnet is enabled. :param vboxnet: vboxnet name :returns: boolean """ properties = yield from self._execute("list", ["dhcpservers"]) flag_dhcp_server_found = False for prop in properties.splitlines(): try: name, value = prop.split(':', 1) except ValueError: continue if name.strip() == "NetworkName" and value.strip().endswith(vboxnet): flag_dhcp_server_found = True if flag_dhcp_server_found and name.strip() == "Enabled": if value.strip() == "Yes": return True return False
python
def _check_dhcp_server(self, vboxnet): """ Check if the DHCP server associated with a vboxnet is enabled. :param vboxnet: vboxnet name :returns: boolean """ properties = yield from self._execute("list", ["dhcpservers"]) flag_dhcp_server_found = False for prop in properties.splitlines(): try: name, value = prop.split(':', 1) except ValueError: continue if name.strip() == "NetworkName" and value.strip().endswith(vboxnet): flag_dhcp_server_found = True if flag_dhcp_server_found and name.strip() == "Enabled": if value.strip() == "Yes": return True return False
[ "def", "_check_dhcp_server", "(", "self", ",", "vboxnet", ")", ":", "properties", "=", "yield", "from", "self", ".", "_execute", "(", "\"list\"", ",", "[", "\"dhcpservers\"", "]", ")", "flag_dhcp_server_found", "=", "False", "for", "prop", "in", "properties", ...
Check if the DHCP server associated with a vboxnet is enabled. :param vboxnet: vboxnet name :returns: boolean
[ "Check", "if", "the", "DHCP", "server", "associated", "with", "a", "vboxnet", "is", "enabled", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/virtualbox_gns3_vm.py#L105-L126
train
221,349
GNS3/gns3-server
gns3server/controller/gns3vm/virtualbox_gns3_vm.py
VirtualBoxGNS3VM._check_vbox_port_forwarding
def _check_vbox_port_forwarding(self): """ Checks if the NAT port forwarding rule exists. :returns: boolean """ result = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"]) for info in result.splitlines(): if '=' in info: name, value = info.split('=', 1) if name.startswith("Forwarding") and value.strip('"').startswith("GNS3VM"): return True return False
python
def _check_vbox_port_forwarding(self): """ Checks if the NAT port forwarding rule exists. :returns: boolean """ result = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"]) for info in result.splitlines(): if '=' in info: name, value = info.split('=', 1) if name.startswith("Forwarding") and value.strip('"').startswith("GNS3VM"): return True return False
[ "def", "_check_vbox_port_forwarding", "(", "self", ")", ":", "result", "=", "yield", "from", "self", ".", "_execute", "(", "\"showvminfo\"", ",", "[", "self", ".", "_vmname", ",", "\"--machinereadable\"", "]", ")", "for", "info", "in", "result", ".", "splitl...
Checks if the NAT port forwarding rule exists. :returns: boolean
[ "Checks", "if", "the", "NAT", "port", "forwarding", "rule", "exists", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/virtualbox_gns3_vm.py#L129-L142
train
221,350
GNS3/gns3-server
gns3server/controller/gns3vm/virtualbox_gns3_vm.py
VirtualBoxGNS3VM.start
def start(self): """ Start the GNS3 VM. """ # get a NAT interface number nat_interface_number = yield from self._look_for_interface("nat") if nat_interface_number < 0: raise GNS3VMError("The GNS3 VM: {} must have a NAT interface configured in order to start".format(self.vmname)) hostonly_interface_number = yield from self._look_for_interface("hostonly") if hostonly_interface_number < 0: raise GNS3VMError("The GNS3 VM: {} must have a host only interface configured in order to start".format(self.vmname)) vboxnet = yield from self._look_for_vboxnet(hostonly_interface_number) if vboxnet is None: raise GNS3VMError("VirtualBox host-only network could not be found for interface {} on GNS3 VM".format(hostonly_interface_number)) if not (yield from self._check_dhcp_server(vboxnet)): raise GNS3VMError("DHCP must be enabled on VirtualBox host-only network: {} for GNS3 VM".format(vboxnet)) vm_state = yield from self._get_state() log.info('"{}" state is {}'.format(self._vmname, vm_state)) if vm_state == "poweroff": yield from self.set_vcpus(self.vcpus) yield from self.set_ram(self.ram) if vm_state in ("poweroff", "saved"): # start the VM if it is not running args = [self._vmname] if self._headless: args.extend(["--type", "headless"]) yield from self._execute("startvm", args) elif vm_state == "paused": args = [self._vmname, "resume"] yield from self._execute("controlvm", args) ip_address = "127.0.0.1" try: # get a random port on localhost with socket.socket() as s: s.bind((ip_address, 0)) api_port = s.getsockname()[1] except OSError as e: raise GNS3VMError("Error while getting random port: {}".format(e)) if (yield from self._check_vbox_port_forwarding()): # delete the GNS3VM NAT port forwarding rule if it exists log.info("Removing GNS3VM NAT port forwarding rule from interface {}".format(nat_interface_number)) yield from self._execute("controlvm", [self._vmname, "natpf{}".format(nat_interface_number), "delete", "GNS3VM"]) # add a GNS3VM NAT port forwarding rule to redirect 127.0.0.1 with random port to port 3080 in the VM log.info("Adding GNS3VM NAT port forwarding rule with port {} to interface {}".format(api_port, nat_interface_number)) yield from self._execute("controlvm", [self._vmname, "natpf{}".format(nat_interface_number), "GNS3VM,tcp,{},{},,3080".format(ip_address, api_port)]) self.ip_address = yield from self._get_ip(hostonly_interface_number, api_port) self.port = 3080 log.info("GNS3 VM has been started with IP {}".format(self.ip_address)) self.running = True
python
def start(self): """ Start the GNS3 VM. """ # get a NAT interface number nat_interface_number = yield from self._look_for_interface("nat") if nat_interface_number < 0: raise GNS3VMError("The GNS3 VM: {} must have a NAT interface configured in order to start".format(self.vmname)) hostonly_interface_number = yield from self._look_for_interface("hostonly") if hostonly_interface_number < 0: raise GNS3VMError("The GNS3 VM: {} must have a host only interface configured in order to start".format(self.vmname)) vboxnet = yield from self._look_for_vboxnet(hostonly_interface_number) if vboxnet is None: raise GNS3VMError("VirtualBox host-only network could not be found for interface {} on GNS3 VM".format(hostonly_interface_number)) if not (yield from self._check_dhcp_server(vboxnet)): raise GNS3VMError("DHCP must be enabled on VirtualBox host-only network: {} for GNS3 VM".format(vboxnet)) vm_state = yield from self._get_state() log.info('"{}" state is {}'.format(self._vmname, vm_state)) if vm_state == "poweroff": yield from self.set_vcpus(self.vcpus) yield from self.set_ram(self.ram) if vm_state in ("poweroff", "saved"): # start the VM if it is not running args = [self._vmname] if self._headless: args.extend(["--type", "headless"]) yield from self._execute("startvm", args) elif vm_state == "paused": args = [self._vmname, "resume"] yield from self._execute("controlvm", args) ip_address = "127.0.0.1" try: # get a random port on localhost with socket.socket() as s: s.bind((ip_address, 0)) api_port = s.getsockname()[1] except OSError as e: raise GNS3VMError("Error while getting random port: {}".format(e)) if (yield from self._check_vbox_port_forwarding()): # delete the GNS3VM NAT port forwarding rule if it exists log.info("Removing GNS3VM NAT port forwarding rule from interface {}".format(nat_interface_number)) yield from self._execute("controlvm", [self._vmname, "natpf{}".format(nat_interface_number), "delete", "GNS3VM"]) # add a GNS3VM NAT port forwarding rule to redirect 127.0.0.1 with random port to port 3080 in the VM log.info("Adding GNS3VM NAT port forwarding rule with port {} to interface {}".format(api_port, nat_interface_number)) yield from self._execute("controlvm", [self._vmname, "natpf{}".format(nat_interface_number), "GNS3VM,tcp,{},{},,3080".format(ip_address, api_port)]) self.ip_address = yield from self._get_ip(hostonly_interface_number, api_port) self.port = 3080 log.info("GNS3 VM has been started with IP {}".format(self.ip_address)) self.running = True
[ "def", "start", "(", "self", ")", ":", "# get a NAT interface number", "nat_interface_number", "=", "yield", "from", "self", ".", "_look_for_interface", "(", "\"nat\"", ")", "if", "nat_interface_number", "<", "0", ":", "raise", "GNS3VMError", "(", "\"The GNS3 VM: {}...
Start the GNS3 VM.
[ "Start", "the", "GNS3", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/virtualbox_gns3_vm.py#L153-L212
train
221,351
GNS3/gns3-server
gns3server/controller/gns3vm/virtualbox_gns3_vm.py
VirtualBoxGNS3VM._get_ip
def _get_ip(self, hostonly_interface_number, api_port): """ Get the IP from VirtualBox. Due to VirtualBox limitation the only way is to send request each second to a GNS3 endpoint in order to get the list of the interfaces and their IP and after that match it with VirtualBox host only. """ remaining_try = 300 while remaining_try > 0: json_data = None session = aiohttp.ClientSession() try: resp = None resp = yield from session.get('http://127.0.0.1:{}/v2/compute/network/interfaces'.format(api_port)) except (OSError, aiohttp.ClientError, TimeoutError, asyncio.TimeoutError): pass if resp: if resp.status < 300: try: json_data = yield from resp.json() except ValueError: pass resp.close() session.close() if json_data: for interface in json_data: if "name" in interface and interface["name"] == "eth{}".format(hostonly_interface_number - 1): if "ip_address" in interface and len(interface["ip_address"]) > 0: return interface["ip_address"] remaining_try -= 1 yield from asyncio.sleep(1) raise GNS3VMError("Could not get the GNS3 VM ip make sure the VM receive an IP from VirtualBox")
python
def _get_ip(self, hostonly_interface_number, api_port): """ Get the IP from VirtualBox. Due to VirtualBox limitation the only way is to send request each second to a GNS3 endpoint in order to get the list of the interfaces and their IP and after that match it with VirtualBox host only. """ remaining_try = 300 while remaining_try > 0: json_data = None session = aiohttp.ClientSession() try: resp = None resp = yield from session.get('http://127.0.0.1:{}/v2/compute/network/interfaces'.format(api_port)) except (OSError, aiohttp.ClientError, TimeoutError, asyncio.TimeoutError): pass if resp: if resp.status < 300: try: json_data = yield from resp.json() except ValueError: pass resp.close() session.close() if json_data: for interface in json_data: if "name" in interface and interface["name"] == "eth{}".format(hostonly_interface_number - 1): if "ip_address" in interface and len(interface["ip_address"]) > 0: return interface["ip_address"] remaining_try -= 1 yield from asyncio.sleep(1) raise GNS3VMError("Could not get the GNS3 VM ip make sure the VM receive an IP from VirtualBox")
[ "def", "_get_ip", "(", "self", ",", "hostonly_interface_number", ",", "api_port", ")", ":", "remaining_try", "=", "300", "while", "remaining_try", ">", "0", ":", "json_data", "=", "None", "session", "=", "aiohttp", ".", "ClientSession", "(", ")", "try", ":",...
Get the IP from VirtualBox. Due to VirtualBox limitation the only way is to send request each second to a GNS3 endpoint in order to get the list of the interfaces and their IP and after that match it with VirtualBox host only.
[ "Get", "the", "IP", "from", "VirtualBox", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/virtualbox_gns3_vm.py#L215-L250
train
221,352
GNS3/gns3-server
gns3server/controller/gns3vm/virtualbox_gns3_vm.py
VirtualBoxGNS3VM.stop
def stop(self): """ Stops the GNS3 VM. """ vm_state = yield from self._get_state() if vm_state == "poweroff": self.running = False return yield from self._execute("controlvm", [self._vmname, "acpipowerbutton"], timeout=3) trial = 120 while True: try: vm_state = yield from self._get_state() # During a small amount of time the command will fail except GNS3VMError: vm_state = "running" if vm_state == "poweroff": break trial -= 1 if trial == 0: yield from self._execute("controlvm", [self._vmname, "poweroff"], timeout=3) break yield from asyncio.sleep(1) log.info("GNS3 VM has been stopped") self.running = False
python
def stop(self): """ Stops the GNS3 VM. """ vm_state = yield from self._get_state() if vm_state == "poweroff": self.running = False return yield from self._execute("controlvm", [self._vmname, "acpipowerbutton"], timeout=3) trial = 120 while True: try: vm_state = yield from self._get_state() # During a small amount of time the command will fail except GNS3VMError: vm_state = "running" if vm_state == "poweroff": break trial -= 1 if trial == 0: yield from self._execute("controlvm", [self._vmname, "poweroff"], timeout=3) break yield from asyncio.sleep(1) log.info("GNS3 VM has been stopped") self.running = False
[ "def", "stop", "(", "self", ")", ":", "vm_state", "=", "yield", "from", "self", ".", "_get_state", "(", ")", "if", "vm_state", "==", "\"poweroff\"", ":", "self", ".", "running", "=", "False", "return", "yield", "from", "self", ".", "_execute", "(", "\"...
Stops the GNS3 VM.
[ "Stops", "the", "GNS3", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/virtualbox_gns3_vm.py#L263-L290
train
221,353
GNS3/gns3-server
gns3server/controller/gns3vm/virtualbox_gns3_vm.py
VirtualBoxGNS3VM.set_vcpus
def set_vcpus(self, vcpus): """ Set the number of vCPU cores for the GNS3 VM. :param vcpus: number of vCPU cores """ yield from self._execute("modifyvm", [self._vmname, "--cpus", str(vcpus)], timeout=3) log.info("GNS3 VM vCPU count set to {}".format(vcpus))
python
def set_vcpus(self, vcpus): """ Set the number of vCPU cores for the GNS3 VM. :param vcpus: number of vCPU cores """ yield from self._execute("modifyvm", [self._vmname, "--cpus", str(vcpus)], timeout=3) log.info("GNS3 VM vCPU count set to {}".format(vcpus))
[ "def", "set_vcpus", "(", "self", ",", "vcpus", ")", ":", "yield", "from", "self", ".", "_execute", "(", "\"modifyvm\"", ",", "[", "self", ".", "_vmname", ",", "\"--cpus\"", ",", "str", "(", "vcpus", ")", "]", ",", "timeout", "=", "3", ")", "log", "...
Set the number of vCPU cores for the GNS3 VM. :param vcpus: number of vCPU cores
[ "Set", "the", "number", "of", "vCPU", "cores", "for", "the", "GNS3", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/virtualbox_gns3_vm.py#L293-L301
train
221,354
GNS3/gns3-server
gns3server/controller/gns3vm/virtualbox_gns3_vm.py
VirtualBoxGNS3VM.set_ram
def set_ram(self, ram): """ Set the RAM amount for the GNS3 VM. :param ram: amount of memory """ yield from self._execute("modifyvm", [self._vmname, "--memory", str(ram)], timeout=3) log.info("GNS3 VM RAM amount set to {}".format(ram))
python
def set_ram(self, ram): """ Set the RAM amount for the GNS3 VM. :param ram: amount of memory """ yield from self._execute("modifyvm", [self._vmname, "--memory", str(ram)], timeout=3) log.info("GNS3 VM RAM amount set to {}".format(ram))
[ "def", "set_ram", "(", "self", ",", "ram", ")", ":", "yield", "from", "self", ".", "_execute", "(", "\"modifyvm\"", ",", "[", "self", ".", "_vmname", ",", "\"--memory\"", ",", "str", "(", "ram", ")", "]", ",", "timeout", "=", "3", ")", "log", ".", ...
Set the RAM amount for the GNS3 VM. :param ram: amount of memory
[ "Set", "the", "RAM", "amount", "for", "the", "GNS3", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/virtualbox_gns3_vm.py#L304-L312
train
221,355
GNS3/gns3-server
gns3server/compute/port_manager.py
PortManager.console_host
def console_host(self, new_host): """ If allow remote connection we need to bind console host to 0.0.0.0 """ server_config = Config.instance().get_section_config("Server") remote_console_connections = server_config.getboolean("allow_remote_console") if remote_console_connections: log.warning("Remote console connections are allowed") self._console_host = "0.0.0.0" else: self._console_host = new_host
python
def console_host(self, new_host): """ If allow remote connection we need to bind console host to 0.0.0.0 """ server_config = Config.instance().get_section_config("Server") remote_console_connections = server_config.getboolean("allow_remote_console") if remote_console_connections: log.warning("Remote console connections are allowed") self._console_host = "0.0.0.0" else: self._console_host = new_host
[ "def", "console_host", "(", "self", ",", "new_host", ")", ":", "server_config", "=", "Config", ".", "instance", "(", ")", ".", "get_section_config", "(", "\"Server\"", ")", "remote_console_connections", "=", "server_config", ".", "getboolean", "(", "\"allow_remote...
If allow remote connection we need to bind console host to 0.0.0.0
[ "If", "allow", "remote", "connection", "we", "need", "to", "bind", "console", "host", "to", "0", ".", "0", ".", "0", ".", "0" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/port_manager.py#L76-L86
train
221,356
GNS3/gns3-server
gns3server/compute/port_manager.py
PortManager.find_unused_port
def find_unused_port(start_port, end_port, host="127.0.0.1", socket_type="TCP", ignore_ports=None): """ Finds an unused port in a range. :param start_port: first port in the range :param end_port: last port in the range :param host: host/address for bind() :param socket_type: TCP (default) or UDP :param ignore_ports: list of port to ignore within the range """ if end_port < start_port: raise HTTPConflict(text="Invalid port range {}-{}".format(start_port, end_port)) last_exception = None for port in range(start_port, end_port + 1): if ignore_ports and (port in ignore_ports or port in BANNED_PORTS): continue try: PortManager._check_port(host, port, socket_type) if host != "0.0.0.0": PortManager._check_port("0.0.0.0", port, socket_type) return port except OSError as e: last_exception = e if port + 1 == end_port: break else: continue raise HTTPConflict(text="Could not find a free port between {} and {} on host {}, last exception: {}".format(start_port, end_port, host, last_exception))
python
def find_unused_port(start_port, end_port, host="127.0.0.1", socket_type="TCP", ignore_ports=None): """ Finds an unused port in a range. :param start_port: first port in the range :param end_port: last port in the range :param host: host/address for bind() :param socket_type: TCP (default) or UDP :param ignore_ports: list of port to ignore within the range """ if end_port < start_port: raise HTTPConflict(text="Invalid port range {}-{}".format(start_port, end_port)) last_exception = None for port in range(start_port, end_port + 1): if ignore_ports and (port in ignore_ports or port in BANNED_PORTS): continue try: PortManager._check_port(host, port, socket_type) if host != "0.0.0.0": PortManager._check_port("0.0.0.0", port, socket_type) return port except OSError as e: last_exception = e if port + 1 == end_port: break else: continue raise HTTPConflict(text="Could not find a free port between {} and {} on host {}, last exception: {}".format(start_port, end_port, host, last_exception))
[ "def", "find_unused_port", "(", "start_port", ",", "end_port", ",", "host", "=", "\"127.0.0.1\"", ",", "socket_type", "=", "\"TCP\"", ",", "ignore_ports", "=", "None", ")", ":", "if", "end_port", "<", "start_port", ":", "raise", "HTTPConflict", "(", "text", ...
Finds an unused port in a range. :param start_port: first port in the range :param end_port: last port in the range :param host: host/address for bind() :param socket_type: TCP (default) or UDP :param ignore_ports: list of port to ignore within the range
[ "Finds", "an", "unused", "port", "in", "a", "range", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/port_manager.py#L131-L165
train
221,357
GNS3/gns3-server
gns3server/compute/port_manager.py
PortManager._check_port
def _check_port(host, port, socket_type): """ Check if an a port is available and raise an OSError if port is not available :returns: boolean """ if socket_type == "UDP": socket_type = socket.SOCK_DGRAM else: socket_type = socket.SOCK_STREAM for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket_type, 0, socket.AI_PASSIVE): af, socktype, proto, _, sa = res with socket.socket(af, socktype, proto) as s: s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(sa) # the port is available if bind is a success return True
python
def _check_port(host, port, socket_type): """ Check if an a port is available and raise an OSError if port is not available :returns: boolean """ if socket_type == "UDP": socket_type = socket.SOCK_DGRAM else: socket_type = socket.SOCK_STREAM for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket_type, 0, socket.AI_PASSIVE): af, socktype, proto, _, sa = res with socket.socket(af, socktype, proto) as s: s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(sa) # the port is available if bind is a success return True
[ "def", "_check_port", "(", "host", ",", "port", ",", "socket_type", ")", ":", "if", "socket_type", "==", "\"UDP\"", ":", "socket_type", "=", "socket", ".", "SOCK_DGRAM", "else", ":", "socket_type", "=", "socket", ".", "SOCK_STREAM", "for", "res", "in", "so...
Check if an a port is available and raise an OSError if port is not available :returns: boolean
[ "Check", "if", "an", "a", "port", "is", "available", "and", "raise", "an", "OSError", "if", "port", "is", "not", "available" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/port_manager.py#L168-L184
train
221,358
GNS3/gns3-server
gns3server/compute/port_manager.py
PortManager.get_free_tcp_port
def get_free_tcp_port(self, project, port_range_start=None, port_range_end=None): """ Get an available TCP port and reserve it :param project: Project instance """ # use the default range is not specific one is given if port_range_start is None and port_range_end is None: port_range_start = self._console_port_range[0] port_range_end = self._console_port_range[1] port = self.find_unused_port(port_range_start, port_range_end, host=self._console_host, socket_type="TCP", ignore_ports=self._used_tcp_ports) self._used_tcp_ports.add(port) project.record_tcp_port(port) log.debug("TCP port {} has been allocated".format(port)) return port
python
def get_free_tcp_port(self, project, port_range_start=None, port_range_end=None): """ Get an available TCP port and reserve it :param project: Project instance """ # use the default range is not specific one is given if port_range_start is None and port_range_end is None: port_range_start = self._console_port_range[0] port_range_end = self._console_port_range[1] port = self.find_unused_port(port_range_start, port_range_end, host=self._console_host, socket_type="TCP", ignore_ports=self._used_tcp_ports) self._used_tcp_ports.add(port) project.record_tcp_port(port) log.debug("TCP port {} has been allocated".format(port)) return port
[ "def", "get_free_tcp_port", "(", "self", ",", "project", ",", "port_range_start", "=", "None", ",", "port_range_end", "=", "None", ")", ":", "# use the default range is not specific one is given", "if", "port_range_start", "is", "None", "and", "port_range_end", "is", ...
Get an available TCP port and reserve it :param project: Project instance
[ "Get", "an", "available", "TCP", "port", "and", "reserve", "it" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/port_manager.py#L186-L207
train
221,359
GNS3/gns3-server
gns3server/compute/port_manager.py
PortManager.reserve_tcp_port
def reserve_tcp_port(self, port, project, port_range_start=None, port_range_end=None): """ Reserve a specific TCP port number. If not available replace it by another. :param port: TCP port number :param project: Project instance :param port_range_start: Port range to use :param port_range_end: Port range to use :returns: The TCP port """ # use the default range is not specific one is given if port_range_start is None and port_range_end is None: port_range_start = self._console_port_range[0] port_range_end = self._console_port_range[1] if port in self._used_tcp_ports: old_port = port port = self.get_free_tcp_port(project, port_range_start=port_range_start, port_range_end=port_range_end) msg = "TCP port {} already in use on host {}. Port has been replaced by {}".format(old_port, self._console_host, port) log.debug(msg) #project.emit("log.warning", {"message": msg}) return port if port < port_range_start or port > port_range_end: old_port = port port = self.get_free_tcp_port(project, port_range_start=port_range_start, port_range_end=port_range_end) msg = "TCP port {} is outside the range {}-{} on host {}. Port has been replaced by {}".format(old_port, port_range_start, port_range_end, self._console_host, port) log.debug(msg) #project.emit("log.warning", {"message": msg}) return port try: PortManager._check_port(self._console_host, port, "TCP") except OSError: old_port = port port = self.get_free_tcp_port(project, port_range_start=port_range_start, port_range_end=port_range_end) msg = "TCP port {} already in use on host {}. Port has been replaced by {}".format(old_port, self._console_host, port) log.debug(msg) #project.emit("log.warning", {"message": msg}) return port self._used_tcp_ports.add(port) project.record_tcp_port(port) log.debug("TCP port {} has been reserved".format(port)) return port
python
def reserve_tcp_port(self, port, project, port_range_start=None, port_range_end=None): """ Reserve a specific TCP port number. If not available replace it by another. :param port: TCP port number :param project: Project instance :param port_range_start: Port range to use :param port_range_end: Port range to use :returns: The TCP port """ # use the default range is not specific one is given if port_range_start is None and port_range_end is None: port_range_start = self._console_port_range[0] port_range_end = self._console_port_range[1] if port in self._used_tcp_ports: old_port = port port = self.get_free_tcp_port(project, port_range_start=port_range_start, port_range_end=port_range_end) msg = "TCP port {} already in use on host {}. Port has been replaced by {}".format(old_port, self._console_host, port) log.debug(msg) #project.emit("log.warning", {"message": msg}) return port if port < port_range_start or port > port_range_end: old_port = port port = self.get_free_tcp_port(project, port_range_start=port_range_start, port_range_end=port_range_end) msg = "TCP port {} is outside the range {}-{} on host {}. Port has been replaced by {}".format(old_port, port_range_start, port_range_end, self._console_host, port) log.debug(msg) #project.emit("log.warning", {"message": msg}) return port try: PortManager._check_port(self._console_host, port, "TCP") except OSError: old_port = port port = self.get_free_tcp_port(project, port_range_start=port_range_start, port_range_end=port_range_end) msg = "TCP port {} already in use on host {}. Port has been replaced by {}".format(old_port, self._console_host, port) log.debug(msg) #project.emit("log.warning", {"message": msg}) return port self._used_tcp_ports.add(port) project.record_tcp_port(port) log.debug("TCP port {} has been reserved".format(port)) return port
[ "def", "reserve_tcp_port", "(", "self", ",", "port", ",", "project", ",", "port_range_start", "=", "None", ",", "port_range_end", "=", "None", ")", ":", "# use the default range is not specific one is given", "if", "port_range_start", "is", "None", "and", "port_range_...
Reserve a specific TCP port number. If not available replace it by another. :param port: TCP port number :param project: Project instance :param port_range_start: Port range to use :param port_range_end: Port range to use :returns: The TCP port
[ "Reserve", "a", "specific", "TCP", "port", "number", ".", "If", "not", "available", "replace", "it", "by", "another", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/port_manager.py#L209-L253
train
221,360
GNS3/gns3-server
gns3server/compute/port_manager.py
PortManager.release_tcp_port
def release_tcp_port(self, port, project): """ Release a specific TCP port number :param port: TCP port number :param project: Project instance """ if port in self._used_tcp_ports: self._used_tcp_ports.remove(port) project.remove_tcp_port(port) log.debug("TCP port {} has been released".format(port))
python
def release_tcp_port(self, port, project): """ Release a specific TCP port number :param port: TCP port number :param project: Project instance """ if port in self._used_tcp_ports: self._used_tcp_ports.remove(port) project.remove_tcp_port(port) log.debug("TCP port {} has been released".format(port))
[ "def", "release_tcp_port", "(", "self", ",", "port", ",", "project", ")", ":", "if", "port", "in", "self", ".", "_used_tcp_ports", ":", "self", ".", "_used_tcp_ports", ".", "remove", "(", "port", ")", "project", ".", "remove_tcp_port", "(", "port", ")", ...
Release a specific TCP port number :param port: TCP port number :param project: Project instance
[ "Release", "a", "specific", "TCP", "port", "number" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/port_manager.py#L255-L266
train
221,361
GNS3/gns3-server
gns3server/compute/port_manager.py
PortManager.get_free_udp_port
def get_free_udp_port(self, project): """ Get an available UDP port and reserve it :param project: Project instance """ port = self.find_unused_port(self._udp_port_range[0], self._udp_port_range[1], host=self._udp_host, socket_type="UDP", ignore_ports=self._used_udp_ports) self._used_udp_ports.add(port) project.record_udp_port(port) log.debug("UDP port {} has been allocated".format(port)) return port
python
def get_free_udp_port(self, project): """ Get an available UDP port and reserve it :param project: Project instance """ port = self.find_unused_port(self._udp_port_range[0], self._udp_port_range[1], host=self._udp_host, socket_type="UDP", ignore_ports=self._used_udp_ports) self._used_udp_ports.add(port) project.record_udp_port(port) log.debug("UDP port {} has been allocated".format(port)) return port
[ "def", "get_free_udp_port", "(", "self", ",", "project", ")", ":", "port", "=", "self", ".", "find_unused_port", "(", "self", ".", "_udp_port_range", "[", "0", "]", ",", "self", ".", "_udp_port_range", "[", "1", "]", ",", "host", "=", "self", ".", "_ud...
Get an available UDP port and reserve it :param project: Project instance
[ "Get", "an", "available", "UDP", "port", "and", "reserve", "it" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/port_manager.py#L268-L283
train
221,362
GNS3/gns3-server
gns3server/compute/port_manager.py
PortManager.reserve_udp_port
def reserve_udp_port(self, port, project): """ Reserve a specific UDP port number :param port: UDP port number :param project: Project instance """ if port in self._used_udp_ports: raise HTTPConflict(text="UDP port {} already in use on host {}".format(port, self._console_host)) if port < self._udp_port_range[0] or port > self._udp_port_range[1]: raise HTTPConflict(text="UDP port {} is outside the range {}-{}".format(port, self._udp_port_range[0], self._udp_port_range[1])) self._used_udp_ports.add(port) project.record_udp_port(port) log.debug("UDP port {} has been reserved".format(port))
python
def reserve_udp_port(self, port, project): """ Reserve a specific UDP port number :param port: UDP port number :param project: Project instance """ if port in self._used_udp_ports: raise HTTPConflict(text="UDP port {} already in use on host {}".format(port, self._console_host)) if port < self._udp_port_range[0] or port > self._udp_port_range[1]: raise HTTPConflict(text="UDP port {} is outside the range {}-{}".format(port, self._udp_port_range[0], self._udp_port_range[1])) self._used_udp_ports.add(port) project.record_udp_port(port) log.debug("UDP port {} has been reserved".format(port))
[ "def", "reserve_udp_port", "(", "self", ",", "port", ",", "project", ")", ":", "if", "port", "in", "self", ".", "_used_udp_ports", ":", "raise", "HTTPConflict", "(", "text", "=", "\"UDP port {} already in use on host {}\"", ".", "format", "(", "port", ",", "se...
Reserve a specific UDP port number :param port: UDP port number :param project: Project instance
[ "Reserve", "a", "specific", "UDP", "port", "number" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/port_manager.py#L285-L299
train
221,363
GNS3/gns3-server
gns3server/compute/port_manager.py
PortManager.release_udp_port
def release_udp_port(self, port, project): """ Release a specific UDP port number :param port: UDP port number :param project: Project instance """ if port in self._used_udp_ports: self._used_udp_ports.remove(port) project.remove_udp_port(port) log.debug("UDP port {} has been released".format(port))
python
def release_udp_port(self, port, project): """ Release a specific UDP port number :param port: UDP port number :param project: Project instance """ if port in self._used_udp_ports: self._used_udp_ports.remove(port) project.remove_udp_port(port) log.debug("UDP port {} has been released".format(port))
[ "def", "release_udp_port", "(", "self", ",", "port", ",", "project", ")", ":", "if", "port", "in", "self", ".", "_used_udp_ports", ":", "self", ".", "_used_udp_ports", ".", "remove", "(", "port", ")", "project", ".", "remove_udp_port", "(", "port", ")", ...
Release a specific UDP port number :param port: UDP port number :param project: Project instance
[ "Release", "a", "specific", "UDP", "port", "number" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/port_manager.py#L301-L312
train
221,364
GNS3/gns3-server
gns3server/compute/iou/__init__.py
IOU.create_node
def create_node(self, *args, **kwargs): """ Creates a new IOU VM. :returns: IOUVM instance """ with (yield from self._iou_id_lock): # wait for a node to be completely created before adding a new one # this is important otherwise we allocate the same application ID # when creating multiple IOU node at the same time application_id = get_next_application_id(self.nodes) node = yield from super().create_node(*args, application_id=application_id, **kwargs) return node
python
def create_node(self, *args, **kwargs): """ Creates a new IOU VM. :returns: IOUVM instance """ with (yield from self._iou_id_lock): # wait for a node to be completely created before adding a new one # this is important otherwise we allocate the same application ID # when creating multiple IOU node at the same time application_id = get_next_application_id(self.nodes) node = yield from super().create_node(*args, application_id=application_id, **kwargs) return node
[ "def", "create_node", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "(", "yield", "from", "self", ".", "_iou_id_lock", ")", ":", "# wait for a node to be completely created before adding a new one", "# this is important otherwise we allocate ...
Creates a new IOU VM. :returns: IOUVM instance
[ "Creates", "a", "new", "IOU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/__init__.py#L45-L58
train
221,365
GNS3/gns3-server
scripts/random_query.py
create_link
async def create_link(project, nodes): """ Create all possible link of a node """ node1 = random.choice(list(nodes.values())) for port in range(0, 8): node2 = random.choice(list(nodes.values())) if node1 == node2: continue data = {"nodes": [ { "adapter_number": 0, "node_id": node1["node_id"], "port_number": port }, { "adapter_number": 0, "node_id": node2["node_id"], "port_number": port } ] } try: await post("/projects/{}/links".format(project["project_id"]), body=data) except (HTTPConflict, HTTPNotFound): pass
python
async def create_link(project, nodes): """ Create all possible link of a node """ node1 = random.choice(list(nodes.values())) for port in range(0, 8): node2 = random.choice(list(nodes.values())) if node1 == node2: continue data = {"nodes": [ { "adapter_number": 0, "node_id": node1["node_id"], "port_number": port }, { "adapter_number": 0, "node_id": node2["node_id"], "port_number": port } ] } try: await post("/projects/{}/links".format(project["project_id"]), body=data) except (HTTPConflict, HTTPNotFound): pass
[ "async", "def", "create_link", "(", "project", ",", "nodes", ")", ":", "node1", "=", "random", ".", "choice", "(", "list", "(", "nodes", ".", "values", "(", ")", ")", ")", "for", "port", "in", "range", "(", "0", ",", "8", ")", ":", "node2", "=", ...
Create all possible link of a node
[ "Create", "all", "possible", "link", "of", "a", "node" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/scripts/random_query.py#L155-L184
train
221,366
GNS3/gns3-server
gns3server/utils/asyncio/pool.py
Pool.join
def join(self): """ Wait for all task to finish """ pending = set() exceptions = set() while len(self._tasks) > 0 or len(pending) > 0: while len(self._tasks) > 0 and len(pending) < self._concurrency: task, args, kwargs = self._tasks.pop(0) pending.add(task(*args, **kwargs)) (done, pending) = yield from asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED) for task in done: if task.exception(): exceptions.add(task.exception()) if len(exceptions) > 0: raise exceptions.pop()
python
def join(self): """ Wait for all task to finish """ pending = set() exceptions = set() while len(self._tasks) > 0 or len(pending) > 0: while len(self._tasks) > 0 and len(pending) < self._concurrency: task, args, kwargs = self._tasks.pop(0) pending.add(task(*args, **kwargs)) (done, pending) = yield from asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED) for task in done: if task.exception(): exceptions.add(task.exception()) if len(exceptions) > 0: raise exceptions.pop()
[ "def", "join", "(", "self", ")", ":", "pending", "=", "set", "(", ")", "exceptions", "=", "set", "(", ")", "while", "len", "(", "self", ".", "_tasks", ")", ">", "0", "or", "len", "(", "pending", ")", ">", "0", ":", "while", "len", "(", "self", ...
Wait for all task to finish
[ "Wait", "for", "all", "task", "to", "finish" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/pool.py#L34-L49
train
221,367
GNS3/gns3-server
gns3server/compute/base_node.py
BaseNode.name
def name(self, new_name): """ Sets the name of this node. :param new_name: name """ log.info("{module}: {name} [{id}] renamed to {new_name}".format(module=self.manager.module_name, name=self.name, id=self.id, new_name=new_name)) self._name = new_name
python
def name(self, new_name): """ Sets the name of this node. :param new_name: name """ log.info("{module}: {name} [{id}] renamed to {new_name}".format(module=self.manager.module_name, name=self.name, id=self.id, new_name=new_name)) self._name = new_name
[ "def", "name", "(", "self", ",", "new_name", ")", ":", "log", ".", "info", "(", "\"{module}: {name} [{id}] renamed to {new_name}\"", ".", "format", "(", "module", "=", "self", ".", "manager", ".", "module_name", ",", "name", "=", "self", ".", "name", ",", ...
Sets the name of this node. :param new_name: name
[ "Sets", "the", "name", "of", "this", "node", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L176-L187
train
221,368
GNS3/gns3-server
gns3server/compute/base_node.py
BaseNode.create
def create(self): """ Creates the node. """ log.info("{module}: {name} [{id}] created".format(module=self.manager.module_name, name=self.name, id=self.id))
python
def create(self): """ Creates the node. """ log.info("{module}: {name} [{id}] created".format(module=self.manager.module_name, name=self.name, id=self.id))
[ "def", "create", "(", "self", ")", ":", "log", ".", "info", "(", "\"{module}: {name} [{id}] created\"", ".", "format", "(", "module", "=", "self", ".", "manager", ".", "module_name", ",", "name", "=", "self", ".", "name", ",", "id", "=", "self", ".", "...
Creates the node.
[ "Creates", "the", "node", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L254-L261
train
221,369
GNS3/gns3-server
gns3server/compute/base_node.py
BaseNode.stop
def stop(self): """ Stop the node process. """ if self._wrapper_telnet_server: self._wrapper_telnet_server.close() yield from self._wrapper_telnet_server.wait_closed() self.status = "stopped"
python
def stop(self): """ Stop the node process. """ if self._wrapper_telnet_server: self._wrapper_telnet_server.close() yield from self._wrapper_telnet_server.wait_closed() self.status = "stopped"
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "_wrapper_telnet_server", ":", "self", ".", "_wrapper_telnet_server", ".", "close", "(", ")", "yield", "from", "self", ".", "_wrapper_telnet_server", ".", "wait_closed", "(", ")", "self", ".", "status"...
Stop the node process.
[ "Stop", "the", "node", "process", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L286-L293
train
221,370
GNS3/gns3-server
gns3server/compute/base_node.py
BaseNode.close
def close(self): """ Close the node process. """ if self._closed: return False log.info("{module}: '{name}' [{id}]: is closing".format(module=self.manager.module_name, name=self.name, id=self.id)) if self._console: self._manager.port_manager.release_tcp_port(self._console, self._project) self._console = None if self._wrap_console: self._manager.port_manager.release_tcp_port(self._internal_console_port, self._project) self._internal_console_port = None if self._aux: self._manager.port_manager.release_tcp_port(self._aux, self._project) self._aux = None self._closed = True return True
python
def close(self): """ Close the node process. """ if self._closed: return False log.info("{module}: '{name}' [{id}]: is closing".format(module=self.manager.module_name, name=self.name, id=self.id)) if self._console: self._manager.port_manager.release_tcp_port(self._console, self._project) self._console = None if self._wrap_console: self._manager.port_manager.release_tcp_port(self._internal_console_port, self._project) self._internal_console_port = None if self._aux: self._manager.port_manager.release_tcp_port(self._aux, self._project) self._aux = None self._closed = True return True
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_closed", ":", "return", "False", "log", ".", "info", "(", "\"{module}: '{name}' [{id}]: is closing\"", ".", "format", "(", "module", "=", "self", ".", "manager", ".", "module_name", ",", "name", "...
Close the node process.
[ "Close", "the", "node", "process", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L303-L327
train
221,371
GNS3/gns3-server
gns3server/compute/base_node.py
BaseNode.start_wrap_console
def start_wrap_console(self): """ Start a telnet proxy for the console allowing multiple client connected at the same time """ if not self._wrap_console or self._console_type != "telnet": return remaining_trial = 60 while True: try: (reader, writer) = yield from asyncio.open_connection(host="127.0.0.1", port=self._internal_console_port) break except (OSError, ConnectionRefusedError) as e: if remaining_trial <= 0: raise e yield from asyncio.sleep(0.1) remaining_trial -= 1 yield from AsyncioTelnetServer.write_client_intro(writer, echo=True) server = AsyncioTelnetServer(reader=reader, writer=writer, binary=True, echo=True) self._wrapper_telnet_server = yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console)
python
def start_wrap_console(self): """ Start a telnet proxy for the console allowing multiple client connected at the same time """ if not self._wrap_console or self._console_type != "telnet": return remaining_trial = 60 while True: try: (reader, writer) = yield from asyncio.open_connection(host="127.0.0.1", port=self._internal_console_port) break except (OSError, ConnectionRefusedError) as e: if remaining_trial <= 0: raise e yield from asyncio.sleep(0.1) remaining_trial -= 1 yield from AsyncioTelnetServer.write_client_intro(writer, echo=True) server = AsyncioTelnetServer(reader=reader, writer=writer, binary=True, echo=True) self._wrapper_telnet_server = yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console)
[ "def", "start_wrap_console", "(", "self", ")", ":", "if", "not", "self", ".", "_wrap_console", "or", "self", ".", "_console_type", "!=", "\"telnet\"", ":", "return", "remaining_trial", "=", "60", "while", "True", ":", "try", ":", "(", "reader", ",", "write...
Start a telnet proxy for the console allowing multiple client connected at the same time
[ "Start", "a", "telnet", "proxy", "for", "the", "console", "allowing", "multiple", "client", "connected", "at", "the", "same", "time" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L330-L349
train
221,372
GNS3/gns3-server
gns3server/compute/base_node.py
BaseNode.aux
def aux(self, aux): """ Changes the aux port :params aux: Console port (integer) or None to free the port """ if aux == self._aux: return if self._aux: self._manager.port_manager.release_tcp_port(self._aux, self._project) self._aux = None if aux is not None: self._aux = self._manager.port_manager.reserve_tcp_port(aux, self._project) log.info("{module}: '{name}' [{id}]: aux port set to {port}".format(module=self.manager.module_name, name=self.name, id=self.id, port=aux))
python
def aux(self, aux): """ Changes the aux port :params aux: Console port (integer) or None to free the port """ if aux == self._aux: return if self._aux: self._manager.port_manager.release_tcp_port(self._aux, self._project) self._aux = None if aux is not None: self._aux = self._manager.port_manager.reserve_tcp_port(aux, self._project) log.info("{module}: '{name}' [{id}]: aux port set to {port}".format(module=self.manager.module_name, name=self.name, id=self.id, port=aux))
[ "def", "aux", "(", "self", ",", "aux", ")", ":", "if", "aux", "==", "self", ".", "_aux", ":", "return", "if", "self", ".", "_aux", ":", "self", ".", "_manager", ".", "port_manager", ".", "release_tcp_port", "(", "self", ".", "_aux", ",", "self", "....
Changes the aux port :params aux: Console port (integer) or None to free the port
[ "Changes", "the", "aux", "port" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L376-L394
train
221,373
GNS3/gns3-server
gns3server/compute/base_node.py
BaseNode.console
def console(self, console): """ Changes the console port :params console: Console port (integer) or None to free the port """ if console == self._console: return if self._console_type == "vnc" and console is not None and console < 5900: raise NodeError("VNC console require a port superior or equal to 5900 currently it's {}".format(console)) if self._console: self._manager.port_manager.release_tcp_port(self._console, self._project) self._console = None if console is not None: if self.console_type == "vnc": self._console = self._manager.port_manager.reserve_tcp_port(console, self._project, port_range_start=5900, port_range_end=6000) else: self._console = self._manager.port_manager.reserve_tcp_port(console, self._project) log.info("{module}: '{name}' [{id}]: console port set to {port}".format(module=self.manager.module_name, name=self.name, id=self.id, port=console))
python
def console(self, console): """ Changes the console port :params console: Console port (integer) or None to free the port """ if console == self._console: return if self._console_type == "vnc" and console is not None and console < 5900: raise NodeError("VNC console require a port superior or equal to 5900 currently it's {}".format(console)) if self._console: self._manager.port_manager.release_tcp_port(self._console, self._project) self._console = None if console is not None: if self.console_type == "vnc": self._console = self._manager.port_manager.reserve_tcp_port(console, self._project, port_range_start=5900, port_range_end=6000) else: self._console = self._manager.port_manager.reserve_tcp_port(console, self._project) log.info("{module}: '{name}' [{id}]: console port set to {port}".format(module=self.manager.module_name, name=self.name, id=self.id, port=console))
[ "def", "console", "(", "self", ",", "console", ")", ":", "if", "console", "==", "self", ".", "_console", ":", "return", "if", "self", ".", "_console_type", "==", "\"vnc\"", "and", "console", "is", "not", "None", "and", "console", "<", "5900", ":", "rai...
Changes the console port :params console: Console port (integer) or None to free the port
[ "Changes", "the", "console", "port" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L407-L432
train
221,374
GNS3/gns3-server
gns3server/compute/base_node.py
BaseNode.console_type
def console_type(self, console_type): """ Sets the console type for this node. :param console_type: console type (string) """ if console_type != self._console_type: # get a new port if the console type change self._manager.port_manager.release_tcp_port(self._console, self._project) if console_type == "vnc": # VNC is a special case and the range must be 5900-6000 self._console = self._manager.port_manager.get_free_tcp_port(self._project, 5900, 6000) else: self._console = self._manager.port_manager.get_free_tcp_port(self._project) self._console_type = console_type log.info("{module}: '{name}' [{id}]: console type set to {console_type}".format(module=self.manager.module_name, name=self.name, id=self.id, console_type=console_type))
python
def console_type(self, console_type): """ Sets the console type for this node. :param console_type: console type (string) """ if console_type != self._console_type: # get a new port if the console type change self._manager.port_manager.release_tcp_port(self._console, self._project) if console_type == "vnc": # VNC is a special case and the range must be 5900-6000 self._console = self._manager.port_manager.get_free_tcp_port(self._project, 5900, 6000) else: self._console = self._manager.port_manager.get_free_tcp_port(self._project) self._console_type = console_type log.info("{module}: '{name}' [{id}]: console type set to {console_type}".format(module=self.manager.module_name, name=self.name, id=self.id, console_type=console_type))
[ "def", "console_type", "(", "self", ",", "console_type", ")", ":", "if", "console_type", "!=", "self", ".", "_console_type", ":", "# get a new port if the console type change", "self", ".", "_manager", ".", "port_manager", ".", "release_tcp_port", "(", "self", ".", ...
Sets the console type for this node. :param console_type: console type (string)
[ "Sets", "the", "console", "type", "for", "this", "node", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L445-L465
train
221,375
GNS3/gns3-server
gns3server/compute/base_node.py
BaseNode.ubridge
def ubridge(self): """ Returns the uBridge hypervisor. :returns: instance of uBridge """ if self._ubridge_hypervisor and not self._ubridge_hypervisor.is_running(): self._ubridge_hypervisor = None return self._ubridge_hypervisor
python
def ubridge(self): """ Returns the uBridge hypervisor. :returns: instance of uBridge """ if self._ubridge_hypervisor and not self._ubridge_hypervisor.is_running(): self._ubridge_hypervisor = None return self._ubridge_hypervisor
[ "def", "ubridge", "(", "self", ")", ":", "if", "self", ".", "_ubridge_hypervisor", "and", "not", "self", ".", "_ubridge_hypervisor", ".", "is_running", "(", ")", ":", "self", ".", "_ubridge_hypervisor", "=", "None", "return", "self", ".", "_ubridge_hypervisor"...
Returns the uBridge hypervisor. :returns: instance of uBridge
[ "Returns", "the", "uBridge", "hypervisor", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L468-L477
train
221,376
GNS3/gns3-server
gns3server/compute/base_node.py
BaseNode.ubridge_path
def ubridge_path(self): """ Returns the uBridge executable path. :returns: path to uBridge """ path = self._manager.config.get_section_config("Server").get("ubridge_path", "ubridge") path = shutil.which(path) return path
python
def ubridge_path(self): """ Returns the uBridge executable path. :returns: path to uBridge """ path = self._manager.config.get_section_config("Server").get("ubridge_path", "ubridge") path = shutil.which(path) return path
[ "def", "ubridge_path", "(", "self", ")", ":", "path", "=", "self", ".", "_manager", ".", "config", ".", "get_section_config", "(", "\"Server\"", ")", ".", "get", "(", "\"ubridge_path\"", ",", "\"ubridge\"", ")", "path", "=", "shutil", ".", "which", "(", ...
Returns the uBridge executable path. :returns: path to uBridge
[ "Returns", "the", "uBridge", "executable", "path", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L490-L499
train
221,377
GNS3/gns3-server
gns3server/compute/base_node.py
BaseNode._ubridge_send
def _ubridge_send(self, command): """ Sends a command to uBridge hypervisor. :param command: command to send """ if not self._ubridge_hypervisor or not self._ubridge_hypervisor.is_running(): yield from self._start_ubridge() if not self._ubridge_hypervisor or not self._ubridge_hypervisor.is_running(): raise NodeError("Cannot send command '{}': uBridge is not running".format(command)) try: yield from self._ubridge_hypervisor.send(command) except UbridgeError as e: raise UbridgeError("{}: {}".format(e, self._ubridge_hypervisor.read_stdout()))
python
def _ubridge_send(self, command): """ Sends a command to uBridge hypervisor. :param command: command to send """ if not self._ubridge_hypervisor or not self._ubridge_hypervisor.is_running(): yield from self._start_ubridge() if not self._ubridge_hypervisor or not self._ubridge_hypervisor.is_running(): raise NodeError("Cannot send command '{}': uBridge is not running".format(command)) try: yield from self._ubridge_hypervisor.send(command) except UbridgeError as e: raise UbridgeError("{}: {}".format(e, self._ubridge_hypervisor.read_stdout()))
[ "def", "_ubridge_send", "(", "self", ",", "command", ")", ":", "if", "not", "self", ".", "_ubridge_hypervisor", "or", "not", "self", ".", "_ubridge_hypervisor", ".", "is_running", "(", ")", ":", "yield", "from", "self", ".", "_start_ubridge", "(", ")", "if...
Sends a command to uBridge hypervisor. :param command: command to send
[ "Sends", "a", "command", "to", "uBridge", "hypervisor", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L502-L516
train
221,378
GNS3/gns3-server
gns3server/compute/base_node.py
BaseNode._stop_ubridge
def _stop_ubridge(self): """ Stops uBridge. """ if self._ubridge_hypervisor and self._ubridge_hypervisor.is_running(): log.info("Stopping uBridge hypervisor {}:{}".format(self._ubridge_hypervisor.host, self._ubridge_hypervisor.port)) yield from self._ubridge_hypervisor.stop() self._ubridge_hypervisor = None
python
def _stop_ubridge(self): """ Stops uBridge. """ if self._ubridge_hypervisor and self._ubridge_hypervisor.is_running(): log.info("Stopping uBridge hypervisor {}:{}".format(self._ubridge_hypervisor.host, self._ubridge_hypervisor.port)) yield from self._ubridge_hypervisor.stop() self._ubridge_hypervisor = None
[ "def", "_stop_ubridge", "(", "self", ")", ":", "if", "self", ".", "_ubridge_hypervisor", "and", "self", ".", "_ubridge_hypervisor", ".", "is_running", "(", ")", ":", "log", ".", "info", "(", "\"Stopping uBridge hypervisor {}:{}\"", ".", "format", "(", "self", ...
Stops uBridge.
[ "Stops", "uBridge", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L545-L553
train
221,379
GNS3/gns3-server
gns3server/compute/base_node.py
BaseNode.add_ubridge_udp_connection
def add_ubridge_udp_connection(self, bridge_name, source_nio, destination_nio): """ Creates an UDP connection in uBridge. :param bridge_name: bridge name in uBridge :param source_nio: source NIO instance :param destination_nio: destination NIO instance """ yield from self._ubridge_send("bridge create {name}".format(name=bridge_name)) if not isinstance(destination_nio, NIOUDP): raise NodeError("Destination NIO is not UDP") yield from self._ubridge_send('bridge add_nio_udp {name} {lport} {rhost} {rport}'.format(name=bridge_name, lport=source_nio.lport, rhost=source_nio.rhost, rport=source_nio.rport)) yield from self._ubridge_send('bridge add_nio_udp {name} {lport} {rhost} {rport}'.format(name=bridge_name, lport=destination_nio.lport, rhost=destination_nio.rhost, rport=destination_nio.rport)) if destination_nio.capturing: yield from self._ubridge_send('bridge start_capture {name} "{pcap_file}"'.format(name=bridge_name, pcap_file=destination_nio.pcap_output_file)) yield from self._ubridge_send('bridge start {name}'.format(name=bridge_name)) yield from self._ubridge_apply_filters(bridge_name, destination_nio.filters)
python
def add_ubridge_udp_connection(self, bridge_name, source_nio, destination_nio): """ Creates an UDP connection in uBridge. :param bridge_name: bridge name in uBridge :param source_nio: source NIO instance :param destination_nio: destination NIO instance """ yield from self._ubridge_send("bridge create {name}".format(name=bridge_name)) if not isinstance(destination_nio, NIOUDP): raise NodeError("Destination NIO is not UDP") yield from self._ubridge_send('bridge add_nio_udp {name} {lport} {rhost} {rport}'.format(name=bridge_name, lport=source_nio.lport, rhost=source_nio.rhost, rport=source_nio.rport)) yield from self._ubridge_send('bridge add_nio_udp {name} {lport} {rhost} {rport}'.format(name=bridge_name, lport=destination_nio.lport, rhost=destination_nio.rhost, rport=destination_nio.rport)) if destination_nio.capturing: yield from self._ubridge_send('bridge start_capture {name} "{pcap_file}"'.format(name=bridge_name, pcap_file=destination_nio.pcap_output_file)) yield from self._ubridge_send('bridge start {name}'.format(name=bridge_name)) yield from self._ubridge_apply_filters(bridge_name, destination_nio.filters)
[ "def", "add_ubridge_udp_connection", "(", "self", ",", "bridge_name", ",", "source_nio", ",", "destination_nio", ")", ":", "yield", "from", "self", ".", "_ubridge_send", "(", "\"bridge create {name}\"", ".", "format", "(", "name", "=", "bridge_name", ")", ")", "...
Creates an UDP connection in uBridge. :param bridge_name: bridge name in uBridge :param source_nio: source NIO instance :param destination_nio: destination NIO instance
[ "Creates", "an", "UDP", "connection", "in", "uBridge", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L556-L585
train
221,380
GNS3/gns3-server
gns3server/compute/base_node.py
BaseNode._ubridge_apply_filters
def _ubridge_apply_filters(self, bridge_name, filters): """ Apply packet filters :param bridge_name: bridge name in uBridge :param filters: Array of filter dictionary """ yield from self._ubridge_send('bridge reset_packet_filters ' + bridge_name) for packet_filter in self._build_filter_list(filters): cmd = 'bridge add_packet_filter {} {}'.format(bridge_name, packet_filter) try: yield from self._ubridge_send(cmd) except UbridgeError as e: match = re.search("Cannot compile filter '(.*)': syntax error", str(e)) if match: message = "Warning: ignoring BPF packet filter '{}' due to syntax error".format(self.name, match.group(1)) log.warning(message) self.project.emit("log.warning", {"message": message}) else: raise
python
def _ubridge_apply_filters(self, bridge_name, filters): """ Apply packet filters :param bridge_name: bridge name in uBridge :param filters: Array of filter dictionary """ yield from self._ubridge_send('bridge reset_packet_filters ' + bridge_name) for packet_filter in self._build_filter_list(filters): cmd = 'bridge add_packet_filter {} {}'.format(bridge_name, packet_filter) try: yield from self._ubridge_send(cmd) except UbridgeError as e: match = re.search("Cannot compile filter '(.*)': syntax error", str(e)) if match: message = "Warning: ignoring BPF packet filter '{}' due to syntax error".format(self.name, match.group(1)) log.warning(message) self.project.emit("log.warning", {"message": message}) else: raise
[ "def", "_ubridge_apply_filters", "(", "self", ",", "bridge_name", ",", "filters", ")", ":", "yield", "from", "self", ".", "_ubridge_send", "(", "'bridge reset_packet_filters '", "+", "bridge_name", ")", "for", "packet_filter", "in", "self", ".", "_build_filter_list"...
Apply packet filters :param bridge_name: bridge name in uBridge :param filters: Array of filter dictionary
[ "Apply", "packet", "filters" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L600-L619
train
221,381
GNS3/gns3-server
gns3server/compute/base_node.py
BaseNode._add_ubridge_ethernet_connection
def _add_ubridge_ethernet_connection(self, bridge_name, ethernet_interface, block_host_traffic=False): """ Creates a connection with an Ethernet interface in uBridge. :param bridge_name: bridge name in uBridge :param ethernet_interface: Ethernet interface name :param block_host_traffic: block network traffic originating from the host OS (Windows only) """ if sys.platform.startswith("linux") and block_host_traffic is False: # on Linux we use RAW sockets by default excepting if host traffic must be blocked yield from self._ubridge_send('bridge add_nio_linux_raw {name} "{interface}"'.format(name=bridge_name, interface=ethernet_interface)) elif sys.platform.startswith("win"): # on Windows we use Winpcap/Npcap windows_interfaces = interfaces() npf_id = None source_mac = None for interface in windows_interfaces: # Winpcap/Npcap uses a NPF ID to identify an interface on Windows if "netcard" in interface and ethernet_interface in interface["netcard"]: npf_id = interface["id"] source_mac = interface["mac_address"] elif ethernet_interface in interface["name"]: npf_id = interface["id"] source_mac = interface["mac_address"] if npf_id: yield from self._ubridge_send('bridge add_nio_ethernet {name} "{interface}"'.format(name=bridge_name, interface=npf_id)) else: raise NodeError("Could not find NPF id for interface {}".format(ethernet_interface)) if block_host_traffic: if source_mac: yield from self._ubridge_send('bridge set_pcap_filter {name} "not ether src {mac}"'.format(name=bridge_name, mac=source_mac)) log.info('PCAP filter applied on "{interface}" for source MAC {mac}'.format(interface=ethernet_interface, mac=source_mac)) else: log.warning("Could not block host network traffic on {} (no MAC address found)".format(ethernet_interface)) else: # on other platforms we just rely on the pcap library yield from self._ubridge_send('bridge add_nio_ethernet {name} "{interface}"'.format(name=bridge_name, interface=ethernet_interface)) source_mac = None for interface in interfaces(): if interface["name"] == ethernet_interface: source_mac = interface["mac_address"] if source_mac: yield from self._ubridge_send('bridge set_pcap_filter {name} "not ether src {mac}"'.format(name=bridge_name, mac=source_mac)) log.info('PCAP filter applied on "{interface}" for source MAC {mac}'.format(interface=ethernet_interface, mac=source_mac))
python
def _add_ubridge_ethernet_connection(self, bridge_name, ethernet_interface, block_host_traffic=False): """ Creates a connection with an Ethernet interface in uBridge. :param bridge_name: bridge name in uBridge :param ethernet_interface: Ethernet interface name :param block_host_traffic: block network traffic originating from the host OS (Windows only) """ if sys.platform.startswith("linux") and block_host_traffic is False: # on Linux we use RAW sockets by default excepting if host traffic must be blocked yield from self._ubridge_send('bridge add_nio_linux_raw {name} "{interface}"'.format(name=bridge_name, interface=ethernet_interface)) elif sys.platform.startswith("win"): # on Windows we use Winpcap/Npcap windows_interfaces = interfaces() npf_id = None source_mac = None for interface in windows_interfaces: # Winpcap/Npcap uses a NPF ID to identify an interface on Windows if "netcard" in interface and ethernet_interface in interface["netcard"]: npf_id = interface["id"] source_mac = interface["mac_address"] elif ethernet_interface in interface["name"]: npf_id = interface["id"] source_mac = interface["mac_address"] if npf_id: yield from self._ubridge_send('bridge add_nio_ethernet {name} "{interface}"'.format(name=bridge_name, interface=npf_id)) else: raise NodeError("Could not find NPF id for interface {}".format(ethernet_interface)) if block_host_traffic: if source_mac: yield from self._ubridge_send('bridge set_pcap_filter {name} "not ether src {mac}"'.format(name=bridge_name, mac=source_mac)) log.info('PCAP filter applied on "{interface}" for source MAC {mac}'.format(interface=ethernet_interface, mac=source_mac)) else: log.warning("Could not block host network traffic on {} (no MAC address found)".format(ethernet_interface)) else: # on other platforms we just rely on the pcap library yield from self._ubridge_send('bridge add_nio_ethernet {name} "{interface}"'.format(name=bridge_name, interface=ethernet_interface)) source_mac = None for interface in interfaces(): if interface["name"] == ethernet_interface: source_mac = interface["mac_address"] if source_mac: yield from self._ubridge_send('bridge set_pcap_filter {name} "not ether src {mac}"'.format(name=bridge_name, mac=source_mac)) log.info('PCAP filter applied on "{interface}" for source MAC {mac}'.format(interface=ethernet_interface, mac=source_mac))
[ "def", "_add_ubridge_ethernet_connection", "(", "self", ",", "bridge_name", ",", "ethernet_interface", ",", "block_host_traffic", "=", "False", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "\"linux\"", ")", "and", "block_host_traffic", "is", "Fa...
Creates a connection with an Ethernet interface in uBridge. :param bridge_name: bridge name in uBridge :param ethernet_interface: Ethernet interface name :param block_host_traffic: block network traffic originating from the host OS (Windows only)
[ "Creates", "a", "connection", "with", "an", "Ethernet", "interface", "in", "uBridge", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L643-L689
train
221,382
GNS3/gns3-server
gns3server/compute/base_node.py
BaseNode.check_available_ram
def check_available_ram(self, requested_ram): """ Sends a warning notification if there is not enough RAM on the system to allocate requested RAM. :param requested_ram: requested amount of RAM in MB """ available_ram = int(psutil.virtual_memory().available / (1024 * 1024)) percentage_left = psutil.virtual_memory().percent if requested_ram > available_ram: message = '"{}" requires {}MB of RAM to run but there is only {}MB - {}% of RAM left on "{}"'.format(self.name, requested_ram, available_ram, percentage_left, platform.node()) self.project.emit("log.warning", {"message": message})
python
def check_available_ram(self, requested_ram): """ Sends a warning notification if there is not enough RAM on the system to allocate requested RAM. :param requested_ram: requested amount of RAM in MB """ available_ram = int(psutil.virtual_memory().available / (1024 * 1024)) percentage_left = psutil.virtual_memory().percent if requested_ram > available_ram: message = '"{}" requires {}MB of RAM to run but there is only {}MB - {}% of RAM left on "{}"'.format(self.name, requested_ram, available_ram, percentage_left, platform.node()) self.project.emit("log.warning", {"message": message})
[ "def", "check_available_ram", "(", "self", ",", "requested_ram", ")", ":", "available_ram", "=", "int", "(", "psutil", ".", "virtual_memory", "(", ")", ".", "available", "/", "(", "1024", "*", "1024", ")", ")", "percentage_left", "=", "psutil", ".", "virtu...
Sends a warning notification if there is not enough RAM on the system to allocate requested RAM. :param requested_ram: requested amount of RAM in MB
[ "Sends", "a", "warning", "notification", "if", "there", "is", "not", "enough", "RAM", "on", "the", "system", "to", "allocate", "requested", "RAM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L722-L737
train
221,383
GNS3/gns3-server
gns3server/compute/qemu/qcow2.py
Qcow2.backing_file
def backing_file(self): """ When using linked clone this will return the path to the base image :returns: None if it's not a linked clone, the path otherwise """ with open(self._path, 'rb') as f: f.seek(self.backing_file_offset) content = f.read(self.backing_file_size) path = content.decode() if len(path) == 0: return None return path
python
def backing_file(self): """ When using linked clone this will return the path to the base image :returns: None if it's not a linked clone, the path otherwise """ with open(self._path, 'rb') as f: f.seek(self.backing_file_offset) content = f.read(self.backing_file_size) path = content.decode() if len(path) == 0: return None return path
[ "def", "backing_file", "(", "self", ")", ":", "with", "open", "(", "self", ".", "_path", ",", "'rb'", ")", "as", "f", ":", "f", ".", "seek", "(", "self", ".", "backing_file_offset", ")", "content", "=", "f", ".", "read", "(", "self", ".", "backing_...
When using linked clone this will return the path to the base image :returns: None if it's not a linked clone, the path otherwise
[ "When", "using", "linked", "clone", "this", "will", "return", "the", "path", "to", "the", "base", "image" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qcow2.py#L74-L88
train
221,384
GNS3/gns3-server
gns3server/compute/qemu/qcow2.py
Qcow2.rebase
def rebase(self, qemu_img, base_image): """ Rebase a linked clone in order to use the correct disk :param qemu_img: Path to the qemu-img binary :param base_image: Path to the base image """ if not os.path.exists(base_image): raise FileNotFoundError(base_image) command = [qemu_img, "rebase", "-u", "-b", base_image, self._path] process = yield from asyncio.create_subprocess_exec(*command) retcode = yield from process.wait() if retcode != 0: raise Qcow2Error("Could not rebase the image") self._reload()
python
def rebase(self, qemu_img, base_image): """ Rebase a linked clone in order to use the correct disk :param qemu_img: Path to the qemu-img binary :param base_image: Path to the base image """ if not os.path.exists(base_image): raise FileNotFoundError(base_image) command = [qemu_img, "rebase", "-u", "-b", base_image, self._path] process = yield from asyncio.create_subprocess_exec(*command) retcode = yield from process.wait() if retcode != 0: raise Qcow2Error("Could not rebase the image") self._reload()
[ "def", "rebase", "(", "self", ",", "qemu_img", ",", "base_image", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "base_image", ")", ":", "raise", "FileNotFoundError", "(", "base_image", ")", "command", "=", "[", "qemu_img", ",", "\"rebase\...
Rebase a linked clone in order to use the correct disk :param qemu_img: Path to the qemu-img binary :param base_image: Path to the base image
[ "Rebase", "a", "linked", "clone", "in", "order", "to", "use", "the", "correct", "disk" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qcow2.py#L91-L106
train
221,385
GNS3/gns3-server
gns3server/utils/qt.py
qt_font_to_style
def qt_font_to_style(font, color): """ Convert a Qt font to CSS style """ if font is None: font = "TypeWriter,10,-1,5,75,0,0,0,0,0" font_info = font.split(",") style = "font-family: {};font-size: {};".format(font_info[0], font_info[1]) if font_info[4] == "75": style += "font-weight: bold;" if font_info[5] == "1": style += "font-style: italic;" if color is None: color = "000000" if len(color) == 9: style += "fill: #" + color[-6:] + ";" style += "fill-opacity: {};".format(round(1.0 / 255 * int(color[:3][-2:], base=16), 2)) else: style += "fill: #" + color[-6:] + ";" style += "fill-opacity: {};".format(1.0) return style
python
def qt_font_to_style(font, color): """ Convert a Qt font to CSS style """ if font is None: font = "TypeWriter,10,-1,5,75,0,0,0,0,0" font_info = font.split(",") style = "font-family: {};font-size: {};".format(font_info[0], font_info[1]) if font_info[4] == "75": style += "font-weight: bold;" if font_info[5] == "1": style += "font-style: italic;" if color is None: color = "000000" if len(color) == 9: style += "fill: #" + color[-6:] + ";" style += "fill-opacity: {};".format(round(1.0 / 255 * int(color[:3][-2:], base=16), 2)) else: style += "fill: #" + color[-6:] + ";" style += "fill-opacity: {};".format(1.0) return style
[ "def", "qt_font_to_style", "(", "font", ",", "color", ")", ":", "if", "font", "is", "None", ":", "font", "=", "\"TypeWriter,10,-1,5,75,0,0,0,0,0\"", "font_info", "=", "font", ".", "split", "(", "\",\"", ")", "style", "=", "\"font-family: {};font-size: {};\"", "....
Convert a Qt font to CSS style
[ "Convert", "a", "Qt", "font", "to", "CSS", "style" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/qt.py#L23-L44
train
221,386
GNS3/gns3-server
gns3server/controller/gns3vm/remote_gns3_vm.py
RemoteGNS3VM.list
def list(self): """ List all VMs """ res = [] for compute in self._controller.computes.values(): if compute.id not in ["local", "vm"]: res.append({"vmname": compute.name}) return res
python
def list(self): """ List all VMs """ res = [] for compute in self._controller.computes.values(): if compute.id not in ["local", "vm"]: res.append({"vmname": compute.name}) return res
[ "def", "list", "(", "self", ")", ":", "res", "=", "[", "]", "for", "compute", "in", "self", ".", "_controller", ".", "computes", ".", "values", "(", ")", ":", "if", "compute", ".", "id", "not", "in", "[", "\"local\"", ",", "\"vm\"", "]", ":", "re...
List all VMs
[ "List", "all", "VMs" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/remote_gns3_vm.py#L36-L46
train
221,387
GNS3/gns3-server
gns3server/compute/dynamips/__init__.py
Dynamips.take_dynamips_id
def take_dynamips_id(self, project_id, dynamips_id): """ Reserve a dynamips id or raise an error :param project_id: UUID of the project :param dynamips_id: Asked id """ self._dynamips_ids.setdefault(project_id, set()) if dynamips_id in self._dynamips_ids[project_id]: raise DynamipsError("Dynamips identifier {} is already used by another router".format(dynamips_id)) self._dynamips_ids[project_id].add(dynamips_id)
python
def take_dynamips_id(self, project_id, dynamips_id): """ Reserve a dynamips id or raise an error :param project_id: UUID of the project :param dynamips_id: Asked id """ self._dynamips_ids.setdefault(project_id, set()) if dynamips_id in self._dynamips_ids[project_id]: raise DynamipsError("Dynamips identifier {} is already used by another router".format(dynamips_id)) self._dynamips_ids[project_id].add(dynamips_id)
[ "def", "take_dynamips_id", "(", "self", ",", "project_id", ",", "dynamips_id", ")", ":", "self", ".", "_dynamips_ids", ".", "setdefault", "(", "project_id", ",", "set", "(", ")", ")", "if", "dynamips_id", "in", "self", ".", "_dynamips_ids", "[", "project_id"...
Reserve a dynamips id or raise an error :param project_id: UUID of the project :param dynamips_id: Asked id
[ "Reserve", "a", "dynamips", "id", "or", "raise", "an", "error" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/__init__.py#L145-L155
train
221,388
GNS3/gns3-server
gns3server/compute/dynamips/__init__.py
Dynamips.release_dynamips_id
def release_dynamips_id(self, project_id, dynamips_id): """ A Dynamips id can be reused by another VM :param project_id: UUID of the project :param dynamips_id: Asked id """ self._dynamips_ids.setdefault(project_id, set()) if dynamips_id in self._dynamips_ids[project_id]: self._dynamips_ids[project_id].remove(dynamips_id)
python
def release_dynamips_id(self, project_id, dynamips_id): """ A Dynamips id can be reused by another VM :param project_id: UUID of the project :param dynamips_id: Asked id """ self._dynamips_ids.setdefault(project_id, set()) if dynamips_id in self._dynamips_ids[project_id]: self._dynamips_ids[project_id].remove(dynamips_id)
[ "def", "release_dynamips_id", "(", "self", ",", "project_id", ",", "dynamips_id", ")", ":", "self", ".", "_dynamips_ids", ".", "setdefault", "(", "project_id", ",", "set", "(", ")", ")", "if", "dynamips_id", "in", "self", ".", "_dynamips_ids", "[", "project_...
A Dynamips id can be reused by another VM :param project_id: UUID of the project :param dynamips_id: Asked id
[ "A", "Dynamips", "id", "can", "be", "reused", "by", "another", "VM" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/__init__.py#L157-L166
train
221,389
GNS3/gns3-server
gns3server/compute/dynamips/__init__.py
Dynamips.project_closing
def project_closing(self, project): """ Called when a project is about to be closed. :param project: Project instance """ yield from super().project_closing(project) # delete the Dynamips devices corresponding to the project tasks = [] for device in self._devices.values(): if device.project.id == project.id: tasks.append(asyncio.async(device.delete())) if tasks: done, _ = yield from asyncio.wait(tasks) for future in done: try: future.result() except (Exception, GeneratorExit) as e: log.error("Could not delete device {}".format(e), exc_info=1)
python
def project_closing(self, project): """ Called when a project is about to be closed. :param project: Project instance """ yield from super().project_closing(project) # delete the Dynamips devices corresponding to the project tasks = [] for device in self._devices.values(): if device.project.id == project.id: tasks.append(asyncio.async(device.delete())) if tasks: done, _ = yield from asyncio.wait(tasks) for future in done: try: future.result() except (Exception, GeneratorExit) as e: log.error("Could not delete device {}".format(e), exc_info=1)
[ "def", "project_closing", "(", "self", ",", "project", ")", ":", "yield", "from", "super", "(", ")", ".", "project_closing", "(", "project", ")", "# delete the Dynamips devices corresponding to the project", "tasks", "=", "[", "]", "for", "device", "in", "self", ...
Called when a project is about to be closed. :param project: Project instance
[ "Called", "when", "a", "project", "is", "about", "to", "be", "closed", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/__init__.py#L187-L207
train
221,390
GNS3/gns3-server
gns3server/compute/dynamips/__init__.py
Dynamips.start_new_hypervisor
def start_new_hypervisor(self, working_dir=None): """ Creates a new Dynamips process and start it. :param working_dir: working directory :returns: the new hypervisor instance """ if not self._dynamips_path: self.find_dynamips() if not working_dir: working_dir = tempfile.gettempdir() # FIXME: hypervisor should always listen to 127.0.0.1 # See https://github.com/GNS3/dynamips/issues/62 server_config = self.config.get_section_config("Server") server_host = server_config.get("host") try: info = socket.getaddrinfo(server_host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE) if not info: raise DynamipsError("getaddrinfo returns an empty list on {}".format(server_host)) for res in info: af, socktype, proto, _, sa = res # let the OS find an unused port for the Dynamips hypervisor with socket.socket(af, socktype, proto) as sock: sock.bind(sa) port = sock.getsockname()[1] break except OSError as e: raise DynamipsError("Could not find free port for the Dynamips hypervisor: {}".format(e)) port_manager = PortManager.instance() hypervisor = Hypervisor(self._dynamips_path, working_dir, server_host, port, port_manager.console_host) log.info("Creating new hypervisor {}:{} with working directory {}".format(hypervisor.host, hypervisor.port, working_dir)) yield from hypervisor.start() log.info("Hypervisor {}:{} has successfully started".format(hypervisor.host, hypervisor.port)) yield from hypervisor.connect() if parse_version(hypervisor.version) < parse_version('0.2.11'): raise DynamipsError("Dynamips version must be >= 0.2.11, detected version is {}".format(hypervisor.version)) return hypervisor
python
def start_new_hypervisor(self, working_dir=None): """ Creates a new Dynamips process and start it. :param working_dir: working directory :returns: the new hypervisor instance """ if not self._dynamips_path: self.find_dynamips() if not working_dir: working_dir = tempfile.gettempdir() # FIXME: hypervisor should always listen to 127.0.0.1 # See https://github.com/GNS3/dynamips/issues/62 server_config = self.config.get_section_config("Server") server_host = server_config.get("host") try: info = socket.getaddrinfo(server_host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE) if not info: raise DynamipsError("getaddrinfo returns an empty list on {}".format(server_host)) for res in info: af, socktype, proto, _, sa = res # let the OS find an unused port for the Dynamips hypervisor with socket.socket(af, socktype, proto) as sock: sock.bind(sa) port = sock.getsockname()[1] break except OSError as e: raise DynamipsError("Could not find free port for the Dynamips hypervisor: {}".format(e)) port_manager = PortManager.instance() hypervisor = Hypervisor(self._dynamips_path, working_dir, server_host, port, port_manager.console_host) log.info("Creating new hypervisor {}:{} with working directory {}".format(hypervisor.host, hypervisor.port, working_dir)) yield from hypervisor.start() log.info("Hypervisor {}:{} has successfully started".format(hypervisor.host, hypervisor.port)) yield from hypervisor.connect() if parse_version(hypervisor.version) < parse_version('0.2.11'): raise DynamipsError("Dynamips version must be >= 0.2.11, detected version is {}".format(hypervisor.version)) return hypervisor
[ "def", "start_new_hypervisor", "(", "self", ",", "working_dir", "=", "None", ")", ":", "if", "not", "self", ".", "_dynamips_path", ":", "self", ".", "find_dynamips", "(", ")", "if", "not", "working_dir", ":", "working_dir", "=", "tempfile", ".", "gettempdir"...
Creates a new Dynamips process and start it. :param working_dir: working directory :returns: the new hypervisor instance
[ "Creates", "a", "new", "Dynamips", "process", "and", "start", "it", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/__init__.py#L270-L314
train
221,391
GNS3/gns3-server
gns3server/compute/dynamips/__init__.py
Dynamips._set_ghost_ios
def _set_ghost_ios(self, vm): """ Manages Ghost IOS support. :param vm: VM instance """ if not vm.mmap: raise DynamipsError("mmap support is required to enable ghost IOS support") if vm.platform == "c7200" and vm.npe == "npe-g2": log.warning("Ghost IOS is not supported for c7200 with NPE-G2") return ghost_file = vm.formatted_ghost_file() module_workdir = vm.project.module_working_directory(self.module_name.lower()) ghost_file_path = os.path.join(module_workdir, ghost_file) if ghost_file_path not in self._ghost_files: # create a new ghost IOS instance ghost_id = str(uuid4()) ghost = Router("ghost-" + ghost_file, ghost_id, vm.project, vm.manager, platform=vm.platform, hypervisor=vm.hypervisor, ghost_flag=True) try: yield from ghost.create() yield from ghost.set_image(vm.image) yield from ghost.set_ghost_status(1) yield from ghost.set_ghost_file(ghost_file_path) yield from ghost.set_ram(vm.ram) try: yield from ghost.start() yield from ghost.stop() self._ghost_files.add(ghost_file_path) except DynamipsError: raise finally: yield from ghost.clean_delete() except DynamipsError as e: log.warn("Could not create ghost instance: {}".format(e)) if vm.ghost_file != ghost_file and os.path.isfile(ghost_file_path): # set the ghost file to the router yield from vm.set_ghost_status(2) yield from vm.set_ghost_file(ghost_file_path)
python
def _set_ghost_ios(self, vm): """ Manages Ghost IOS support. :param vm: VM instance """ if not vm.mmap: raise DynamipsError("mmap support is required to enable ghost IOS support") if vm.platform == "c7200" and vm.npe == "npe-g2": log.warning("Ghost IOS is not supported for c7200 with NPE-G2") return ghost_file = vm.formatted_ghost_file() module_workdir = vm.project.module_working_directory(self.module_name.lower()) ghost_file_path = os.path.join(module_workdir, ghost_file) if ghost_file_path not in self._ghost_files: # create a new ghost IOS instance ghost_id = str(uuid4()) ghost = Router("ghost-" + ghost_file, ghost_id, vm.project, vm.manager, platform=vm.platform, hypervisor=vm.hypervisor, ghost_flag=True) try: yield from ghost.create() yield from ghost.set_image(vm.image) yield from ghost.set_ghost_status(1) yield from ghost.set_ghost_file(ghost_file_path) yield from ghost.set_ram(vm.ram) try: yield from ghost.start() yield from ghost.stop() self._ghost_files.add(ghost_file_path) except DynamipsError: raise finally: yield from ghost.clean_delete() except DynamipsError as e: log.warn("Could not create ghost instance: {}".format(e)) if vm.ghost_file != ghost_file and os.path.isfile(ghost_file_path): # set the ghost file to the router yield from vm.set_ghost_status(2) yield from vm.set_ghost_file(ghost_file_path)
[ "def", "_set_ghost_ios", "(", "self", ",", "vm", ")", ":", "if", "not", "vm", ".", "mmap", ":", "raise", "DynamipsError", "(", "\"mmap support is required to enable ghost IOS support\"", ")", "if", "vm", ".", "platform", "==", "\"c7200\"", "and", "vm", ".", "n...
Manages Ghost IOS support. :param vm: VM instance
[ "Manages", "Ghost", "IOS", "support", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/__init__.py#L398-L440
train
221,392
GNS3/gns3-server
gns3server/compute/dynamips/__init__.py
Dynamips.set_vm_configs
def set_vm_configs(self, vm, settings): """ Set VM configs from pushed content or existing config files. :param vm: VM instance :param settings: VM settings """ startup_config_content = settings.get("startup_config_content") if startup_config_content: self._create_config(vm, vm.startup_config_path, startup_config_content) private_config_content = settings.get("private_config_content") if private_config_content: self._create_config(vm, vm.private_config_path, private_config_content)
python
def set_vm_configs(self, vm, settings): """ Set VM configs from pushed content or existing config files. :param vm: VM instance :param settings: VM settings """ startup_config_content = settings.get("startup_config_content") if startup_config_content: self._create_config(vm, vm.startup_config_path, startup_config_content) private_config_content = settings.get("private_config_content") if private_config_content: self._create_config(vm, vm.private_config_path, private_config_content)
[ "def", "set_vm_configs", "(", "self", ",", "vm", ",", "settings", ")", ":", "startup_config_content", "=", "settings", ".", "get", "(", "\"startup_config_content\"", ")", "if", "startup_config_content", ":", "self", ".", "_create_config", "(", "vm", ",", "vm", ...
Set VM configs from pushed content or existing config files. :param vm: VM instance :param settings: VM settings
[ "Set", "VM", "configs", "from", "pushed", "content", "or", "existing", "config", "files", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/__init__.py#L505-L518
train
221,393
GNS3/gns3-server
gns3server/compute/dynamips/__init__.py
Dynamips.auto_idlepc
def auto_idlepc(self, vm): """ Try to find the best possible idle-pc value. :param vm: VM instance """ yield from vm.set_idlepc("0x0") was_auto_started = False try: status = yield from vm.get_status() if status != "running": yield from vm.start() was_auto_started = True yield from asyncio.sleep(20) # leave time to the router to boot validated_idlepc = None idlepcs = yield from vm.get_idle_pc_prop() if not idlepcs: raise DynamipsError("No Idle-PC values found") for idlepc in idlepcs: match = re.search(r"^0x[0-9a-f]{8}$", idlepc.split()[0]) if not match: continue yield from vm.set_idlepc(idlepc.split()[0]) log.debug("Auto Idle-PC: trying idle-PC value {}".format(vm.idlepc)) start_time = time.time() initial_cpu_usage = yield from vm.get_cpu_usage() log.debug("Auto Idle-PC: initial CPU usage is {}%".format(initial_cpu_usage)) yield from asyncio.sleep(3) # wait 3 seconds to probe the cpu again elapsed_time = time.time() - start_time cpu_usage = yield from vm.get_cpu_usage() cpu_elapsed_usage = cpu_usage - initial_cpu_usage cpu_usage = abs(cpu_elapsed_usage * 100.0 / elapsed_time) if cpu_usage > 100: cpu_usage = 100 log.debug("Auto Idle-PC: CPU usage is {}% after {:.2} seconds".format(cpu_usage, elapsed_time)) if cpu_usage < 70: validated_idlepc = vm.idlepc log.debug("Auto Idle-PC: idle-PC value {} has been validated".format(validated_idlepc)) break if validated_idlepc is None: raise DynamipsError("Sorry, no idle-pc value was suitable") except DynamipsError: raise finally: if was_auto_started: yield from vm.stop() return validated_idlepc
python
def auto_idlepc(self, vm): """ Try to find the best possible idle-pc value. :param vm: VM instance """ yield from vm.set_idlepc("0x0") was_auto_started = False try: status = yield from vm.get_status() if status != "running": yield from vm.start() was_auto_started = True yield from asyncio.sleep(20) # leave time to the router to boot validated_idlepc = None idlepcs = yield from vm.get_idle_pc_prop() if not idlepcs: raise DynamipsError("No Idle-PC values found") for idlepc in idlepcs: match = re.search(r"^0x[0-9a-f]{8}$", idlepc.split()[0]) if not match: continue yield from vm.set_idlepc(idlepc.split()[0]) log.debug("Auto Idle-PC: trying idle-PC value {}".format(vm.idlepc)) start_time = time.time() initial_cpu_usage = yield from vm.get_cpu_usage() log.debug("Auto Idle-PC: initial CPU usage is {}%".format(initial_cpu_usage)) yield from asyncio.sleep(3) # wait 3 seconds to probe the cpu again elapsed_time = time.time() - start_time cpu_usage = yield from vm.get_cpu_usage() cpu_elapsed_usage = cpu_usage - initial_cpu_usage cpu_usage = abs(cpu_elapsed_usage * 100.0 / elapsed_time) if cpu_usage > 100: cpu_usage = 100 log.debug("Auto Idle-PC: CPU usage is {}% after {:.2} seconds".format(cpu_usage, elapsed_time)) if cpu_usage < 70: validated_idlepc = vm.idlepc log.debug("Auto Idle-PC: idle-PC value {} has been validated".format(validated_idlepc)) break if validated_idlepc is None: raise DynamipsError("Sorry, no idle-pc value was suitable") except DynamipsError: raise finally: if was_auto_started: yield from vm.stop() return validated_idlepc
[ "def", "auto_idlepc", "(", "self", ",", "vm", ")", ":", "yield", "from", "vm", ".", "set_idlepc", "(", "\"0x0\"", ")", "was_auto_started", "=", "False", "try", ":", "status", "=", "yield", "from", "vm", ".", "get_status", "(", ")", "if", "status", "!="...
Try to find the best possible idle-pc value. :param vm: VM instance
[ "Try", "to", "find", "the", "best", "possible", "idle", "-", "pc", "value", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/__init__.py#L555-L605
train
221,394
GNS3/gns3-server
gns3server/web/documentation.py
Documentation.write_documentation
def write_documentation(self, doc_type): """ Build all the doc page for handlers :param doc_type: Type of doc to generate (controller, compute) """ for handler_name in sorted(self._documentation): if "controller." in handler_name: server_type = "controller" elif "compute" in handler_name: server_type = "compute" else: server_type = "root" if doc_type != server_type: continue print("Build {}".format(handler_name)) for path in sorted(self._documentation[handler_name]): api_version = self._documentation[handler_name][path]["api_version"] if api_version is None: continue filename = self._file_path(path) handler_doc = self._documentation[handler_name][path] handler = handler_name.replace(server_type + ".", "") self._create_handler_directory(handler, api_version, server_type) with open("{}/api/v{}/{}/{}/{}.rst".format(self._directory, api_version, server_type, handler, filename), 'w+') as f: f.write('{}\n------------------------------------------------------------------------------------------------------------------------------------------\n\n'.format(path)) f.write('.. contents::\n') for method in handler_doc["methods"]: f.write('\n{} {}\n'.format(method["method"], path.replace("{", '**{').replace("}", "}**"))) f.write('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n') f.write('{}\n\n'.format(method["description"])) if len(method["parameters"]) > 0: f.write("Parameters\n**********\n") for parameter in method["parameters"]: desc = method["parameters"][parameter] f.write("- **{}**: {}\n".format(parameter, desc)) f.write("\n") f.write("Response status codes\n**********************\n") for code in method["status_codes"]: desc = method["status_codes"][code] f.write("- **{}**: {}\n".format(code, desc)) f.write("\n") if "properties" in method["input_schema"]: f.write("Input\n*******\n") self._write_definitions(f, method["input_schema"]) self._write_json_schema(f, method["input_schema"]) if "properties" in method["output_schema"]: f.write("Output\n*******\n") self._write_json_schema(f, method["output_schema"]) self._include_query_example(f, method, path, api_version, server_type)
python
def write_documentation(self, doc_type): """ Build all the doc page for handlers :param doc_type: Type of doc to generate (controller, compute) """ for handler_name in sorted(self._documentation): if "controller." in handler_name: server_type = "controller" elif "compute" in handler_name: server_type = "compute" else: server_type = "root" if doc_type != server_type: continue print("Build {}".format(handler_name)) for path in sorted(self._documentation[handler_name]): api_version = self._documentation[handler_name][path]["api_version"] if api_version is None: continue filename = self._file_path(path) handler_doc = self._documentation[handler_name][path] handler = handler_name.replace(server_type + ".", "") self._create_handler_directory(handler, api_version, server_type) with open("{}/api/v{}/{}/{}/{}.rst".format(self._directory, api_version, server_type, handler, filename), 'w+') as f: f.write('{}\n------------------------------------------------------------------------------------------------------------------------------------------\n\n'.format(path)) f.write('.. contents::\n') for method in handler_doc["methods"]: f.write('\n{} {}\n'.format(method["method"], path.replace("{", '**{').replace("}", "}**"))) f.write('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n') f.write('{}\n\n'.format(method["description"])) if len(method["parameters"]) > 0: f.write("Parameters\n**********\n") for parameter in method["parameters"]: desc = method["parameters"][parameter] f.write("- **{}**: {}\n".format(parameter, desc)) f.write("\n") f.write("Response status codes\n**********************\n") for code in method["status_codes"]: desc = method["status_codes"][code] f.write("- **{}**: {}\n".format(code, desc)) f.write("\n") if "properties" in method["input_schema"]: f.write("Input\n*******\n") self._write_definitions(f, method["input_schema"]) self._write_json_schema(f, method["input_schema"]) if "properties" in method["output_schema"]: f.write("Output\n*******\n") self._write_json_schema(f, method["output_schema"]) self._include_query_example(f, method, path, api_version, server_type)
[ "def", "write_documentation", "(", "self", ",", "doc_type", ")", ":", "for", "handler_name", "in", "sorted", "(", "self", ".", "_documentation", ")", ":", "if", "\"controller.\"", "in", "handler_name", ":", "server_type", "=", "\"controller\"", "elif", "\"comput...
Build all the doc page for handlers :param doc_type: Type of doc to generate (controller, compute)
[ "Build", "all", "the", "doc", "page", "for", "handlers" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/web/documentation.py#L48-L108
train
221,395
GNS3/gns3-server
gns3server/web/documentation.py
Documentation._create_handler_directory
def _create_handler_directory(self, handler_name, api_version, server_type): """Create a directory for the handler and add an index inside""" directory = "{}/api/v{}/{}/{}".format(self._directory, api_version, server_type, handler_name) os.makedirs(directory, exist_ok=True) with open("{}/api/v{}/{}/{}.rst".format(self._directory, api_version, server_type, handler_name), "w+") as f: f.write(handler_name.replace("api.", "").replace("_", " ", ).capitalize()) f.write("\n-----------------------------\n\n") f.write(".. toctree::\n :glob:\n :maxdepth: 2\n\n {}/*\n".format(handler_name))
python
def _create_handler_directory(self, handler_name, api_version, server_type): """Create a directory for the handler and add an index inside""" directory = "{}/api/v{}/{}/{}".format(self._directory, api_version, server_type, handler_name) os.makedirs(directory, exist_ok=True) with open("{}/api/v{}/{}/{}.rst".format(self._directory, api_version, server_type, handler_name), "w+") as f: f.write(handler_name.replace("api.", "").replace("_", " ", ).capitalize()) f.write("\n-----------------------------\n\n") f.write(".. toctree::\n :glob:\n :maxdepth: 2\n\n {}/*\n".format(handler_name))
[ "def", "_create_handler_directory", "(", "self", ",", "handler_name", ",", "api_version", ",", "server_type", ")", ":", "directory", "=", "\"{}/api/v{}/{}/{}\"", ".", "format", "(", "self", ".", "_directory", ",", "api_version", ",", "server_type", ",", "handler_n...
Create a directory for the handler and add an index inside
[ "Create", "a", "directory", "for", "the", "handler", "and", "add", "an", "index", "inside" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/web/documentation.py#L110-L119
train
221,396
GNS3/gns3-server
gns3server/web/documentation.py
Documentation._include_query_example
def _include_query_example(self, f, method, path, api_version, server_type): """If a sample session is available we include it in documentation""" m = method["method"].lower() query_path = "{}_{}_{}.txt".format(server_type, m, self._file_path(path)) if os.path.isfile(os.path.join(self._directory, "api", "examples", query_path)): f.write("Sample session\n***************\n") f.write("\n\n.. literalinclude:: ../../../examples/{}\n\n".format(query_path))
python
def _include_query_example(self, f, method, path, api_version, server_type): """If a sample session is available we include it in documentation""" m = method["method"].lower() query_path = "{}_{}_{}.txt".format(server_type, m, self._file_path(path)) if os.path.isfile(os.path.join(self._directory, "api", "examples", query_path)): f.write("Sample session\n***************\n") f.write("\n\n.. literalinclude:: ../../../examples/{}\n\n".format(query_path))
[ "def", "_include_query_example", "(", "self", ",", "f", ",", "method", ",", "path", ",", "api_version", ",", "server_type", ")", ":", "m", "=", "method", "[", "\"method\"", "]", ".", "lower", "(", ")", "query_path", "=", "\"{}_{}_{}.txt\"", ".", "format", ...
If a sample session is available we include it in documentation
[ "If", "a", "sample", "session", "is", "available", "we", "include", "it", "in", "documentation" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/web/documentation.py#L121-L127
train
221,397
GNS3/gns3-server
gns3server/web/documentation.py
Documentation._write_json_schema_object
def _write_json_schema_object(self, f, obj): """ obj is current object in JSON schema schema is the whole schema including definitions """ for name in sorted(obj.get("properties", {})): prop = obj["properties"][name] mandatory = " " if name in obj.get("required", []): mandatory = "&#10004;" if "enum" in prop: field_type = "enum" prop['description'] = "Possible values: {}".format(', '.join(map(lambda a: a or "null", prop['enum']))) else: field_type = prop.get("type", "") # Resolve oneOf relation to their human type. if field_type == 'object' and 'oneOf' in prop: field_type = ', '.join(map(lambda p: p['$ref'].split('/').pop(), prop['oneOf'])) f.write(" <tr><td>{}</td>\ <td>{}</td> \ <td>{}</td> \ <td>{}</td> \ </tr>\n".format( name, mandatory, field_type, prop.get("description", "") ))
python
def _write_json_schema_object(self, f, obj): """ obj is current object in JSON schema schema is the whole schema including definitions """ for name in sorted(obj.get("properties", {})): prop = obj["properties"][name] mandatory = " " if name in obj.get("required", []): mandatory = "&#10004;" if "enum" in prop: field_type = "enum" prop['description'] = "Possible values: {}".format(', '.join(map(lambda a: a or "null", prop['enum']))) else: field_type = prop.get("type", "") # Resolve oneOf relation to their human type. if field_type == 'object' and 'oneOf' in prop: field_type = ', '.join(map(lambda p: p['$ref'].split('/').pop(), prop['oneOf'])) f.write(" <tr><td>{}</td>\ <td>{}</td> \ <td>{}</td> \ <td>{}</td> \ </tr>\n".format( name, mandatory, field_type, prop.get("description", "") ))
[ "def", "_write_json_schema_object", "(", "self", ",", "f", ",", "obj", ")", ":", "for", "name", "in", "sorted", "(", "obj", ".", "get", "(", "\"properties\"", ",", "{", "}", ")", ")", ":", "prop", "=", "obj", "[", "\"properties\"", "]", "[", "name", ...
obj is current object in JSON schema schema is the whole schema including definitions
[ "obj", "is", "current", "object", "in", "JSON", "schema", "schema", "is", "the", "whole", "schema", "including", "definitions" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/web/documentation.py#L143-L173
train
221,398
GNS3/gns3-server
gns3server/controller/compute.py
Compute._set_auth
def _set_auth(self, user, password): """ Set authentication parameters """ if user is None or len(user.strip()) == 0: self._user = None self._password = None self._auth = None else: self._user = user.strip() if password: self._password = password.strip() try: self._auth = aiohttp.BasicAuth(self._user, self._password, "utf-8") except ValueError as e: log.error(str(e)) else: self._password = None self._auth = aiohttp.BasicAuth(self._user, "")
python
def _set_auth(self, user, password): """ Set authentication parameters """ if user is None or len(user.strip()) == 0: self._user = None self._password = None self._auth = None else: self._user = user.strip() if password: self._password = password.strip() try: self._auth = aiohttp.BasicAuth(self._user, self._password, "utf-8") except ValueError as e: log.error(str(e)) else: self._password = None self._auth = aiohttp.BasicAuth(self._user, "")
[ "def", "_set_auth", "(", "self", ",", "user", ",", "password", ")", ":", "if", "user", "is", "None", "or", "len", "(", "user", ".", "strip", "(", ")", ")", "==", "0", ":", "self", ".", "_user", "=", "None", "self", ".", "_password", "=", "None", ...
Set authentication parameters
[ "Set", "authentication", "parameters" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L120-L138
train
221,399