id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
240,300
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): 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
240,301
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): 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
240,302
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): # 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
240,303
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): 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
240,304
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): 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
240,305
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): 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
240,306
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): 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
240,307
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): # 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
240,308
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): 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
240,309
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): 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
240,310
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): 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
240,311
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): 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
240,312
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): 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
240,313
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): # 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
240,314
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): 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
240,315
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): 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
240,316
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): 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
240,317
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): 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
240,318
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): 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
240,319
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): 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
240,320
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): 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
240,321
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): # 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
240,322
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): # 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
240,323
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): 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
240,324
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): 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
240,325
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): 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
240,326
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): 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
240,327
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): 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
240,328
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): 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
240,329
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): 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
240,330
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): 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
240,331
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): 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
240,332
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): 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
240,333
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): 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
240,334
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): 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
240,335
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): 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
240,336
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): 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
240,337
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): 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
240,338
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): 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
240,339
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): 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
240,340
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): 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
240,341
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): 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
240,342
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): 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
240,343
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): 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
240,344
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): 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
240,345
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): 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
240,346
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): 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
240,347
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): 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
240,348
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): 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
240,349
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): 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
240,350
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): 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
240,351
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): 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
240,352
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): 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
240,353
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): 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
240,354
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): 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
240,355
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): 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
240,356
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): 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
240,357
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): 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
240,358
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): 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
240,359
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): 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
240,360
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): 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
240,361
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): 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
240,362
GNS3/gns3-server
gns3server/controller/compute.py
Compute.interfaces
def interfaces(self): """ Get the list of network on compute """ if not self._interfaces_cache: response = yield from self.get("/network/interfaces") self._interfaces_cache = response.json return self._interfaces_cache
python
def interfaces(self): if not self._interfaces_cache: response = yield from self.get("/network/interfaces") self._interfaces_cache = response.json return self._interfaces_cache
[ "def", "interfaces", "(", "self", ")", ":", "if", "not", "self", ".", "_interfaces_cache", ":", "response", "=", "yield", "from", "self", ".", "get", "(", "\"/network/interfaces\"", ")", "self", ".", "_interfaces_cache", "=", "response", ".", "json", "return...
Get the list of network on compute
[ "Get", "the", "list", "of", "network", "on", "compute" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L141-L148
240,363
GNS3/gns3-server
gns3server/controller/compute.py
Compute.stream_file
def stream_file(self, project, path): """ Read file of a project and stream it :param project: A project object :param path: The path of the file in the project :returns: A file stream """ # Due to Python 3.4 limitation we can't use with and asyncio # https://www.python.org/dev/peps/pep-0492/ # that why we wrap the answer class StreamResponse: def __init__(self, response): self._response = response def __enter__(self): return self._response.content def __exit__(self): self._response.close() url = self._getUrl("/projects/{}/stream/{}".format(project.id, path)) response = yield from self._session().request("GET", url, auth=self._auth, timeout=None) if response.status == 404: raise aiohttp.web.HTTPNotFound(text="{} not found on compute".format(path)) elif response.status == 403: raise aiohttp.web.HTTPForbidden(text="forbidden to open {} on compute".format(path)) elif response.status != 200: raise aiohttp.web.HTTPInternalServerError(text="Unexpected error {}: {}: while opening {} on compute".format(response.status, response.reason, path)) return StreamResponse(response)
python
def stream_file(self, project, path): # Due to Python 3.4 limitation we can't use with and asyncio # https://www.python.org/dev/peps/pep-0492/ # that why we wrap the answer class StreamResponse: def __init__(self, response): self._response = response def __enter__(self): return self._response.content def __exit__(self): self._response.close() url = self._getUrl("/projects/{}/stream/{}".format(project.id, path)) response = yield from self._session().request("GET", url, auth=self._auth, timeout=None) if response.status == 404: raise aiohttp.web.HTTPNotFound(text="{} not found on compute".format(path)) elif response.status == 403: raise aiohttp.web.HTTPForbidden(text="forbidden to open {} on compute".format(path)) elif response.status != 200: raise aiohttp.web.HTTPInternalServerError(text="Unexpected error {}: {}: while opening {} on compute".format(response.status, response.reason, path)) return StreamResponse(response)
[ "def", "stream_file", "(", "self", ",", "project", ",", "path", ")", ":", "# Due to Python 3.4 limitation we can't use with and asyncio", "# https://www.python.org/dev/peps/pep-0492/", "# that why we wrap the answer", "class", "StreamResponse", ":", "def", "__init__", "(", "sel...
Read file of a project and stream it :param project: A project object :param path: The path of the file in the project :returns: A file stream
[ "Read", "file", "of", "a", "project", "and", "stream", "it" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L340-L373
240,364
GNS3/gns3-server
gns3server/controller/compute.py
Compute.connect
def connect(self): """ Check if remote server is accessible """ if not self._connected and not self._closed: try: log.info("Connecting to compute '{}'".format(self._id)) response = yield from self._run_http_query("GET", "/capabilities") except ComputeError as e: # Try to reconnect after 2 seconds if server unavailable only if not during tests (otherwise we create a ressources usage bomb) if not hasattr(sys, "_called_from_test") or not sys._called_from_test: self._connection_failure += 1 # After 5 failure we close the project using the compute to avoid sync issues if self._connection_failure == 5: log.warning("Cannot connect to compute '{}': {}".format(self._id, e)) yield from self._controller.close_compute_projects(self) asyncio.get_event_loop().call_later(2, lambda: asyncio.async(self._try_reconnect())) return except aiohttp.web.HTTPNotFound: raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server or it's a 1.X server".format(self._id)) except aiohttp.web.HTTPUnauthorized: raise aiohttp.web.HTTPConflict(text="Invalid auth for server {}".format(self._id)) except aiohttp.web.HTTPServiceUnavailable: raise aiohttp.web.HTTPConflict(text="The server {} is unavailable".format(self._id)) except ValueError: raise aiohttp.web.HTTPConflict(text="Invalid server url for server {}".format(self._id)) if "version" not in response.json: self._http_session.close() raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server".format(self._id)) self._capabilities = response.json if parse_version(__version__)[:2] != parse_version(response.json["version"])[:2]: self._http_session.close() raise aiohttp.web.HTTPConflict(text="The server {} versions are not compatible {} != {}".format(self._id, __version__, response.json["version"])) self._notifications = asyncio.gather(self._connect_notification()) self._connected = True self._connection_failure = 0 self._controller.notification.emit("compute.updated", self.__json__())
python
def connect(self): if not self._connected and not self._closed: try: log.info("Connecting to compute '{}'".format(self._id)) response = yield from self._run_http_query("GET", "/capabilities") except ComputeError as e: # Try to reconnect after 2 seconds if server unavailable only if not during tests (otherwise we create a ressources usage bomb) if not hasattr(sys, "_called_from_test") or not sys._called_from_test: self._connection_failure += 1 # After 5 failure we close the project using the compute to avoid sync issues if self._connection_failure == 5: log.warning("Cannot connect to compute '{}': {}".format(self._id, e)) yield from self._controller.close_compute_projects(self) asyncio.get_event_loop().call_later(2, lambda: asyncio.async(self._try_reconnect())) return except aiohttp.web.HTTPNotFound: raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server or it's a 1.X server".format(self._id)) except aiohttp.web.HTTPUnauthorized: raise aiohttp.web.HTTPConflict(text="Invalid auth for server {}".format(self._id)) except aiohttp.web.HTTPServiceUnavailable: raise aiohttp.web.HTTPConflict(text="The server {} is unavailable".format(self._id)) except ValueError: raise aiohttp.web.HTTPConflict(text="Invalid server url for server {}".format(self._id)) if "version" not in response.json: self._http_session.close() raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server".format(self._id)) self._capabilities = response.json if parse_version(__version__)[:2] != parse_version(response.json["version"])[:2]: self._http_session.close() raise aiohttp.web.HTTPConflict(text="The server {} versions are not compatible {} != {}".format(self._id, __version__, response.json["version"])) self._notifications = asyncio.gather(self._connect_notification()) self._connected = True self._connection_failure = 0 self._controller.notification.emit("compute.updated", self.__json__())
[ "def", "connect", "(", "self", ")", ":", "if", "not", "self", ".", "_connected", "and", "not", "self", ".", "_closed", ":", "try", ":", "log", ".", "info", "(", "\"Connecting to compute '{}'\"", ".", "format", "(", "self", ".", "_id", ")", ")", "respon...
Check if remote server is accessible
[ "Check", "if", "remote", "server", "is", "accessible" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L401-L440
240,365
GNS3/gns3-server
gns3server/controller/compute.py
Compute._connect_notification
def _connect_notification(self): """ Connect to the notification stream """ try: self._ws = yield from self._session().ws_connect(self._getUrl("/notifications/ws"), auth=self._auth) except (aiohttp.WSServerHandshakeError, aiohttp.ClientResponseError): self._ws = None while self._ws is not None: try: response = yield from self._ws.receive() except aiohttp.WSServerHandshakeError: self._ws = None break if response.tp == aiohttp.WSMsgType.closed or response.tp == aiohttp.WSMsgType.error or response.data is None: self._connected = False break msg = json.loads(response.data) action = msg.pop("action") event = msg.pop("event") if action == "ping": self._cpu_usage_percent = event["cpu_usage_percent"] self._memory_usage_percent = event["memory_usage_percent"] self._controller.notification.emit("compute.updated", self.__json__()) else: yield from self._controller.notification.dispatch(action, event, compute_id=self.id) if self._ws: yield from self._ws.close() # Try to reconnect after 1 seconds if server unavailable only if not during tests (otherwise we create a ressources usage bomb) if not hasattr(sys, "_called_from_test") or not sys._called_from_test: asyncio.get_event_loop().call_later(1, lambda: asyncio.async(self.connect())) self._ws = None self._cpu_usage_percent = None self._memory_usage_percent = None self._controller.notification.emit("compute.updated", self.__json__())
python
def _connect_notification(self): try: self._ws = yield from self._session().ws_connect(self._getUrl("/notifications/ws"), auth=self._auth) except (aiohttp.WSServerHandshakeError, aiohttp.ClientResponseError): self._ws = None while self._ws is not None: try: response = yield from self._ws.receive() except aiohttp.WSServerHandshakeError: self._ws = None break if response.tp == aiohttp.WSMsgType.closed or response.tp == aiohttp.WSMsgType.error or response.data is None: self._connected = False break msg = json.loads(response.data) action = msg.pop("action") event = msg.pop("event") if action == "ping": self._cpu_usage_percent = event["cpu_usage_percent"] self._memory_usage_percent = event["memory_usage_percent"] self._controller.notification.emit("compute.updated", self.__json__()) else: yield from self._controller.notification.dispatch(action, event, compute_id=self.id) if self._ws: yield from self._ws.close() # Try to reconnect after 1 seconds if server unavailable only if not during tests (otherwise we create a ressources usage bomb) if not hasattr(sys, "_called_from_test") or not sys._called_from_test: asyncio.get_event_loop().call_later(1, lambda: asyncio.async(self.connect())) self._ws = None self._cpu_usage_percent = None self._memory_usage_percent = None self._controller.notification.emit("compute.updated", self.__json__())
[ "def", "_connect_notification", "(", "self", ")", ":", "try", ":", "self", ".", "_ws", "=", "yield", "from", "self", ".", "_session", "(", ")", ".", "ws_connect", "(", "self", ".", "_getUrl", "(", "\"/notifications/ws\"", ")", ",", "auth", "=", "self", ...
Connect to the notification stream
[ "Connect", "to", "the", "notification", "stream" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L443-L479
240,366
GNS3/gns3-server
gns3server/controller/compute.py
Compute.forward
def forward(self, method, type, path, data=None): """ Forward a call to the emulator on compute """ try: action = "/{}/{}".format(type, path) res = yield from self.http_query(method, action, data=data, timeout=None) except aiohttp.ServerDisconnectedError: log.error("Connection lost to %s during %s %s", self._id, method, action) raise aiohttp.web.HTTPGatewayTimeout() return res.json
python
def forward(self, method, type, path, data=None): try: action = "/{}/{}".format(type, path) res = yield from self.http_query(method, action, data=data, timeout=None) except aiohttp.ServerDisconnectedError: log.error("Connection lost to %s during %s %s", self._id, method, action) raise aiohttp.web.HTTPGatewayTimeout() return res.json
[ "def", "forward", "(", "self", ",", "method", ",", "type", ",", "path", ",", "data", "=", "None", ")", ":", "try", ":", "action", "=", "\"/{}/{}\"", ".", "format", "(", "type", ",", "path", ")", "res", "=", "yield", "from", "self", ".", "http_query...
Forward a call to the emulator on compute
[ "Forward", "a", "call", "to", "the", "emulator", "on", "compute" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L604-L614
240,367
GNS3/gns3-server
gns3server/controller/compute.py
Compute.images
def images(self, type): """ Return the list of images available for this type on controller and on the compute node. """ images = [] res = yield from self.http_query("GET", "/{}/images".format(type), timeout=None) images = res.json try: if type in ["qemu", "dynamips", "iou"]: for local_image in list_images(type): if local_image['filename'] not in [i['filename'] for i in images]: images.append(local_image) images = sorted(images, key=itemgetter('filename')) else: images = sorted(images, key=itemgetter('image')) except OSError as e: raise ComputeError("Can't list images: {}".format(str(e))) return images
python
def images(self, type): images = [] res = yield from self.http_query("GET", "/{}/images".format(type), timeout=None) images = res.json try: if type in ["qemu", "dynamips", "iou"]: for local_image in list_images(type): if local_image['filename'] not in [i['filename'] for i in images]: images.append(local_image) images = sorted(images, key=itemgetter('filename')) else: images = sorted(images, key=itemgetter('image')) except OSError as e: raise ComputeError("Can't list images: {}".format(str(e))) return images
[ "def", "images", "(", "self", ",", "type", ")", ":", "images", "=", "[", "]", "res", "=", "yield", "from", "self", ".", "http_query", "(", "\"GET\"", ",", "\"/{}/images\"", ".", "format", "(", "type", ")", ",", "timeout", "=", "None", ")", "images", ...
Return the list of images available for this type on controller and on the compute node.
[ "Return", "the", "list", "of", "images", "available", "for", "this", "type", "on", "controller", "and", "on", "the", "compute", "node", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L617-L637
240,368
GNS3/gns3-server
gns3server/controller/compute.py
Compute.list_files
def list_files(self, project): """ List files in the project on computes """ path = "/projects/{}/files".format(project.id) res = yield from self.http_query("GET", path, timeout=120) return res.json
python
def list_files(self, project): path = "/projects/{}/files".format(project.id) res = yield from self.http_query("GET", path, timeout=120) return res.json
[ "def", "list_files", "(", "self", ",", "project", ")", ":", "path", "=", "\"/projects/{}/files\"", ".", "format", "(", "project", ".", "id", ")", "res", "=", "yield", "from", "self", ".", "http_query", "(", "\"GET\"", ",", "path", ",", "timeout", "=", ...
List files in the project on computes
[ "List", "files", "in", "the", "project", "on", "computes" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L640-L646
240,369
GNS3/gns3-server
gns3server/controller/compute.py
Compute.get_ip_on_same_subnet
def get_ip_on_same_subnet(self, other_compute): """ Try to found the best ip for communication from one compute to another :returns: Tuple (ip_for_this_compute, ip_for_other_compute) """ if other_compute == self: return (self.host_ip, self.host_ip) # Perhaps the user has correct network gateway, we trust him if (self.host_ip not in ('0.0.0.0', '127.0.0.1') and other_compute.host_ip not in ('0.0.0.0', '127.0.0.1')): return (self.host_ip, other_compute.host_ip) this_compute_interfaces = yield from self.interfaces() other_compute_interfaces = yield from other_compute.interfaces() # Sort interface to put the compute host in first position # we guess that if user specified this host it could have a reason (VMware Nat / Host only interface) this_compute_interfaces = sorted(this_compute_interfaces, key=lambda i: i["ip_address"] != self.host_ip) other_compute_interfaces = sorted(other_compute_interfaces, key=lambda i: i["ip_address"] != other_compute.host_ip) for this_interface in this_compute_interfaces: # Skip if no ip or no netmask (vbox when stopped set a null netmask) if len(this_interface["ip_address"]) == 0 or this_interface["netmask"] is None: continue # Ignore 169.254 network because it's for Windows special purpose if this_interface["ip_address"].startswith("169.254."): continue this_network = ipaddress.ip_network("{}/{}".format(this_interface["ip_address"], this_interface["netmask"]), strict=False) for other_interface in other_compute_interfaces: if len(other_interface["ip_address"]) == 0 or other_interface["netmask"] is None: continue # Avoid stuff like 127.0.0.1 if other_interface["ip_address"] == this_interface["ip_address"]: continue other_network = ipaddress.ip_network("{}/{}".format(other_interface["ip_address"], other_interface["netmask"]), strict=False) if this_network.overlaps(other_network): return (this_interface["ip_address"], other_interface["ip_address"]) raise ValueError("No common subnet for compute {} and {}".format(self.name, other_compute.name))
python
def get_ip_on_same_subnet(self, other_compute): if other_compute == self: return (self.host_ip, self.host_ip) # Perhaps the user has correct network gateway, we trust him if (self.host_ip not in ('0.0.0.0', '127.0.0.1') and other_compute.host_ip not in ('0.0.0.0', '127.0.0.1')): return (self.host_ip, other_compute.host_ip) this_compute_interfaces = yield from self.interfaces() other_compute_interfaces = yield from other_compute.interfaces() # Sort interface to put the compute host in first position # we guess that if user specified this host it could have a reason (VMware Nat / Host only interface) this_compute_interfaces = sorted(this_compute_interfaces, key=lambda i: i["ip_address"] != self.host_ip) other_compute_interfaces = sorted(other_compute_interfaces, key=lambda i: i["ip_address"] != other_compute.host_ip) for this_interface in this_compute_interfaces: # Skip if no ip or no netmask (vbox when stopped set a null netmask) if len(this_interface["ip_address"]) == 0 or this_interface["netmask"] is None: continue # Ignore 169.254 network because it's for Windows special purpose if this_interface["ip_address"].startswith("169.254."): continue this_network = ipaddress.ip_network("{}/{}".format(this_interface["ip_address"], this_interface["netmask"]), strict=False) for other_interface in other_compute_interfaces: if len(other_interface["ip_address"]) == 0 or other_interface["netmask"] is None: continue # Avoid stuff like 127.0.0.1 if other_interface["ip_address"] == this_interface["ip_address"]: continue other_network = ipaddress.ip_network("{}/{}".format(other_interface["ip_address"], other_interface["netmask"]), strict=False) if this_network.overlaps(other_network): return (this_interface["ip_address"], other_interface["ip_address"]) raise ValueError("No common subnet for compute {} and {}".format(self.name, other_compute.name))
[ "def", "get_ip_on_same_subnet", "(", "self", ",", "other_compute", ")", ":", "if", "other_compute", "==", "self", ":", "return", "(", "self", ".", "host_ip", ",", "self", ".", "host_ip", ")", "# Perhaps the user has correct network gateway, we trust him", "if", "(",...
Try to found the best ip for communication from one compute to another :returns: Tuple (ip_for_this_compute, ip_for_other_compute)
[ "Try", "to", "found", "the", "best", "ip", "for", "communication", "from", "one", "compute", "to", "another" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L649-L693
240,370
GNS3/gns3-server
gns3server/compute/dynamips/nodes/frame_relay_switch.py
FrameRelaySwitch.add_nio
def add_nio(self, nio, port_number): """ Adds a NIO as new port on Frame Relay switch. :param nio: NIO instance to add :param port_number: port to allocate for the NIO """ if port_number in self._nios: raise DynamipsError("Port {} isn't free".format(port_number)) log.info('Frame Relay switch "{name}" [{id}]: NIO {nio} bound to port {port}'.format(name=self._name, id=self._id, nio=nio, port=port_number)) self._nios[port_number] = nio yield from self.set_mappings(self._mappings)
python
def add_nio(self, nio, port_number): if port_number in self._nios: raise DynamipsError("Port {} isn't free".format(port_number)) log.info('Frame Relay switch "{name}" [{id}]: NIO {nio} bound to port {port}'.format(name=self._name, id=self._id, nio=nio, port=port_number)) self._nios[port_number] = nio yield from self.set_mappings(self._mappings)
[ "def", "add_nio", "(", "self", ",", "nio", ",", "port_number", ")", ":", "if", "port_number", "in", "self", ".", "_nios", ":", "raise", "DynamipsError", "(", "\"Port {} isn't free\"", ".", "format", "(", "port_number", ")", ")", "log", ".", "info", "(", ...
Adds a NIO as new port on Frame Relay switch. :param nio: NIO instance to add :param port_number: port to allocate for the NIO
[ "Adds", "a", "NIO", "as", "new", "port", "on", "Frame", "Relay", "switch", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/frame_relay_switch.py#L160-L177
240,371
GNS3/gns3-server
gns3server/compute/dynamips/nodes/frame_relay_switch.py
FrameRelaySwitch.remove_nio
def remove_nio(self, port_number): """ Removes the specified NIO as member of this Frame Relay switch. :param port_number: allocated port number :returns: the NIO that was bound to the allocated port """ if port_number not in self._nios: raise DynamipsError("Port {} is not allocated".format(port_number)) # remove VCs mapped with the port for source, destination in self._active_mappings.copy().items(): source_port, source_dlci = source destination_port, destination_dlci = destination if port_number == source_port: log.info('Frame Relay switch "{name}" [{id}]: unmapping VC between port {source_port} DLCI {source_dlci} and port {destination_port} DLCI {destination_dlci}'.format(name=self._name, id=self._id, source_port=source_port, source_dlci=source_dlci, destination_port=destination_port, destination_dlci=destination_dlci)) yield from self.unmap_vc(source_port, source_dlci, destination_port, destination_dlci) yield from self.unmap_vc(destination_port, destination_dlci, source_port, source_dlci) nio = self._nios[port_number] if isinstance(nio, NIOUDP): self.manager.port_manager.release_udp_port(nio.lport, self._project) log.info('Frame Relay switch "{name}" [{id}]: NIO {nio} removed from port {port}'.format(name=self._name, id=self._id, nio=nio, port=port_number)) del self._nios[port_number] return nio
python
def remove_nio(self, port_number): if port_number not in self._nios: raise DynamipsError("Port {} is not allocated".format(port_number)) # remove VCs mapped with the port for source, destination in self._active_mappings.copy().items(): source_port, source_dlci = source destination_port, destination_dlci = destination if port_number == source_port: log.info('Frame Relay switch "{name}" [{id}]: unmapping VC between port {source_port} DLCI {source_dlci} and port {destination_port} DLCI {destination_dlci}'.format(name=self._name, id=self._id, source_port=source_port, source_dlci=source_dlci, destination_port=destination_port, destination_dlci=destination_dlci)) yield from self.unmap_vc(source_port, source_dlci, destination_port, destination_dlci) yield from self.unmap_vc(destination_port, destination_dlci, source_port, source_dlci) nio = self._nios[port_number] if isinstance(nio, NIOUDP): self.manager.port_manager.release_udp_port(nio.lport, self._project) log.info('Frame Relay switch "{name}" [{id}]: NIO {nio} removed from port {port}'.format(name=self._name, id=self._id, nio=nio, port=port_number)) del self._nios[port_number] return nio
[ "def", "remove_nio", "(", "self", ",", "port_number", ")", ":", "if", "port_number", "not", "in", "self", ".", "_nios", ":", "raise", "DynamipsError", "(", "\"Port {} is not allocated\"", ".", "format", "(", "port_number", ")", ")", "# remove VCs mapped with the p...
Removes the specified NIO as member of this Frame Relay switch. :param port_number: allocated port number :returns: the NIO that was bound to the allocated port
[ "Removes", "the", "specified", "NIO", "as", "member", "of", "this", "Frame", "Relay", "switch", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/frame_relay_switch.py#L180-L216
240,372
GNS3/gns3-server
gns3server/main.py
main
def main(): """ Entry point for GNS3 server """ if not sys.platform.startswith("win"): if "--daemon" in sys.argv: daemonize() from gns3server.run import run run()
python
def main(): if not sys.platform.startswith("win"): if "--daemon" in sys.argv: daemonize() from gns3server.run import run run()
[ "def", "main", "(", ")", ":", "if", "not", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", ":", "if", "\"--daemon\"", "in", "sys", ".", "argv", ":", "daemonize", "(", ")", "from", "gns3server", ".", "run", "import", "run", "run", "(",...
Entry point for GNS3 server
[ "Entry", "point", "for", "GNS3", "server" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/main.py#L74-L83
240,373
GNS3/gns3-server
gns3server/compute/docker/docker_vm.py
DockerVM._get_free_display_port
def _get_free_display_port(self): """ Search a free display port """ display = 100 if not os.path.exists("/tmp/.X11-unix/"): return display while True: if not os.path.exists("/tmp/.X11-unix/X{}".format(display)): return display display += 1
python
def _get_free_display_port(self): display = 100 if not os.path.exists("/tmp/.X11-unix/"): return display while True: if not os.path.exists("/tmp/.X11-unix/X{}".format(display)): return display display += 1
[ "def", "_get_free_display_port", "(", "self", ")", ":", "display", "=", "100", "if", "not", "os", ".", "path", ".", "exists", "(", "\"/tmp/.X11-unix/\"", ")", ":", "return", "display", "while", "True", ":", "if", "not", "os", ".", "path", ".", "exists", ...
Search a free display port
[ "Search", "a", "free", "display", "port" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L120-L130
240,374
GNS3/gns3-server
gns3server/compute/docker/docker_vm.py
DockerVM.create
def create(self): """Creates the Docker container.""" try: image_infos = yield from self._get_image_information() except DockerHttp404Error: log.info("Image %s is missing pulling it from docker hub", self._image) yield from self.pull_image(self._image) image_infos = yield from self._get_image_information() if image_infos is None: raise DockerError("Can't get image informations, please try again.") params = { "Hostname": self._name, "Name": self._name, "Image": self._image, "NetworkDisabled": True, "Tty": True, "OpenStdin": True, "StdinOnce": False, "HostConfig": { "CapAdd": ["ALL"], "Privileged": True, "Binds": self._mount_binds(image_infos) }, "Volumes": {}, "Env": ["container=docker"], # Systemd compliant: https://github.com/GNS3/gns3-server/issues/573 "Cmd": [], "Entrypoint": image_infos.get("Config", {"Entrypoint": []})["Entrypoint"] } if params["Entrypoint"] is None: params["Entrypoint"] = [] if self._start_command: params["Cmd"] = shlex.split(self._start_command) if len(params["Cmd"]) == 0: params["Cmd"] = image_infos.get("Config", {"Cmd": []})["Cmd"] if params["Cmd"] is None: params["Cmd"] = [] if len(params["Cmd"]) == 0 and len(params["Entrypoint"]) == 0: params["Cmd"] = ["/bin/sh"] params["Entrypoint"].insert(0, "/gns3/init.sh") # FIXME /gns3/init.sh is not found? # Give the information to the container on how many interface should be inside params["Env"].append("GNS3_MAX_ETHERNET=eth{}".format(self.adapters - 1)) # Give the information to the container the list of volume path mounted params["Env"].append("GNS3_VOLUMES={}".format(":".join(self._volumes))) if self._environment: for e in self._environment.strip().split("\n"): e = e.strip() if not e.startswith("GNS3_"): params["Env"].append(e) if self._console_type == "vnc": yield from self._start_vnc() params["Env"].append("QT_GRAPHICSSYSTEM=native") # To fix a Qt issue: https://github.com/GNS3/gns3-server/issues/556 params["Env"].append("DISPLAY=:{}".format(self._display)) params["HostConfig"]["Binds"].append("/tmp/.X11-unix/:/tmp/.X11-unix/") result = yield from self.manager.query("POST", "containers/create", data=params) self._cid = result['Id'] log.info("Docker container '{name}' [{id}] created".format( name=self._name, id=self._id)) return True
python
def create(self): try: image_infos = yield from self._get_image_information() except DockerHttp404Error: log.info("Image %s is missing pulling it from docker hub", self._image) yield from self.pull_image(self._image) image_infos = yield from self._get_image_information() if image_infos is None: raise DockerError("Can't get image informations, please try again.") params = { "Hostname": self._name, "Name": self._name, "Image": self._image, "NetworkDisabled": True, "Tty": True, "OpenStdin": True, "StdinOnce": False, "HostConfig": { "CapAdd": ["ALL"], "Privileged": True, "Binds": self._mount_binds(image_infos) }, "Volumes": {}, "Env": ["container=docker"], # Systemd compliant: https://github.com/GNS3/gns3-server/issues/573 "Cmd": [], "Entrypoint": image_infos.get("Config", {"Entrypoint": []})["Entrypoint"] } if params["Entrypoint"] is None: params["Entrypoint"] = [] if self._start_command: params["Cmd"] = shlex.split(self._start_command) if len(params["Cmd"]) == 0: params["Cmd"] = image_infos.get("Config", {"Cmd": []})["Cmd"] if params["Cmd"] is None: params["Cmd"] = [] if len(params["Cmd"]) == 0 and len(params["Entrypoint"]) == 0: params["Cmd"] = ["/bin/sh"] params["Entrypoint"].insert(0, "/gns3/init.sh") # FIXME /gns3/init.sh is not found? # Give the information to the container on how many interface should be inside params["Env"].append("GNS3_MAX_ETHERNET=eth{}".format(self.adapters - 1)) # Give the information to the container the list of volume path mounted params["Env"].append("GNS3_VOLUMES={}".format(":".join(self._volumes))) if self._environment: for e in self._environment.strip().split("\n"): e = e.strip() if not e.startswith("GNS3_"): params["Env"].append(e) if self._console_type == "vnc": yield from self._start_vnc() params["Env"].append("QT_GRAPHICSSYSTEM=native") # To fix a Qt issue: https://github.com/GNS3/gns3-server/issues/556 params["Env"].append("DISPLAY=:{}".format(self._display)) params["HostConfig"]["Binds"].append("/tmp/.X11-unix/:/tmp/.X11-unix/") result = yield from self.manager.query("POST", "containers/create", data=params) self._cid = result['Id'] log.info("Docker container '{name}' [{id}] created".format( name=self._name, id=self._id)) return True
[ "def", "create", "(", "self", ")", ":", "try", ":", "image_infos", "=", "yield", "from", "self", ".", "_get_image_information", "(", ")", "except", "DockerHttp404Error", ":", "log", ".", "info", "(", "\"Image %s is missing pulling it from docker hub\"", ",", "self...
Creates the Docker container.
[ "Creates", "the", "Docker", "container", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L268-L332
240,375
GNS3/gns3-server
gns3server/compute/docker/docker_vm.py
DockerVM.update
def update(self): """ Destroy an recreate the container with the new settings """ # We need to save the console and state and restore it console = self.console aux = self.aux state = yield from self._get_container_state() yield from self.reset() yield from self.create() self.console = console self.aux = aux if state == "running": yield from self.start()
python
def update(self): # We need to save the console and state and restore it console = self.console aux = self.aux state = yield from self._get_container_state() yield from self.reset() yield from self.create() self.console = console self.aux = aux if state == "running": yield from self.start()
[ "def", "update", "(", "self", ")", ":", "# We need to save the console and state and restore it", "console", "=", "self", ".", "console", "aux", "=", "self", ".", "aux", "state", "=", "yield", "from", "self", ".", "_get_container_state", "(", ")", "yield", "from...
Destroy an recreate the container with the new settings
[ "Destroy", "an", "recreate", "the", "container", "with", "the", "new", "settings" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L335-L349
240,376
GNS3/gns3-server
gns3server/compute/docker/docker_vm.py
DockerVM.start
def start(self): """Starts this Docker container.""" try: state = yield from self._get_container_state() except DockerHttp404Error: raise DockerError("Docker container '{name}' with ID {cid} does not exist or is not ready yet. Please try again in a few seconds.".format(name=self.name, cid=self._cid)) if state == "paused": yield from self.unpause() elif state == "running": return else: yield from self._clean_servers() yield from self.manager.query("POST", "containers/{}/start".format(self._cid)) self._namespace = yield from self._get_namespace() yield from self._start_ubridge() for adapter_number in range(0, self.adapters): nio = self._ethernet_adapters[adapter_number].get_nio(0) with (yield from self.manager.ubridge_lock): try: yield from self._add_ubridge_connection(nio, adapter_number) except UbridgeNamespaceError: log.error("Container %s failed to start", self.name) yield from self.stop() # The container can crash soon after the start, this means we can not move the interface to the container namespace logdata = yield from self._get_log() for line in logdata.split('\n'): log.error(line) raise DockerError(logdata) if self.console_type == "telnet": yield from self._start_console() elif self.console_type == "http" or self.console_type == "https": yield from self._start_http() if self.allocate_aux: yield from self._start_aux() self.status = "started" log.info("Docker container '{name}' [{image}] started listen for {console_type} on {console}".format(name=self._name, image=self._image, console=self.console, console_type=self.console_type))
python
def start(self): try: state = yield from self._get_container_state() except DockerHttp404Error: raise DockerError("Docker container '{name}' with ID {cid} does not exist or is not ready yet. Please try again in a few seconds.".format(name=self.name, cid=self._cid)) if state == "paused": yield from self.unpause() elif state == "running": return else: yield from self._clean_servers() yield from self.manager.query("POST", "containers/{}/start".format(self._cid)) self._namespace = yield from self._get_namespace() yield from self._start_ubridge() for adapter_number in range(0, self.adapters): nio = self._ethernet_adapters[adapter_number].get_nio(0) with (yield from self.manager.ubridge_lock): try: yield from self._add_ubridge_connection(nio, adapter_number) except UbridgeNamespaceError: log.error("Container %s failed to start", self.name) yield from self.stop() # The container can crash soon after the start, this means we can not move the interface to the container namespace logdata = yield from self._get_log() for line in logdata.split('\n'): log.error(line) raise DockerError(logdata) if self.console_type == "telnet": yield from self._start_console() elif self.console_type == "http" or self.console_type == "https": yield from self._start_http() if self.allocate_aux: yield from self._start_aux() self.status = "started" log.info("Docker container '{name}' [{image}] started listen for {console_type} on {console}".format(name=self._name, image=self._image, console=self.console, console_type=self.console_type))
[ "def", "start", "(", "self", ")", ":", "try", ":", "state", "=", "yield", "from", "self", ".", "_get_container_state", "(", ")", "except", "DockerHttp404Error", ":", "raise", "DockerError", "(", "\"Docker container '{name}' with ID {cid} does not exist or is not ready y...
Starts this Docker container.
[ "Starts", "this", "Docker", "container", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L352-L399
240,377
GNS3/gns3-server
gns3server/compute/docker/docker_vm.py
DockerVM._start_aux
def _start_aux(self): """ Start an auxilary console """ # We can not use the API because docker doesn't expose a websocket api for exec # https://github.com/GNS3/gns3-gui/issues/1039 process = yield from asyncio.subprocess.create_subprocess_exec( "docker", "exec", "-i", self._cid, "/gns3/bin/busybox", "script", "-qfc", "while true; do TERM=vt100 /gns3/bin/busybox sh; done", "/dev/null", stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT, stdin=asyncio.subprocess.PIPE) server = AsyncioTelnetServer(reader=process.stdout, writer=process.stdin, binary=True, echo=True) self._telnet_servers.append((yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.aux))) log.debug("Docker container '%s' started listen for auxilary telnet on %d", self.name, self.aux)
python
def _start_aux(self): # We can not use the API because docker doesn't expose a websocket api for exec # https://github.com/GNS3/gns3-gui/issues/1039 process = yield from asyncio.subprocess.create_subprocess_exec( "docker", "exec", "-i", self._cid, "/gns3/bin/busybox", "script", "-qfc", "while true; do TERM=vt100 /gns3/bin/busybox sh; done", "/dev/null", stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT, stdin=asyncio.subprocess.PIPE) server = AsyncioTelnetServer(reader=process.stdout, writer=process.stdin, binary=True, echo=True) self._telnet_servers.append((yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.aux))) log.debug("Docker container '%s' started listen for auxilary telnet on %d", self.name, self.aux)
[ "def", "_start_aux", "(", "self", ")", ":", "# We can not use the API because docker doesn't expose a websocket api for exec", "# https://github.com/GNS3/gns3-gui/issues/1039", "process", "=", "yield", "from", "asyncio", ".", "subprocess", ".", "create_subprocess_exec", "(", "\"d...
Start an auxilary console
[ "Start", "an", "auxilary", "console" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L402-L416
240,378
GNS3/gns3-server
gns3server/compute/docker/docker_vm.py
DockerVM._fix_permissions
def _fix_permissions(self): """ Because docker run as root we need to fix permission and ownership to allow user to interact with it from their filesystem and do operation like file delete """ state = yield from self._get_container_state() if state == "stopped" or state == "exited": # We need to restart it to fix permissions yield from self.manager.query("POST", "containers/{}/start".format(self._cid)) for volume in self._volumes: log.debug("Docker container '{name}' [{image}] fix ownership on {path}".format( name=self._name, image=self._image, path=volume)) process = yield from asyncio.subprocess.create_subprocess_exec( "docker", "exec", self._cid, "/gns3/bin/busybox", "sh", "-c", "(" "/gns3/bin/busybox find \"{path}\" -depth -print0" " | /gns3/bin/busybox xargs -0 /gns3/bin/busybox stat -c '%a:%u:%g:%n' > \"{path}/.gns3_perms\"" ")" " && /gns3/bin/busybox chmod -R u+rX \"{path}\"" " && /gns3/bin/busybox chown {uid}:{gid} -R \"{path}\"" .format(uid=os.getuid(), gid=os.getgid(), path=volume), ) yield from process.wait()
python
def _fix_permissions(self): state = yield from self._get_container_state() if state == "stopped" or state == "exited": # We need to restart it to fix permissions yield from self.manager.query("POST", "containers/{}/start".format(self._cid)) for volume in self._volumes: log.debug("Docker container '{name}' [{image}] fix ownership on {path}".format( name=self._name, image=self._image, path=volume)) process = yield from asyncio.subprocess.create_subprocess_exec( "docker", "exec", self._cid, "/gns3/bin/busybox", "sh", "-c", "(" "/gns3/bin/busybox find \"{path}\" -depth -print0" " | /gns3/bin/busybox xargs -0 /gns3/bin/busybox stat -c '%a:%u:%g:%n' > \"{path}/.gns3_perms\"" ")" " && /gns3/bin/busybox chmod -R u+rX \"{path}\"" " && /gns3/bin/busybox chown {uid}:{gid} -R \"{path}\"" .format(uid=os.getuid(), gid=os.getgid(), path=volume), ) yield from process.wait()
[ "def", "_fix_permissions", "(", "self", ")", ":", "state", "=", "yield", "from", "self", ".", "_get_container_state", "(", ")", "if", "state", "==", "\"stopped\"", "or", "state", "==", "\"exited\"", ":", "# We need to restart it to fix permissions", "yield", "from...
Because docker run as root we need to fix permission and ownership to allow user to interact with it from their filesystem and do operation like file delete
[ "Because", "docker", "run", "as", "root", "we", "need", "to", "fix", "permission", "and", "ownership", "to", "allow", "user", "to", "interact", "with", "it", "from", "their", "filesystem", "and", "do", "operation", "like", "file", "delete" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L419-L448
240,379
GNS3/gns3-server
gns3server/compute/docker/docker_vm.py
DockerVM._start_vnc
def _start_vnc(self): """ Start a VNC server for this container """ self._display = self._get_free_display_port() if shutil.which("Xvfb") is None or shutil.which("x11vnc") is None: raise DockerError("Please install Xvfb and x11vnc before using the VNC support") self._xvfb_process = yield from asyncio.create_subprocess_exec("Xvfb", "-nolisten", "tcp", ":{}".format(self._display), "-screen", "0", self._console_resolution + "x16") # We pass a port for TCPV6 due to a crash in X11VNC if not here: https://github.com/GNS3/gns3-server/issues/569 self._x11vnc_process = yield from asyncio.create_subprocess_exec("x11vnc", "-forever", "-nopw", "-shared", "-geometry", self._console_resolution, "-display", "WAIT:{}".format(self._display), "-rfbport", str(self.console), "-rfbportv6", str(self.console), "-noncache", "-listen", self._manager.port_manager.console_host) x11_socket = os.path.join("/tmp/.X11-unix/", "X{}".format(self._display)) yield from wait_for_file_creation(x11_socket)
python
def _start_vnc(self): self._display = self._get_free_display_port() if shutil.which("Xvfb") is None or shutil.which("x11vnc") is None: raise DockerError("Please install Xvfb and x11vnc before using the VNC support") self._xvfb_process = yield from asyncio.create_subprocess_exec("Xvfb", "-nolisten", "tcp", ":{}".format(self._display), "-screen", "0", self._console_resolution + "x16") # We pass a port for TCPV6 due to a crash in X11VNC if not here: https://github.com/GNS3/gns3-server/issues/569 self._x11vnc_process = yield from asyncio.create_subprocess_exec("x11vnc", "-forever", "-nopw", "-shared", "-geometry", self._console_resolution, "-display", "WAIT:{}".format(self._display), "-rfbport", str(self.console), "-rfbportv6", str(self.console), "-noncache", "-listen", self._manager.port_manager.console_host) x11_socket = os.path.join("/tmp/.X11-unix/", "X{}".format(self._display)) yield from wait_for_file_creation(x11_socket)
[ "def", "_start_vnc", "(", "self", ")", ":", "self", ".", "_display", "=", "self", ".", "_get_free_display_port", "(", ")", "if", "shutil", ".", "which", "(", "\"Xvfb\"", ")", "is", "None", "or", "shutil", ".", "which", "(", "\"x11vnc\"", ")", "is", "No...
Start a VNC server for this container
[ "Start", "a", "VNC", "server", "for", "this", "container" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L451-L464
240,380
GNS3/gns3-server
gns3server/compute/docker/docker_vm.py
DockerVM._start_http
def _start_http(self): """ Start an HTTP tunnel to container localhost. It's not perfect but the only way we have to inject network packet is using nc. """ log.debug("Forward HTTP for %s to %d", self.name, self._console_http_port) command = ["docker", "exec", "-i", self._cid, "/gns3/bin/busybox", "nc", "127.0.0.1", str(self._console_http_port)] # We replace host and port in the server answer otherwise some link could be broken server = AsyncioRawCommandServer(command, replaces=[ ( '://127.0.0.1'.encode(), # {{HOST}} mean client host '://{{HOST}}'.encode(), ), ( ':{}'.format(self._console_http_port).encode(), ':{}'.format(self.console).encode(), ) ]) self._telnet_servers.append((yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console)))
python
def _start_http(self): log.debug("Forward HTTP for %s to %d", self.name, self._console_http_port) command = ["docker", "exec", "-i", self._cid, "/gns3/bin/busybox", "nc", "127.0.0.1", str(self._console_http_port)] # We replace host and port in the server answer otherwise some link could be broken server = AsyncioRawCommandServer(command, replaces=[ ( '://127.0.0.1'.encode(), # {{HOST}} mean client host '://{{HOST}}'.encode(), ), ( ':{}'.format(self._console_http_port).encode(), ':{}'.format(self.console).encode(), ) ]) self._telnet_servers.append((yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console)))
[ "def", "_start_http", "(", "self", ")", ":", "log", ".", "debug", "(", "\"Forward HTTP for %s to %d\"", ",", "self", ".", "name", ",", "self", ".", "_console_http_port", ")", "command", "=", "[", "\"docker\"", ",", "\"exec\"", ",", "\"-i\"", ",", "self", "...
Start an HTTP tunnel to container localhost. It's not perfect but the only way we have to inject network packet is using nc.
[ "Start", "an", "HTTP", "tunnel", "to", "container", "localhost", ".", "It", "s", "not", "perfect", "but", "the", "only", "way", "we", "have", "to", "inject", "network", "packet", "is", "using", "nc", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L467-L485
240,381
GNS3/gns3-server
gns3server/compute/docker/docker_vm.py
DockerVM._start_console
def _start_console(self): """ Start streaming the console via telnet """ class InputStream: def __init__(self): self._data = b"" def write(self, data): self._data += data @asyncio.coroutine def drain(self): if not self.ws.closed: self.ws.send_bytes(self._data) self._data = b"" output_stream = asyncio.StreamReader() input_stream = InputStream() telnet = AsyncioTelnetServer(reader=output_stream, writer=input_stream, echo=True) self._telnet_servers.append((yield from asyncio.start_server(telnet.run, self._manager.port_manager.console_host, self.console))) self._console_websocket = yield from self.manager.websocket_query("containers/{}/attach/ws?stream=1&stdin=1&stdout=1&stderr=1".format(self._cid)) input_stream.ws = self._console_websocket output_stream.feed_data(self.name.encode() + b" console is now available... Press RETURN to get started.\r\n") asyncio.async(self._read_console_output(self._console_websocket, output_stream))
python
def _start_console(self): class InputStream: def __init__(self): self._data = b"" def write(self, data): self._data += data @asyncio.coroutine def drain(self): if not self.ws.closed: self.ws.send_bytes(self._data) self._data = b"" output_stream = asyncio.StreamReader() input_stream = InputStream() telnet = AsyncioTelnetServer(reader=output_stream, writer=input_stream, echo=True) self._telnet_servers.append((yield from asyncio.start_server(telnet.run, self._manager.port_manager.console_host, self.console))) self._console_websocket = yield from self.manager.websocket_query("containers/{}/attach/ws?stream=1&stdin=1&stdout=1&stderr=1".format(self._cid)) input_stream.ws = self._console_websocket output_stream.feed_data(self.name.encode() + b" console is now available... Press RETURN to get started.\r\n") asyncio.async(self._read_console_output(self._console_websocket, output_stream))
[ "def", "_start_console", "(", "self", ")", ":", "class", "InputStream", ":", "def", "__init__", "(", "self", ")", ":", "self", ".", "_data", "=", "b\"\"", "def", "write", "(", "self", ",", "data", ")", ":", "self", ".", "_data", "+=", "data", "@", ...
Start streaming the console via telnet
[ "Start", "streaming", "the", "console", "via", "telnet" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L488-L518
240,382
GNS3/gns3-server
gns3server/compute/docker/docker_vm.py
DockerVM._read_console_output
def _read_console_output(self, ws, out): """ Read Websocket and forward it to the telnet :param ws: Websocket connection :param out: Output stream """ while True: msg = yield from ws.receive() if msg.tp == aiohttp.WSMsgType.text: out.feed_data(msg.data.encode()) elif msg.tp == aiohttp.WSMsgType.BINARY: out.feed_data(msg.data) elif msg.tp == aiohttp.WSMsgType.ERROR: log.critical("Docker WebSocket Error: {}".format(msg.data)) else: out.feed_eof() ws.close() break yield from self.stop()
python
def _read_console_output(self, ws, out): while True: msg = yield from ws.receive() if msg.tp == aiohttp.WSMsgType.text: out.feed_data(msg.data.encode()) elif msg.tp == aiohttp.WSMsgType.BINARY: out.feed_data(msg.data) elif msg.tp == aiohttp.WSMsgType.ERROR: log.critical("Docker WebSocket Error: {}".format(msg.data)) else: out.feed_eof() ws.close() break yield from self.stop()
[ "def", "_read_console_output", "(", "self", ",", "ws", ",", "out", ")", ":", "while", "True", ":", "msg", "=", "yield", "from", "ws", ".", "receive", "(", ")", "if", "msg", ".", "tp", "==", "aiohttp", ".", "WSMsgType", ".", "text", ":", "out", ".",...
Read Websocket and forward it to the telnet :param ws: Websocket connection :param out: Output stream
[ "Read", "Websocket", "and", "forward", "it", "to", "the", "telnet" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L521-L541
240,383
GNS3/gns3-server
gns3server/compute/docker/docker_vm.py
DockerVM.is_running
def is_running(self): """Checks if the container is running. :returns: True or False :rtype: bool """ state = yield from self._get_container_state() if state == "running": return True if self.status == "started": # The container crashed we need to clean yield from self.stop() return False
python
def is_running(self): state = yield from self._get_container_state() if state == "running": return True if self.status == "started": # The container crashed we need to clean yield from self.stop() return False
[ "def", "is_running", "(", "self", ")", ":", "state", "=", "yield", "from", "self", ".", "_get_container_state", "(", ")", "if", "state", "==", "\"running\"", ":", "return", "True", "if", "self", ".", "status", "==", "\"started\"", ":", "# The container crash...
Checks if the container is running. :returns: True or False :rtype: bool
[ "Checks", "if", "the", "container", "is", "running", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L544-L555
240,384
GNS3/gns3-server
gns3server/compute/docker/docker_vm.py
DockerVM.restart
def restart(self): """Restart this Docker container.""" yield from self.manager.query("POST", "containers/{}/restart".format(self._cid)) log.info("Docker container '{name}' [{image}] restarted".format( name=self._name, image=self._image))
python
def restart(self): yield from self.manager.query("POST", "containers/{}/restart".format(self._cid)) log.info("Docker container '{name}' [{image}] restarted".format( name=self._name, image=self._image))
[ "def", "restart", "(", "self", ")", ":", "yield", "from", "self", ".", "manager", ".", "query", "(", "\"POST\"", ",", "\"containers/{}/restart\"", ".", "format", "(", "self", ".", "_cid", ")", ")", "log", ".", "info", "(", "\"Docker container '{name}' [{imag...
Restart this Docker container.
[ "Restart", "this", "Docker", "container", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L558-L562
240,385
GNS3/gns3-server
gns3server/compute/docker/docker_vm.py
DockerVM._clean_servers
def _clean_servers(self): """ Clean the list of running console servers """ if len(self._telnet_servers) > 0: for telnet_server in self._telnet_servers: telnet_server.close() yield from telnet_server.wait_closed() self._telnet_servers = []
python
def _clean_servers(self): if len(self._telnet_servers) > 0: for telnet_server in self._telnet_servers: telnet_server.close() yield from telnet_server.wait_closed() self._telnet_servers = []
[ "def", "_clean_servers", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_telnet_servers", ")", ">", "0", ":", "for", "telnet_server", "in", "self", ".", "_telnet_servers", ":", "telnet_server", ".", "close", "(", ")", "yield", "from", "telnet_serve...
Clean the list of running console servers
[ "Clean", "the", "list", "of", "running", "console", "servers" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L565-L573
240,386
GNS3/gns3-server
gns3server/compute/docker/docker_vm.py
DockerVM.stop
def stop(self): """Stops this Docker container.""" try: yield from self._clean_servers() yield from self._stop_ubridge() try: state = yield from self._get_container_state() except DockerHttp404Error: self.status = "stopped" return if state == "paused": yield from self.unpause() yield from self._fix_permissions() state = yield from self._get_container_state() if state != "stopped" or state != "exited": # t=5 number of seconds to wait before killing the container try: yield from self.manager.query("POST", "containers/{}/stop".format(self._cid), params={"t": 5}) log.info("Docker container '{name}' [{image}] stopped".format( name=self._name, image=self._image)) except DockerHttp304Error: # Container is already stopped pass # Ignore runtime error because when closing the server except RuntimeError as e: log.debug("Docker runtime error when closing: {}".format(str(e))) return self.status = "stopped"
python
def stop(self): try: yield from self._clean_servers() yield from self._stop_ubridge() try: state = yield from self._get_container_state() except DockerHttp404Error: self.status = "stopped" return if state == "paused": yield from self.unpause() yield from self._fix_permissions() state = yield from self._get_container_state() if state != "stopped" or state != "exited": # t=5 number of seconds to wait before killing the container try: yield from self.manager.query("POST", "containers/{}/stop".format(self._cid), params={"t": 5}) log.info("Docker container '{name}' [{image}] stopped".format( name=self._name, image=self._image)) except DockerHttp304Error: # Container is already stopped pass # Ignore runtime error because when closing the server except RuntimeError as e: log.debug("Docker runtime error when closing: {}".format(str(e))) return self.status = "stopped"
[ "def", "stop", "(", "self", ")", ":", "try", ":", "yield", "from", "self", ".", "_clean_servers", "(", ")", "yield", "from", "self", ".", "_stop_ubridge", "(", ")", "try", ":", "state", "=", "yield", "from", "self", ".", "_get_container_state", "(", ")...
Stops this Docker container.
[ "Stops", "this", "Docker", "container", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L576-L607
240,387
GNS3/gns3-server
gns3server/compute/docker/docker_vm.py
DockerVM.pause
def pause(self): """Pauses this Docker container.""" yield from self.manager.query("POST", "containers/{}/pause".format(self._cid)) self.status = "suspended" log.info("Docker container '{name}' [{image}] paused".format(name=self._name, image=self._image))
python
def pause(self): yield from self.manager.query("POST", "containers/{}/pause".format(self._cid)) self.status = "suspended" log.info("Docker container '{name}' [{image}] paused".format(name=self._name, image=self._image))
[ "def", "pause", "(", "self", ")", ":", "yield", "from", "self", ".", "manager", ".", "query", "(", "\"POST\"", ",", "\"containers/{}/pause\"", ".", "format", "(", "self", ".", "_cid", ")", ")", "self", ".", "status", "=", "\"suspended\"", "log", ".", "...
Pauses this Docker container.
[ "Pauses", "this", "Docker", "container", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L610-L614
240,388
GNS3/gns3-server
gns3server/compute/docker/docker_vm.py
DockerVM._get_log
def _get_log(self): """ Return the log from the container :returns: string """ result = yield from self.manager.query("GET", "containers/{}/logs".format(self._cid), params={"stderr": 1, "stdout": 1}) return result
python
def _get_log(self): result = yield from self.manager.query("GET", "containers/{}/logs".format(self._cid), params={"stderr": 1, "stdout": 1}) return result
[ "def", "_get_log", "(", "self", ")", ":", "result", "=", "yield", "from", "self", ".", "manager", ".", "query", "(", "\"GET\"", ",", "\"containers/{}/logs\"", ".", "format", "(", "self", ".", "_cid", ")", ",", "params", "=", "{", "\"stderr\"", ":", "1"...
Return the log from the container :returns: string
[ "Return", "the", "log", "from", "the", "container" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L916-L924
240,389
GNS3/gns3-server
gns3server/compute/iou/utils/application_id.py
get_next_application_id
def get_next_application_id(nodes): """ Calculates free application_id from given nodes :param nodes: :raises IOUError when exceeds number :return: integer first free id """ used = set([n.application_id for n in nodes]) pool = set(range(1, 512)) try: return (pool - used).pop() except KeyError: raise IOUError("Cannot create a new IOU VM (limit of 512 VMs on one host reached)")
python
def get_next_application_id(nodes): used = set([n.application_id for n in nodes]) pool = set(range(1, 512)) try: return (pool - used).pop() except KeyError: raise IOUError("Cannot create a new IOU VM (limit of 512 VMs on one host reached)")
[ "def", "get_next_application_id", "(", "nodes", ")", ":", "used", "=", "set", "(", "[", "n", ".", "application_id", "for", "n", "in", "nodes", "]", ")", "pool", "=", "set", "(", "range", "(", "1", ",", "512", ")", ")", "try", ":", "return", "(", ...
Calculates free application_id from given nodes :param nodes: :raises IOUError when exceeds number :return: integer first free id
[ "Calculates", "free", "application_id", "from", "given", "nodes" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/utils/application_id.py#L24-L37
240,390
GNS3/gns3-server
gns3server/config.py
Config.clear
def clear(self): """Restart with a clean config""" self._config = configparser.RawConfigParser() # Override config from command line even if we modify the config file and live reload it. self._override_config = {} self.read_config()
python
def clear(self): self._config = configparser.RawConfigParser() # Override config from command line even if we modify the config file and live reload it. self._override_config = {} self.read_config()
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_config", "=", "configparser", ".", "RawConfigParser", "(", ")", "# Override config from command line even if we modify the config file and live reload it.", "self", ".", "_override_config", "=", "{", "}", "self", "."...
Restart with a clean config
[ "Restart", "with", "a", "clean", "config" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/config.py#L137-L143
240,391
GNS3/gns3-server
gns3server/config.py
Config.read_config
def read_config(self): """ Read the configuration files. """ try: parsed_files = self._config.read(self._files, encoding="utf-8") except configparser.Error as e: log.error("Can't parse configuration file: %s", str(e)) return if not parsed_files: log.warning("No configuration file could be found or read") else: for file in parsed_files: log.info("Load configuration file {}".format(file)) self._watched_files[file] = os.stat(file).st_mtime
python
def read_config(self): try: parsed_files = self._config.read(self._files, encoding="utf-8") except configparser.Error as e: log.error("Can't parse configuration file: %s", str(e)) return if not parsed_files: log.warning("No configuration file could be found or read") else: for file in parsed_files: log.info("Load configuration file {}".format(file)) self._watched_files[file] = os.stat(file).st_mtime
[ "def", "read_config", "(", "self", ")", ":", "try", ":", "parsed_files", "=", "self", ".", "_config", ".", "read", "(", "self", ".", "_files", ",", "encoding", "=", "\"utf-8\"", ")", "except", "configparser", ".", "Error", "as", "e", ":", "log", ".", ...
Read the configuration files.
[ "Read", "the", "configuration", "files", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/config.py#L169-L184
240,392
GNS3/gns3-server
gns3server/config.py
Config.get_section_config
def get_section_config(self, section): """ Get a specific configuration section. Returns the default section if none can be found. :returns: configparser section """ if section not in self._config: return self._config["DEFAULT"] return self._config[section]
python
def get_section_config(self, section): if section not in self._config: return self._config["DEFAULT"] return self._config[section]
[ "def", "get_section_config", "(", "self", ",", "section", ")", ":", "if", "section", "not", "in", "self", ".", "_config", ":", "return", "self", ".", "_config", "[", "\"DEFAULT\"", "]", "return", "self", ".", "_config", "[", "section", "]" ]
Get a specific configuration section. Returns the default section if none can be found. :returns: configparser section
[ "Get", "a", "specific", "configuration", "section", ".", "Returns", "the", "default", "section", "if", "none", "can", "be", "found", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/config.py#L195-L205
240,393
GNS3/gns3-server
gns3server/config.py
Config.set_section_config
def set_section_config(self, section, content): """ Set a specific configuration section. It's not dumped on the disk. :param section: Section name :param content: A dictionary with section content """ if not self._config.has_section(section): self._config.add_section(section) for key in content: if isinstance(content[key], bool): content[key] = str(content[key]).lower() self._config.set(section, key, content[key]) self._override_config[section] = content
python
def set_section_config(self, section, content): if not self._config.has_section(section): self._config.add_section(section) for key in content: if isinstance(content[key], bool): content[key] = str(content[key]).lower() self._config.set(section, key, content[key]) self._override_config[section] = content
[ "def", "set_section_config", "(", "self", ",", "section", ",", "content", ")", ":", "if", "not", "self", ".", "_config", ".", "has_section", "(", "section", ")", ":", "self", ".", "_config", ".", "add_section", "(", "section", ")", "for", "key", "in", ...
Set a specific configuration section. It's not dumped on the disk. :param section: Section name :param content: A dictionary with section content
[ "Set", "a", "specific", "configuration", "section", ".", "It", "s", "not", "dumped", "on", "the", "disk", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/config.py#L207-L222
240,394
GNS3/gns3-server
gns3server/config.py
Config.set
def set(self, section, key, value): """ Set a config value. It's not dumped on the disk. If the section doesn't exists the section is created """ conf = self.get_section_config(section) if isinstance(value, bool): conf[key] = str(value) else: conf[key] = value self.set_section_config(section, conf)
python
def set(self, section, key, value): conf = self.get_section_config(section) if isinstance(value, bool): conf[key] = str(value) else: conf[key] = value self.set_section_config(section, conf)
[ "def", "set", "(", "self", ",", "section", ",", "key", ",", "value", ")", ":", "conf", "=", "self", ".", "get_section_config", "(", "section", ")", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "conf", "[", "key", "]", "=", "str", "(", ...
Set a config value. It's not dumped on the disk. If the section doesn't exists the section is created
[ "Set", "a", "config", "value", ".", "It", "s", "not", "dumped", "on", "the", "disk", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/config.py#L224-L237
240,395
GNS3/gns3-server
gns3server/config.py
Config.instance
def instance(*args, **kwargs): """ Singleton to return only one instance of Config. :returns: instance of Config """ if not hasattr(Config, "_instance") or Config._instance is None: Config._instance = Config(*args, **kwargs) return Config._instance
python
def instance(*args, **kwargs): if not hasattr(Config, "_instance") or Config._instance is None: Config._instance = Config(*args, **kwargs) return Config._instance
[ "def", "instance", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "hasattr", "(", "Config", ",", "\"_instance\"", ")", "or", "Config", ".", "_instance", "is", "None", ":", "Config", ".", "_instance", "=", "Config", "(", "*", "args"...
Singleton to return only one instance of Config. :returns: instance of Config
[ "Singleton", "to", "return", "only", "one", "instance", "of", "Config", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/config.py#L240-L249
240,396
GNS3/gns3-server
gns3server/utils/asyncio/__init__.py
wait_run_in_executor
def wait_run_in_executor(func, *args, **kwargs): """ Run blocking code in a different thread and wait for the result. :param func: Run this function in a different thread :param args: Parameters of the function :param kwargs: Keyword parameters of the function :returns: Return the result of the function """ loop = asyncio.get_event_loop() future = loop.run_in_executor(None, functools.partial(func, *args, **kwargs)) yield from asyncio.wait([future]) return future.result()
python
def wait_run_in_executor(func, *args, **kwargs): loop = asyncio.get_event_loop() future = loop.run_in_executor(None, functools.partial(func, *args, **kwargs)) yield from asyncio.wait([future]) return future.result()
[ "def", "wait_run_in_executor", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "future", "=", "loop", ".", "run_in_executor", "(", "None", ",", "functools", ".", "partial", "(", ...
Run blocking code in a different thread and wait for the result. :param func: Run this function in a different thread :param args: Parameters of the function :param kwargs: Keyword parameters of the function :returns: Return the result of the function
[ "Run", "blocking", "code", "in", "a", "different", "thread", "and", "wait", "for", "the", "result", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/__init__.py#L26-L40
240,397
GNS3/gns3-server
gns3server/utils/asyncio/__init__.py
subprocess_check_output
def subprocess_check_output(*args, cwd=None, env=None, stderr=False): """ Run a command and capture output :param *args: List of command arguments :param cwd: Current working directory :param env: Command environment :param stderr: Read on stderr :returns: Command output """ if stderr: proc = yield from asyncio.create_subprocess_exec(*args, stderr=asyncio.subprocess.PIPE, cwd=cwd, env=env) output = yield from proc.stderr.read() else: proc = yield from asyncio.create_subprocess_exec(*args, stdout=asyncio.subprocess.PIPE, cwd=cwd, env=env) output = yield from proc.stdout.read() if output is None: return "" # If we received garbage we ignore invalid characters # it should happens only when user try to use another binary # and the code of VPCS, dynamips... Will detect it's not the correct binary return output.decode("utf-8", errors="ignore")
python
def subprocess_check_output(*args, cwd=None, env=None, stderr=False): if stderr: proc = yield from asyncio.create_subprocess_exec(*args, stderr=asyncio.subprocess.PIPE, cwd=cwd, env=env) output = yield from proc.stderr.read() else: proc = yield from asyncio.create_subprocess_exec(*args, stdout=asyncio.subprocess.PIPE, cwd=cwd, env=env) output = yield from proc.stdout.read() if output is None: return "" # If we received garbage we ignore invalid characters # it should happens only when user try to use another binary # and the code of VPCS, dynamips... Will detect it's not the correct binary return output.decode("utf-8", errors="ignore")
[ "def", "subprocess_check_output", "(", "*", "args", ",", "cwd", "=", "None", ",", "env", "=", "None", ",", "stderr", "=", "False", ")", ":", "if", "stderr", ":", "proc", "=", "yield", "from", "asyncio", ".", "create_subprocess_exec", "(", "*", "args", ...
Run a command and capture output :param *args: List of command arguments :param cwd: Current working directory :param env: Command environment :param stderr: Read on stderr :returns: Command output
[ "Run", "a", "command", "and", "capture", "output" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/__init__.py#L44-L66
240,398
GNS3/gns3-server
gns3server/utils/asyncio/__init__.py
wait_for_process_termination
def wait_for_process_termination(process, timeout=10): """ Wait for a process terminate, and raise asyncio.TimeoutError in case of timeout. In theory this can be implemented by just: yield from asyncio.wait_for(self._iou_process.wait(), timeout=100) But it's broken before Python 3.4: http://bugs.python.org/issue23140 :param process: An asyncio subprocess :param timeout: Timeout in seconds """ if sys.version_info >= (3, 5): try: yield from asyncio.wait_for(process.wait(), timeout=timeout) except ProcessLookupError: return else: while timeout > 0: if process.returncode is not None: return yield from asyncio.sleep(0.1) timeout -= 0.1 raise asyncio.TimeoutError()
python
def wait_for_process_termination(process, timeout=10): if sys.version_info >= (3, 5): try: yield from asyncio.wait_for(process.wait(), timeout=timeout) except ProcessLookupError: return else: while timeout > 0: if process.returncode is not None: return yield from asyncio.sleep(0.1) timeout -= 0.1 raise asyncio.TimeoutError()
[ "def", "wait_for_process_termination", "(", "process", ",", "timeout", "=", "10", ")", ":", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "5", ")", ":", "try", ":", "yield", "from", "asyncio", ".", "wait_for", "(", "process", ".", "wait", "(",...
Wait for a process terminate, and raise asyncio.TimeoutError in case of timeout. In theory this can be implemented by just: yield from asyncio.wait_for(self._iou_process.wait(), timeout=100) But it's broken before Python 3.4: http://bugs.python.org/issue23140 :param process: An asyncio subprocess :param timeout: Timeout in seconds
[ "Wait", "for", "a", "process", "terminate", "and", "raise", "asyncio", ".", "TimeoutError", "in", "case", "of", "timeout", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/__init__.py#L69-L95
240,399
GNS3/gns3-server
gns3server/utils/asyncio/__init__.py
locked_coroutine
def locked_coroutine(f): """ Method decorator that replace asyncio.coroutine that warranty that this specific method of this class instance will not we executed twice at the same time """ @asyncio.coroutine def new_function(*args, **kwargs): # In the instance of the class we will store # a lock has an attribute. lock_var_name = "__" + f.__name__ + "_lock" if not hasattr(args[0], lock_var_name): setattr(args[0], lock_var_name, asyncio.Lock()) with (yield from getattr(args[0], lock_var_name)): return (yield from f(*args, **kwargs)) return new_function
python
def locked_coroutine(f): @asyncio.coroutine def new_function(*args, **kwargs): # In the instance of the class we will store # a lock has an attribute. lock_var_name = "__" + f.__name__ + "_lock" if not hasattr(args[0], lock_var_name): setattr(args[0], lock_var_name, asyncio.Lock()) with (yield from getattr(args[0], lock_var_name)): return (yield from f(*args, **kwargs)) return new_function
[ "def", "locked_coroutine", "(", "f", ")", ":", "@", "asyncio", ".", "coroutine", "def", "new_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# In the instance of the class we will store", "# a lock has an attribute.", "lock_var_name", "=", "\"__\"",...
Method decorator that replace asyncio.coroutine that warranty that this specific method of this class instance will not we executed twice at the same time
[ "Method", "decorator", "that", "replace", "asyncio", ".", "coroutine", "that", "warranty", "that", "this", "specific", "method", "of", "this", "class", "instance", "will", "not", "we", "executed", "twice", "at", "the", "same", "time" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/__init__.py#L142-L160