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,500
GNS3/gns3-server
gns3server/compute/dynamips/nodes/atm_switch.py
ATMSwitch.remove_nio
def remove_nio(self, port_number): """ Removes the specified NIO as member of this ATM switch. :param port_number: allocated 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(): if len(source) == 3 and len(destination) == 3: # remove the virtual channels mapped with this port/nio source_port, source_vpi, source_vci = source destination_port, destination_vpi, destination_vci = destination if port_number == source_port: log.info('ATM switch "{name}" [{id}]: unmapping VCC between port {source_port} VPI {source_vpi} VCI {source_vci} and port {destination_port} VPI {destination_vpi} VCI {destination_vci}'.format(name=self._name, id=self._id, source_port=source_port, source_vpi=source_vpi, source_vci=source_vci, destination_port=destination_port, destination_vpi=destination_vpi, destination_vci=destination_vci)) yield from self.unmap_pvc(source_port, source_vpi, source_vci, destination_port, destination_vpi, destination_vci) yield from self.unmap_pvc(destination_port, destination_vpi, destination_vci, source_port, source_vpi, source_vci) else: # remove the virtual paths mapped with this port/nio source_port, source_vpi = source destination_port, destination_vpi = destination if port_number == source_port: log.info('ATM switch "{name}" [{id}]: unmapping VPC between port {source_port} VPI {source_vpi} and port {destination_port} VPI {destination_vpi}'.format(name=self._name, id=self._id, source_port=source_port, source_vpi=source_vpi, destination_port=destination_port, destination_vpi=destination_vpi)) yield from self.unmap_vp(source_port, source_vpi, destination_port, destination_vpi) yield from self.unmap_vp(destination_port, destination_vpi, source_port, source_vpi) nio = self._nios[port_number] if isinstance(nio, NIOUDP): self.manager.port_manager.release_udp_port(nio.lport, self._project) log.info('ATM 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(): if len(source) == 3 and len(destination) == 3: # remove the virtual channels mapped with this port/nio source_port, source_vpi, source_vci = source destination_port, destination_vpi, destination_vci = destination if port_number == source_port: log.info('ATM switch "{name}" [{id}]: unmapping VCC between port {source_port} VPI {source_vpi} VCI {source_vci} and port {destination_port} VPI {destination_vpi} VCI {destination_vci}'.format(name=self._name, id=self._id, source_port=source_port, source_vpi=source_vpi, source_vci=source_vci, destination_port=destination_port, destination_vpi=destination_vpi, destination_vci=destination_vci)) yield from self.unmap_pvc(source_port, source_vpi, source_vci, destination_port, destination_vpi, destination_vci) yield from self.unmap_pvc(destination_port, destination_vpi, destination_vci, source_port, source_vpi, source_vci) else: # remove the virtual paths mapped with this port/nio source_port, source_vpi = source destination_port, destination_vpi = destination if port_number == source_port: log.info('ATM switch "{name}" [{id}]: unmapping VPC between port {source_port} VPI {source_vpi} and port {destination_port} VPI {destination_vpi}'.format(name=self._name, id=self._id, source_port=source_port, source_vpi=source_vpi, destination_port=destination_port, destination_vpi=destination_vpi)) yield from self.unmap_vp(source_port, source_vpi, destination_port, destination_vpi) yield from self.unmap_vp(destination_port, destination_vpi, source_port, source_vpi) nio = self._nios[port_number] if isinstance(nio, NIOUDP): self.manager.port_manager.release_udp_port(nio.lport, self._project) log.info('ATM 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 ATM switch. :param port_number: allocated port number
[ "Removes", "the", "specified", "NIO", "as", "member", "of", "this", "ATM", "switch", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/atm_switch.py#L180-L230
240,501
GNS3/gns3-server
gns3server/compute/dynamips/nodes/atm_switch.py
ATMSwitch.map_vp
def map_vp(self, port1, vpi1, port2, vpi2): """ Creates a new Virtual Path connection. :param port1: input port :param vpi1: input vpi :param port2: output port :param vpi2: output vpi """ if port1 not in self._nios: return if port2 not in self._nios: return nio1 = self._nios[port1] nio2 = self._nios[port2] yield from self._hypervisor.send('atmsw create_vpc "{name}" {input_nio} {input_vpi} {output_nio} {output_vpi}'.format(name=self._name, input_nio=nio1, input_vpi=vpi1, output_nio=nio2, output_vpi=vpi2)) log.info('ATM switch "{name}" [{id}]: VPC from port {port1} VPI {vpi1} to port {port2} VPI {vpi2} created'.format(name=self._name, id=self._id, port1=port1, vpi1=vpi1, port2=port2, vpi2=vpi2)) self._active_mappings[(port1, vpi1)] = (port2, vpi2)
python
def map_vp(self, port1, vpi1, port2, vpi2): if port1 not in self._nios: return if port2 not in self._nios: return nio1 = self._nios[port1] nio2 = self._nios[port2] yield from self._hypervisor.send('atmsw create_vpc "{name}" {input_nio} {input_vpi} {output_nio} {output_vpi}'.format(name=self._name, input_nio=nio1, input_vpi=vpi1, output_nio=nio2, output_vpi=vpi2)) log.info('ATM switch "{name}" [{id}]: VPC from port {port1} VPI {vpi1} to port {port2} VPI {vpi2} created'.format(name=self._name, id=self._id, port1=port1, vpi1=vpi1, port2=port2, vpi2=vpi2)) self._active_mappings[(port1, vpi1)] = (port2, vpi2)
[ "def", "map_vp", "(", "self", ",", "port1", ",", "vpi1", ",", "port2", ",", "vpi2", ")", ":", "if", "port1", "not", "in", "self", ".", "_nios", ":", "return", "if", "port2", "not", "in", "self", ".", "_nios", ":", "return", "nio1", "=", "self", "...
Creates a new Virtual Path connection. :param port1: input port :param vpi1: input vpi :param port2: output port :param vpi2: output vpi
[ "Creates", "a", "new", "Virtual", "Path", "connection", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/atm_switch.py#L279-L311
240,502
GNS3/gns3-server
gns3server/web/response.py
Response.file
def file(self, path, status=200, set_content_length=True): """ Return a file as a response """ ct, encoding = mimetypes.guess_type(path) if not ct: ct = 'application/octet-stream' if encoding: self.headers[aiohttp.hdrs.CONTENT_ENCODING] = encoding self.content_type = ct if set_content_length: st = os.stat(path) self.last_modified = st.st_mtime self.headers[aiohttp.hdrs.CONTENT_LENGTH] = str(st.st_size) else: self.enable_chunked_encoding() self.set_status(status) try: with open(path, 'rb') as fobj: yield from self.prepare(self._request) while True: data = fobj.read(4096) if not data: break yield from self.write(data) yield from self.drain() except FileNotFoundError: raise aiohttp.web.HTTPNotFound() except PermissionError: raise aiohttp.web.HTTPForbidden()
python
def file(self, path, status=200, set_content_length=True): ct, encoding = mimetypes.guess_type(path) if not ct: ct = 'application/octet-stream' if encoding: self.headers[aiohttp.hdrs.CONTENT_ENCODING] = encoding self.content_type = ct if set_content_length: st = os.stat(path) self.last_modified = st.st_mtime self.headers[aiohttp.hdrs.CONTENT_LENGTH] = str(st.st_size) else: self.enable_chunked_encoding() self.set_status(status) try: with open(path, 'rb') as fobj: yield from self.prepare(self._request) while True: data = fobj.read(4096) if not data: break yield from self.write(data) yield from self.drain() except FileNotFoundError: raise aiohttp.web.HTTPNotFound() except PermissionError: raise aiohttp.web.HTTPForbidden()
[ "def", "file", "(", "self", ",", "path", ",", "status", "=", "200", ",", "set_content_length", "=", "True", ")", ":", "ct", ",", "encoding", "=", "mimetypes", ".", "guess_type", "(", "path", ")", "if", "not", "ct", ":", "ct", "=", "'application/octet-s...
Return a file as a response
[ "Return", "a", "file", "as", "a", "response" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/web/response.py#L116-L150
240,503
GNS3/gns3-server
gns3server/controller/snapshot.py
Snapshot.restore
def restore(self): """ Restore the snapshot """ yield from self._project.delete_on_computes() # We don't send close notif to clients because the close / open dance is purely internal yield from self._project.close(ignore_notification=True) self._project.controller.notification.emit("snapshot.restored", self.__json__()) try: if os.path.exists(os.path.join(self._project.path, "project-files")): shutil.rmtree(os.path.join(self._project.path, "project-files")) with open(self._path, "rb") as f: project = yield from import_project(self._project.controller, self._project.id, f, location=self._project.path) except (OSError, PermissionError) as e: raise aiohttp.web.HTTPConflict(text=str(e)) yield from project.open() return project
python
def restore(self): yield from self._project.delete_on_computes() # We don't send close notif to clients because the close / open dance is purely internal yield from self._project.close(ignore_notification=True) self._project.controller.notification.emit("snapshot.restored", self.__json__()) try: if os.path.exists(os.path.join(self._project.path, "project-files")): shutil.rmtree(os.path.join(self._project.path, "project-files")) with open(self._path, "rb") as f: project = yield from import_project(self._project.controller, self._project.id, f, location=self._project.path) except (OSError, PermissionError) as e: raise aiohttp.web.HTTPConflict(text=str(e)) yield from project.open() return project
[ "def", "restore", "(", "self", ")", ":", "yield", "from", "self", ".", "_project", ".", "delete_on_computes", "(", ")", "# We don't send close notif to clients because the close / open dance is purely internal", "yield", "from", "self", ".", "_project", ".", "close", "(...
Restore the snapshot
[ "Restore", "the", "snapshot" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/snapshot.py#L75-L92
240,504
GNS3/gns3-server
gns3server/utils/get_resource.py
get_resource
def get_resource(resource_name): """ Return a resource in current directory or in frozen package """ resource_path = None if hasattr(sys, "frozen"): resource_path = os.path.normpath(os.path.join(os.path.dirname(sys.executable), resource_name)) elif not hasattr(sys, "frozen") and pkg_resources.resource_exists("gns3server", resource_name): resource_path = pkg_resources.resource_filename("gns3server", resource_name) resource_path = os.path.normpath(resource_path) return resource_path
python
def get_resource(resource_name): resource_path = None if hasattr(sys, "frozen"): resource_path = os.path.normpath(os.path.join(os.path.dirname(sys.executable), resource_name)) elif not hasattr(sys, "frozen") and pkg_resources.resource_exists("gns3server", resource_name): resource_path = pkg_resources.resource_filename("gns3server", resource_name) resource_path = os.path.normpath(resource_path) return resource_path
[ "def", "get_resource", "(", "resource_name", ")", ":", "resource_path", "=", "None", "if", "hasattr", "(", "sys", ",", "\"frozen\"", ")", ":", "resource_path", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "os", "."...
Return a resource in current directory or in frozen package
[ "Return", "a", "resource", "in", "current", "directory", "or", "in", "frozen", "package" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/get_resource.py#L46-L57
240,505
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM._nvram_changed
def _nvram_changed(self, path): """ Called when the NVRAM file has changed """ log.debug("NVRAM changed: {}".format(path)) self.save_configs() self.updated()
python
def _nvram_changed(self, path): log.debug("NVRAM changed: {}".format(path)) self.save_configs() self.updated()
[ "def", "_nvram_changed", "(", "self", ",", "path", ")", ":", "log", ".", "debug", "(", "\"NVRAM changed: {}\"", ".", "format", "(", "path", ")", ")", "self", ".", "save_configs", "(", ")", "self", ".", "updated", "(", ")" ]
Called when the NVRAM file has changed
[ "Called", "when", "the", "NVRAM", "file", "has", "changed" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L95-L101
240,506
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.close
def close(self): """ Closes this IOU VM. """ if not (yield from super().close()): return False adapters = self._ethernet_adapters + self._serial_adapters for adapter in adapters: if adapter is not None: for nio in adapter.ports.values(): if nio and isinstance(nio, NIOUDP): self.manager.port_manager.release_udp_port(nio.lport, self._project) yield from self.stop()
python
def close(self): if not (yield from super().close()): return False adapters = self._ethernet_adapters + self._serial_adapters for adapter in adapters: if adapter is not None: for nio in adapter.ports.values(): if nio and isinstance(nio, NIOUDP): self.manager.port_manager.release_udp_port(nio.lport, self._project) yield from self.stop()
[ "def", "close", "(", "self", ")", ":", "if", "not", "(", "yield", "from", "super", "(", ")", ".", "close", "(", ")", ")", ":", "return", "False", "adapters", "=", "self", ".", "_ethernet_adapters", "+", "self", ".", "_serial_adapters", "for", "adapter"...
Closes this IOU VM.
[ "Closes", "this", "IOU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L104-L119
240,507
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.path
def path(self, path): """ Path of the IOU executable. :param path: path to the IOU image executable """ self._path = self.manager.get_abs_image_path(path) log.info('IOU "{name}" [{id}]: IOU image updated to "{path}"'.format(name=self._name, id=self._id, path=self._path))
python
def path(self, path): self._path = self.manager.get_abs_image_path(path) log.info('IOU "{name}" [{id}]: IOU image updated to "{path}"'.format(name=self._name, id=self._id, path=self._path))
[ "def", "path", "(", "self", ",", "path", ")", ":", "self", ".", "_path", "=", "self", ".", "manager", ".", "get_abs_image_path", "(", "path", ")", "log", ".", "info", "(", "'IOU \"{name}\" [{id}]: IOU image updated to \"{path}\"'", ".", "format", "(", "name", ...
Path of the IOU executable. :param path: path to the IOU image executable
[ "Path", "of", "the", "IOU", "executable", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L132-L140
240,508
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.use_default_iou_values
def use_default_iou_values(self, state): """ Sets if this device uses the default IOU image values. :param state: boolean """ self._use_default_iou_values = state if state: log.info('IOU "{name}" [{id}]: uses the default IOU image values'.format(name=self._name, id=self._id)) else: log.info('IOU "{name}" [{id}]: does not use the default IOU image values'.format(name=self._name, id=self._id))
python
def use_default_iou_values(self, state): self._use_default_iou_values = state if state: log.info('IOU "{name}" [{id}]: uses the default IOU image values'.format(name=self._name, id=self._id)) else: log.info('IOU "{name}" [{id}]: does not use the default IOU image values'.format(name=self._name, id=self._id))
[ "def", "use_default_iou_values", "(", "self", ",", "state", ")", ":", "self", ".", "_use_default_iou_values", "=", "state", "if", "state", ":", "log", ".", "info", "(", "'IOU \"{name}\" [{id}]: uses the default IOU image values'", ".", "format", "(", "name", "=", ...
Sets if this device uses the default IOU image values. :param state: boolean
[ "Sets", "if", "this", "device", "uses", "the", "default", "IOU", "image", "values", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L153-L164
240,509
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.update_default_iou_values
def update_default_iou_values(self): """ Finds the default RAM and NVRAM values for the IOU image. """ try: output = yield from gns3server.utils.asyncio.subprocess_check_output(self._path, "-h", cwd=self.working_dir, stderr=True) match = re.search("-n <n>\s+Size of nvram in Kb \(default ([0-9]+)KB\)", output) if match: self.nvram = int(match.group(1)) match = re.search("-m <n>\s+Megabytes of router memory \(default ([0-9]+)MB\)", output) if match: self.ram = int(match.group(1)) except (ValueError, OSError, subprocess.SubprocessError) as e: log.warning("could not find default RAM and NVRAM values for {}: {}".format(os.path.basename(self._path), e))
python
def update_default_iou_values(self): try: output = yield from gns3server.utils.asyncio.subprocess_check_output(self._path, "-h", cwd=self.working_dir, stderr=True) match = re.search("-n <n>\s+Size of nvram in Kb \(default ([0-9]+)KB\)", output) if match: self.nvram = int(match.group(1)) match = re.search("-m <n>\s+Megabytes of router memory \(default ([0-9]+)MB\)", output) if match: self.ram = int(match.group(1)) except (ValueError, OSError, subprocess.SubprocessError) as e: log.warning("could not find default RAM and NVRAM values for {}: {}".format(os.path.basename(self._path), e))
[ "def", "update_default_iou_values", "(", "self", ")", ":", "try", ":", "output", "=", "yield", "from", "gns3server", ".", "utils", ".", "asyncio", ".", "subprocess_check_output", "(", "self", ".", "_path", ",", "\"-h\"", ",", "cwd", "=", "self", ".", "work...
Finds the default RAM and NVRAM values for the IOU image.
[ "Finds", "the", "default", "RAM", "and", "NVRAM", "values", "for", "the", "IOU", "image", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L167-L181
240,510
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM._check_requirements
def _check_requirements(self): """ Checks the IOU image. """ if not self._path: raise IOUError("IOU image is not configured") if not os.path.isfile(self._path) or not os.path.exists(self._path): if os.path.islink(self._path): raise IOUError("IOU image '{}' linked to '{}' is not accessible".format(self._path, os.path.realpath(self._path))) else: raise IOUError("IOU image '{}' is not accessible".format(self._path)) try: with open(self._path, "rb") as f: # read the first 7 bytes of the file. elf_header_start = f.read(7) except OSError as e: raise IOUError("Cannot read ELF header for IOU image '{}': {}".format(self._path, e)) # IOU images must start with the ELF magic number, be 32-bit or 64-bit, little endian # and have an ELF version of 1 normal IOS image are big endian! if elf_header_start != b'\x7fELF\x01\x01\x01' and elf_header_start != b'\x7fELF\x02\x01\x01': raise IOUError("'{}' is not a valid IOU image".format(self._path)) if not os.access(self._path, os.X_OK): raise IOUError("IOU image '{}' is not executable".format(self._path))
python
def _check_requirements(self): if not self._path: raise IOUError("IOU image is not configured") if not os.path.isfile(self._path) or not os.path.exists(self._path): if os.path.islink(self._path): raise IOUError("IOU image '{}' linked to '{}' is not accessible".format(self._path, os.path.realpath(self._path))) else: raise IOUError("IOU image '{}' is not accessible".format(self._path)) try: with open(self._path, "rb") as f: # read the first 7 bytes of the file. elf_header_start = f.read(7) except OSError as e: raise IOUError("Cannot read ELF header for IOU image '{}': {}".format(self._path, e)) # IOU images must start with the ELF magic number, be 32-bit or 64-bit, little endian # and have an ELF version of 1 normal IOS image are big endian! if elf_header_start != b'\x7fELF\x01\x01\x01' and elf_header_start != b'\x7fELF\x02\x01\x01': raise IOUError("'{}' is not a valid IOU image".format(self._path)) if not os.access(self._path, os.X_OK): raise IOUError("IOU image '{}' is not executable".format(self._path))
[ "def", "_check_requirements", "(", "self", ")", ":", "if", "not", "self", ".", "_path", ":", "raise", "IOUError", "(", "\"IOU image is not configured\"", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "self", ".", "_path", ")", "or", "not", "os...
Checks the IOU image.
[ "Checks", "the", "IOU", "image", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L188-L214
240,511
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.iourc_path
def iourc_path(self): """ Returns the IOURC file path. :returns: path to IOURC """ iourc_path = self._config().get("iourc_path") if not iourc_path: # look for the iourc file in the temporary dir. path = os.path.join(self.temporary_directory, "iourc") if os.path.exists(path): return path # look for the iourc file in the user home dir. path = os.path.join(os.path.expanduser("~/"), ".iourc") if os.path.exists(path): return path # look for the iourc file in the current working dir. path = os.path.join(self.working_dir, "iourc") if os.path.exists(path): return path return iourc_path
python
def iourc_path(self): iourc_path = self._config().get("iourc_path") if not iourc_path: # look for the iourc file in the temporary dir. path = os.path.join(self.temporary_directory, "iourc") if os.path.exists(path): return path # look for the iourc file in the user home dir. path = os.path.join(os.path.expanduser("~/"), ".iourc") if os.path.exists(path): return path # look for the iourc file in the current working dir. path = os.path.join(self.working_dir, "iourc") if os.path.exists(path): return path return iourc_path
[ "def", "iourc_path", "(", "self", ")", ":", "iourc_path", "=", "self", ".", "_config", "(", ")", ".", "get", "(", "\"iourc_path\"", ")", "if", "not", "iourc_path", ":", "# look for the iourc file in the temporary dir.", "path", "=", "os", ".", "path", ".", ...
Returns the IOURC file path. :returns: path to IOURC
[ "Returns", "the", "IOURC", "file", "path", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L241-L262
240,512
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.name
def name(self, new_name): """ Sets the name of this IOU VM. :param new_name: name """ if self.startup_config_file: content = self.startup_config_content content = re.sub(r"^hostname .+$", "hostname " + new_name, content, flags=re.MULTILINE) self.startup_config_content = content super(IOUVM, IOUVM).name.__set__(self, new_name)
python
def name(self, new_name): if self.startup_config_file: content = self.startup_config_content content = re.sub(r"^hostname .+$", "hostname " + new_name, content, flags=re.MULTILINE) self.startup_config_content = content super(IOUVM, IOUVM).name.__set__(self, new_name)
[ "def", "name", "(", "self", ",", "new_name", ")", ":", "if", "self", ".", "startup_config_file", ":", "content", "=", "self", ".", "startup_config_content", "content", "=", "re", ".", "sub", "(", "r\"^hostname .+$\"", ",", "\"hostname \"", "+", "new_name", "...
Sets the name of this IOU VM. :param new_name: name
[ "Sets", "the", "name", "of", "this", "IOU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L320-L332
240,513
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM._library_check
def _library_check(self): """ Checks for missing shared library dependencies in the IOU image. """ try: output = yield from gns3server.utils.asyncio.subprocess_check_output("ldd", self._path) except (FileNotFoundError, subprocess.SubprocessError) as e: log.warn("Could not determine the shared library dependencies for {}: {}".format(self._path, e)) return p = re.compile("([\.\w]+)\s=>\s+not found") missing_libs = p.findall(output) if missing_libs: raise IOUError("The following shared library dependencies cannot be found for IOU image {}: {}".format(self._path, ", ".join(missing_libs)))
python
def _library_check(self): try: output = yield from gns3server.utils.asyncio.subprocess_check_output("ldd", self._path) except (FileNotFoundError, subprocess.SubprocessError) as e: log.warn("Could not determine the shared library dependencies for {}: {}".format(self._path, e)) return p = re.compile("([\.\w]+)\s=>\s+not found") missing_libs = p.findall(output) if missing_libs: raise IOUError("The following shared library dependencies cannot be found for IOU image {}: {}".format(self._path, ", ".join(missing_libs)))
[ "def", "_library_check", "(", "self", ")", ":", "try", ":", "output", "=", "yield", "from", "gns3server", ".", "utils", ".", "asyncio", ".", "subprocess_check_output", "(", "\"ldd\"", ",", "self", ".", "_path", ")", "except", "(", "FileNotFoundError", ",", ...
Checks for missing shared library dependencies in the IOU image.
[ "Checks", "for", "missing", "shared", "library", "dependencies", "in", "the", "IOU", "image", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L364-L379
240,514
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM._nvram_file
def _nvram_file(self): """ Path to the nvram file """ return os.path.join(self.working_dir, "nvram_{:05d}".format(self.application_id))
python
def _nvram_file(self): return os.path.join(self.working_dir, "nvram_{:05d}".format(self.application_id))
[ "def", "_nvram_file", "(", "self", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "working_dir", ",", "\"nvram_{:05d}\"", ".", "format", "(", "self", ".", "application_id", ")", ")" ]
Path to the nvram file
[ "Path", "to", "the", "nvram", "file" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L441-L445
240,515
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM._push_configs_to_nvram
def _push_configs_to_nvram(self): """ Push the startup-config and private-config content to the NVRAM. """ startup_config_content = self.startup_config_content if startup_config_content: nvram_file = self._nvram_file() try: if not os.path.exists(nvram_file): open(nvram_file, "a").close() nvram_content = None else: with open(nvram_file, "rb") as file: nvram_content = file.read() except OSError as e: raise IOUError("Cannot read nvram file {}: {}".format(nvram_file, e)) startup_config_content = startup_config_content.encode("utf-8") private_config_content = self.private_config_content if private_config_content is not None: private_config_content = private_config_content.encode("utf-8") try: nvram_content = nvram_import(nvram_content, startup_config_content, private_config_content, self.nvram) except ValueError as e: raise IOUError("Cannot push configs to nvram {}: {}".format(nvram_file, e)) try: with open(nvram_file, "wb") as file: file.write(nvram_content) except OSError as e: raise IOUError("Cannot write nvram file {}: {}".format(nvram_file, e))
python
def _push_configs_to_nvram(self): startup_config_content = self.startup_config_content if startup_config_content: nvram_file = self._nvram_file() try: if not os.path.exists(nvram_file): open(nvram_file, "a").close() nvram_content = None else: with open(nvram_file, "rb") as file: nvram_content = file.read() except OSError as e: raise IOUError("Cannot read nvram file {}: {}".format(nvram_file, e)) startup_config_content = startup_config_content.encode("utf-8") private_config_content = self.private_config_content if private_config_content is not None: private_config_content = private_config_content.encode("utf-8") try: nvram_content = nvram_import(nvram_content, startup_config_content, private_config_content, self.nvram) except ValueError as e: raise IOUError("Cannot push configs to nvram {}: {}".format(nvram_file, e)) try: with open(nvram_file, "wb") as file: file.write(nvram_content) except OSError as e: raise IOUError("Cannot write nvram file {}: {}".format(nvram_file, e))
[ "def", "_push_configs_to_nvram", "(", "self", ")", ":", "startup_config_content", "=", "self", ".", "startup_config_content", "if", "startup_config_content", ":", "nvram_file", "=", "self", ".", "_nvram_file", "(", ")", "try", ":", "if", "not", "os", ".", "path"...
Push the startup-config and private-config content to the NVRAM.
[ "Push", "the", "startup", "-", "config", "and", "private", "-", "config", "content", "to", "the", "NVRAM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L447-L477
240,516
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.start
def start(self): """ Starts the IOU process. """ self._check_requirements() if not self.is_running(): yield from self._library_check() try: self._rename_nvram_file() except OSError as e: raise IOUError("Could not rename nvram files: {}".format(e)) iourc_path = self.iourc_path if not iourc_path: raise IOUError("Could not find an iourc file (IOU license)") if not os.path.isfile(iourc_path): raise IOUError("The iourc path '{}' is not a regular file".format(iourc_path)) yield from self._check_iou_licence() yield from self._start_ubridge() self._create_netmap_config() if self.use_default_iou_values: # make sure we have the default nvram amount to correctly push the configs yield from self.update_default_iou_values() self._push_configs_to_nvram() # check if there is enough RAM to run self.check_available_ram(self.ram) self._nvram_watcher = FileWatcher(self._nvram_file(), self._nvram_changed, delay=2) # created a environment variable pointing to the iourc file. env = os.environ.copy() if "IOURC" not in os.environ: env["IOURC"] = iourc_path command = yield from self._build_command() try: log.info("Starting IOU: {}".format(command)) self.command_line = ' '.join(command) self._iou_process = yield from asyncio.create_subprocess_exec( *command, stdout=asyncio.subprocess.PIPE, stdin=asyncio.subprocess.PIPE, stderr=subprocess.STDOUT, cwd=self.working_dir, env=env) log.info("IOU instance {} started PID={}".format(self._id, self._iou_process.pid)) self._started = True self.status = "started" callback = functools.partial(self._termination_callback, "IOU") gns3server.utils.asyncio.monitor_process(self._iou_process, callback) except FileNotFoundError as e: raise IOUError("Could not start IOU: {}: 32-bit binary support is probably not installed".format(e)) except (OSError, subprocess.SubprocessError) as e: iou_stdout = self.read_iou_stdout() log.error("Could not start IOU {}: {}\n{}".format(self._path, e, iou_stdout)) raise IOUError("Could not start IOU {}: {}\n{}".format(self._path, e, iou_stdout)) server = AsyncioTelnetServer(reader=self._iou_process.stdout, writer=self._iou_process.stdin, binary=True, echo=True) self._telnet_server = yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console) # configure networking support yield from self._networking()
python
def start(self): self._check_requirements() if not self.is_running(): yield from self._library_check() try: self._rename_nvram_file() except OSError as e: raise IOUError("Could not rename nvram files: {}".format(e)) iourc_path = self.iourc_path if not iourc_path: raise IOUError("Could not find an iourc file (IOU license)") if not os.path.isfile(iourc_path): raise IOUError("The iourc path '{}' is not a regular file".format(iourc_path)) yield from self._check_iou_licence() yield from self._start_ubridge() self._create_netmap_config() if self.use_default_iou_values: # make sure we have the default nvram amount to correctly push the configs yield from self.update_default_iou_values() self._push_configs_to_nvram() # check if there is enough RAM to run self.check_available_ram(self.ram) self._nvram_watcher = FileWatcher(self._nvram_file(), self._nvram_changed, delay=2) # created a environment variable pointing to the iourc file. env = os.environ.copy() if "IOURC" not in os.environ: env["IOURC"] = iourc_path command = yield from self._build_command() try: log.info("Starting IOU: {}".format(command)) self.command_line = ' '.join(command) self._iou_process = yield from asyncio.create_subprocess_exec( *command, stdout=asyncio.subprocess.PIPE, stdin=asyncio.subprocess.PIPE, stderr=subprocess.STDOUT, cwd=self.working_dir, env=env) log.info("IOU instance {} started PID={}".format(self._id, self._iou_process.pid)) self._started = True self.status = "started" callback = functools.partial(self._termination_callback, "IOU") gns3server.utils.asyncio.monitor_process(self._iou_process, callback) except FileNotFoundError as e: raise IOUError("Could not start IOU: {}: 32-bit binary support is probably not installed".format(e)) except (OSError, subprocess.SubprocessError) as e: iou_stdout = self.read_iou_stdout() log.error("Could not start IOU {}: {}\n{}".format(self._path, e, iou_stdout)) raise IOUError("Could not start IOU {}: {}\n{}".format(self._path, e, iou_stdout)) server = AsyncioTelnetServer(reader=self._iou_process.stdout, writer=self._iou_process.stdin, binary=True, echo=True) self._telnet_server = yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console) # configure networking support yield from self._networking()
[ "def", "start", "(", "self", ")", ":", "self", ".", "_check_requirements", "(", ")", "if", "not", "self", ".", "is_running", "(", ")", ":", "yield", "from", "self", ".", "_library_check", "(", ")", "try", ":", "self", ".", "_rename_nvram_file", "(", ")...
Starts the IOU process.
[ "Starts", "the", "IOU", "process", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L480-L547
240,517
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM._networking
def _networking(self): """ Configures the IOL bridge in uBridge. """ bridge_name = "IOL-BRIDGE-{}".format(self.application_id + 512) try: # delete any previous bridge if it exists yield from self._ubridge_send("iol_bridge delete {name}".format(name=bridge_name)) except UbridgeError: pass yield from self._ubridge_send("iol_bridge create {name} {bridge_id}".format(name=bridge_name, bridge_id=self.application_id + 512)) bay_id = 0 for adapter in self._adapters: unit_id = 0 for unit in adapter.ports.keys(): nio = adapter.get_nio(unit) if nio and isinstance(nio, NIOUDP): yield from self._ubridge_send("iol_bridge add_nio_udp {name} {iol_id} {bay} {unit} {lport} {rhost} {rport}".format(name=bridge_name, iol_id=self.application_id, bay=bay_id, unit=unit_id, lport=nio.lport, rhost=nio.rhost, rport=nio.rport)) if nio.capturing: yield from self._ubridge_send('iol_bridge start_capture {name} "{output_file}" {data_link_type}'.format(name=bridge_name, output_file=nio.pcap_output_file, data_link_type=re.sub("^DLT_", "", nio.pcap_data_link_type))) yield from self._ubridge_apply_filters(bay_id, unit_id, nio.filters) unit_id += 1 bay_id += 1 yield from self._ubridge_send("iol_bridge start {name}".format(name=bridge_name))
python
def _networking(self): bridge_name = "IOL-BRIDGE-{}".format(self.application_id + 512) try: # delete any previous bridge if it exists yield from self._ubridge_send("iol_bridge delete {name}".format(name=bridge_name)) except UbridgeError: pass yield from self._ubridge_send("iol_bridge create {name} {bridge_id}".format(name=bridge_name, bridge_id=self.application_id + 512)) bay_id = 0 for adapter in self._adapters: unit_id = 0 for unit in adapter.ports.keys(): nio = adapter.get_nio(unit) if nio and isinstance(nio, NIOUDP): yield from self._ubridge_send("iol_bridge add_nio_udp {name} {iol_id} {bay} {unit} {lport} {rhost} {rport}".format(name=bridge_name, iol_id=self.application_id, bay=bay_id, unit=unit_id, lport=nio.lport, rhost=nio.rhost, rport=nio.rport)) if nio.capturing: yield from self._ubridge_send('iol_bridge start_capture {name} "{output_file}" {data_link_type}'.format(name=bridge_name, output_file=nio.pcap_output_file, data_link_type=re.sub("^DLT_", "", nio.pcap_data_link_type))) yield from self._ubridge_apply_filters(bay_id, unit_id, nio.filters) unit_id += 1 bay_id += 1 yield from self._ubridge_send("iol_bridge start {name}".format(name=bridge_name))
[ "def", "_networking", "(", "self", ")", ":", "bridge_name", "=", "\"IOL-BRIDGE-{}\"", ".", "format", "(", "self", ".", "application_id", "+", "512", ")", "try", ":", "# delete any previous bridge if it exists", "yield", "from", "self", ".", "_ubridge_send", "(", ...
Configures the IOL bridge in uBridge.
[ "Configures", "the", "IOL", "bridge", "in", "uBridge", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L550-L585
240,518
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM._rename_nvram_file
def _rename_nvram_file(self): """ Before starting the VM, rename the nvram and vlan.dat files with the correct IOU application identifier. """ destination = self._nvram_file() for file_path in glob.glob(os.path.join(glob.escape(self.working_dir), "nvram_*")): shutil.move(file_path, destination) destination = os.path.join(self.working_dir, "vlan.dat-{:05d}".format(self.application_id)) for file_path in glob.glob(os.path.join(glob.escape(self.working_dir), "vlan.dat-*")): shutil.move(file_path, destination)
python
def _rename_nvram_file(self): destination = self._nvram_file() for file_path in glob.glob(os.path.join(glob.escape(self.working_dir), "nvram_*")): shutil.move(file_path, destination) destination = os.path.join(self.working_dir, "vlan.dat-{:05d}".format(self.application_id)) for file_path in glob.glob(os.path.join(glob.escape(self.working_dir), "vlan.dat-*")): shutil.move(file_path, destination)
[ "def", "_rename_nvram_file", "(", "self", ")", ":", "destination", "=", "self", ".", "_nvram_file", "(", ")", "for", "file_path", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "glob", ".", "escape", "(", "self", ".", "working_dir...
Before starting the VM, rename the nvram and vlan.dat files with the correct IOU application identifier.
[ "Before", "starting", "the", "VM", "rename", "the", "nvram", "and", "vlan", ".", "dat", "files", "with", "the", "correct", "IOU", "application", "identifier", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L608-L618
240,519
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.stop
def stop(self): """ Stops the IOU process. """ yield from self._stop_ubridge() if self._nvram_watcher: self._nvram_watcher.close() self._nvram_watcher = None if self._telnet_server: self._telnet_server.close() self._telnet_server = None if self.is_running(): self._terminate_process_iou() if self._iou_process.returncode is None: try: yield from gns3server.utils.asyncio.wait_for_process_termination(self._iou_process, timeout=3) except asyncio.TimeoutError: if self._iou_process.returncode is None: log.warning("IOU process {} is still running... killing it".format(self._iou_process.pid)) try: self._iou_process.kill() except ProcessLookupError: pass self._iou_process = None self._started = False self.save_configs()
python
def stop(self): yield from self._stop_ubridge() if self._nvram_watcher: self._nvram_watcher.close() self._nvram_watcher = None if self._telnet_server: self._telnet_server.close() self._telnet_server = None if self.is_running(): self._terminate_process_iou() if self._iou_process.returncode is None: try: yield from gns3server.utils.asyncio.wait_for_process_termination(self._iou_process, timeout=3) except asyncio.TimeoutError: if self._iou_process.returncode is None: log.warning("IOU process {} is still running... killing it".format(self._iou_process.pid)) try: self._iou_process.kill() except ProcessLookupError: pass self._iou_process = None self._started = False self.save_configs()
[ "def", "stop", "(", "self", ")", ":", "yield", "from", "self", ".", "_stop_ubridge", "(", ")", "if", "self", ".", "_nvram_watcher", ":", "self", ".", "_nvram_watcher", ".", "close", "(", ")", "self", ".", "_nvram_watcher", "=", "None", "if", "self", "....
Stops the IOU process.
[ "Stops", "the", "IOU", "process", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L621-L650
240,520
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM._terminate_process_iou
def _terminate_process_iou(self): """ Terminate the IOU process if running """ if self._iou_process: log.info('Stopping IOU process for IOU VM "{}" PID={}'.format(self.name, self._iou_process.pid)) try: self._iou_process.terminate() # Sometime the process can already be dead when we garbage collect except ProcessLookupError: pass self._started = False self.status = "stopped"
python
def _terminate_process_iou(self): if self._iou_process: log.info('Stopping IOU process for IOU VM "{}" PID={}'.format(self.name, self._iou_process.pid)) try: self._iou_process.terminate() # Sometime the process can already be dead when we garbage collect except ProcessLookupError: pass self._started = False self.status = "stopped"
[ "def", "_terminate_process_iou", "(", "self", ")", ":", "if", "self", ".", "_iou_process", ":", "log", ".", "info", "(", "'Stopping IOU process for IOU VM \"{}\" PID={}'", ".", "format", "(", "self", ".", "name", ",", "self", ".", "_iou_process", ".", "pid", "...
Terminate the IOU process if running
[ "Terminate", "the", "IOU", "process", "if", "running" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L652-L665
240,521
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM._create_netmap_config
def _create_netmap_config(self): """ Creates the NETMAP file. """ netmap_path = os.path.join(self.working_dir, "NETMAP") try: with open(netmap_path, "w", encoding="utf-8") as f: for bay in range(0, 16): for unit in range(0, 4): f.write("{ubridge_id}:{bay}/{unit}{iou_id:>5d}:{bay}/{unit}\n".format(ubridge_id=str(self.application_id + 512), bay=bay, unit=unit, iou_id=self.application_id)) log.info("IOU {name} [id={id}]: NETMAP file created".format(name=self._name, id=self._id)) except OSError as e: raise IOUError("Could not create {}: {}".format(netmap_path, e))
python
def _create_netmap_config(self): netmap_path = os.path.join(self.working_dir, "NETMAP") try: with open(netmap_path, "w", encoding="utf-8") as f: for bay in range(0, 16): for unit in range(0, 4): f.write("{ubridge_id}:{bay}/{unit}{iou_id:>5d}:{bay}/{unit}\n".format(ubridge_id=str(self.application_id + 512), bay=bay, unit=unit, iou_id=self.application_id)) log.info("IOU {name} [id={id}]: NETMAP file created".format(name=self._name, id=self._id)) except OSError as e: raise IOUError("Could not create {}: {}".format(netmap_path, e))
[ "def", "_create_netmap_config", "(", "self", ")", ":", "netmap_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "working_dir", ",", "\"NETMAP\"", ")", "try", ":", "with", "open", "(", "netmap_path", ",", "\"w\"", ",", "encoding", "=", "\"utf...
Creates the NETMAP file.
[ "Creates", "the", "NETMAP", "file", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L687-L704
240,522
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.read_iou_stdout
def read_iou_stdout(self): """ Reads the standard output of the IOU process. Only use when the process has been stopped or has crashed. """ output = "" if self._iou_stdout_file: try: with open(self._iou_stdout_file, "rb") as file: output = file.read().decode("utf-8", errors="replace") except OSError as e: log.warn("could not read {}: {}".format(self._iou_stdout_file, e)) return output
python
def read_iou_stdout(self): output = "" if self._iou_stdout_file: try: with open(self._iou_stdout_file, "rb") as file: output = file.read().decode("utf-8", errors="replace") except OSError as e: log.warn("could not read {}: {}".format(self._iou_stdout_file, e)) return output
[ "def", "read_iou_stdout", "(", "self", ")", ":", "output", "=", "\"\"", "if", "self", ".", "_iou_stdout_file", ":", "try", ":", "with", "open", "(", "self", ".", "_iou_stdout_file", ",", "\"rb\"", ")", "as", "file", ":", "output", "=", "file", ".", "re...
Reads the standard output of the IOU process. Only use when the process has been stopped or has crashed.
[ "Reads", "the", "standard", "output", "of", "the", "IOU", "process", ".", "Only", "use", "when", "the", "process", "has", "been", "stopped", "or", "has", "crashed", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L756-L769
240,523
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.ethernet_adapters
def ethernet_adapters(self, ethernet_adapters): """ Sets the number of Ethernet adapters for this IOU VM. :param ethernet_adapters: number of adapters """ self._ethernet_adapters.clear() for _ in range(0, ethernet_adapters): self._ethernet_adapters.append(EthernetAdapter(interfaces=4)) log.info('IOU "{name}" [{id}]: number of Ethernet adapters changed to {adapters}'.format(name=self._name, id=self._id, adapters=len(self._ethernet_adapters))) self._adapters = self._ethernet_adapters + self._serial_adapters
python
def ethernet_adapters(self, ethernet_adapters): self._ethernet_adapters.clear() for _ in range(0, ethernet_adapters): self._ethernet_adapters.append(EthernetAdapter(interfaces=4)) log.info('IOU "{name}" [{id}]: number of Ethernet adapters changed to {adapters}'.format(name=self._name, id=self._id, adapters=len(self._ethernet_adapters))) self._adapters = self._ethernet_adapters + self._serial_adapters
[ "def", "ethernet_adapters", "(", "self", ",", "ethernet_adapters", ")", ":", "self", ".", "_ethernet_adapters", ".", "clear", "(", ")", "for", "_", "in", "range", "(", "0", ",", "ethernet_adapters", ")", ":", "self", ".", "_ethernet_adapters", ".", "append",...
Sets the number of Ethernet adapters for this IOU VM. :param ethernet_adapters: number of adapters
[ "Sets", "the", "number", "of", "Ethernet", "adapters", "for", "this", "IOU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L786-L801
240,524
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.serial_adapters
def serial_adapters(self, serial_adapters): """ Sets the number of Serial adapters for this IOU VM. :param serial_adapters: number of adapters """ self._serial_adapters.clear() for _ in range(0, serial_adapters): self._serial_adapters.append(SerialAdapter(interfaces=4)) log.info('IOU "{name}" [{id}]: number of Serial adapters changed to {adapters}'.format(name=self._name, id=self._id, adapters=len(self._serial_adapters))) self._adapters = self._ethernet_adapters + self._serial_adapters
python
def serial_adapters(self, serial_adapters): self._serial_adapters.clear() for _ in range(0, serial_adapters): self._serial_adapters.append(SerialAdapter(interfaces=4)) log.info('IOU "{name}" [{id}]: number of Serial adapters changed to {adapters}'.format(name=self._name, id=self._id, adapters=len(self._serial_adapters))) self._adapters = self._ethernet_adapters + self._serial_adapters
[ "def", "serial_adapters", "(", "self", ",", "serial_adapters", ")", ":", "self", ".", "_serial_adapters", ".", "clear", "(", ")", "for", "_", "in", "range", "(", "0", ",", "serial_adapters", ")", ":", "self", ".", "_serial_adapters", ".", "append", "(", ...
Sets the number of Serial adapters for this IOU VM. :param serial_adapters: number of adapters
[ "Sets", "the", "number", "of", "Serial", "adapters", "for", "this", "IOU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L814-L829
240,525
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.adapter_add_nio_binding
def adapter_add_nio_binding(self, adapter_number, port_number, nio): """ Adds a adapter NIO binding. :param adapter_number: adapter number :param port_number: port number :param nio: NIO instance to add to the adapter/port """ try: adapter = self._adapters[adapter_number] except IndexError: raise IOUError('Adapter {adapter_number} does not exist for IOU "{name}"'.format(name=self._name, adapter_number=adapter_number)) if not adapter.port_exists(port_number): raise IOUError("Port {port_number} does not exist in adapter {adapter}".format(adapter=adapter, port_number=port_number)) adapter.add_nio(port_number, nio) log.info('IOU "{name}" [{id}]: {nio} added to {adapter_number}/{port_number}'.format(name=self._name, id=self._id, nio=nio, adapter_number=adapter_number, port_number=port_number)) if self.ubridge: bridge_name = "IOL-BRIDGE-{}".format(self.application_id + 512) yield from self._ubridge_send("iol_bridge add_nio_udp {name} {iol_id} {bay} {unit} {lport} {rhost} {rport}".format(name=bridge_name, iol_id=self.application_id, bay=adapter_number, unit=port_number, lport=nio.lport, rhost=nio.rhost, rport=nio.rport)) yield from self._ubridge_apply_filters(adapter_number, port_number, nio.filters)
python
def adapter_add_nio_binding(self, adapter_number, port_number, nio): try: adapter = self._adapters[adapter_number] except IndexError: raise IOUError('Adapter {adapter_number} does not exist for IOU "{name}"'.format(name=self._name, adapter_number=adapter_number)) if not adapter.port_exists(port_number): raise IOUError("Port {port_number} does not exist in adapter {adapter}".format(adapter=adapter, port_number=port_number)) adapter.add_nio(port_number, nio) log.info('IOU "{name}" [{id}]: {nio} added to {adapter_number}/{port_number}'.format(name=self._name, id=self._id, nio=nio, adapter_number=adapter_number, port_number=port_number)) if self.ubridge: bridge_name = "IOL-BRIDGE-{}".format(self.application_id + 512) yield from self._ubridge_send("iol_bridge add_nio_udp {name} {iol_id} {bay} {unit} {lport} {rhost} {rport}".format(name=bridge_name, iol_id=self.application_id, bay=adapter_number, unit=port_number, lport=nio.lport, rhost=nio.rhost, rport=nio.rport)) yield from self._ubridge_apply_filters(adapter_number, port_number, nio.filters)
[ "def", "adapter_add_nio_binding", "(", "self", ",", "adapter_number", ",", "port_number", ",", "nio", ")", ":", "try", ":", "adapter", "=", "self", ".", "_adapters", "[", "adapter_number", "]", "except", "IndexError", ":", "raise", "IOUError", "(", "'Adapter {...
Adds a adapter NIO binding. :param adapter_number: adapter number :param port_number: port number :param nio: NIO instance to add to the adapter/port
[ "Adds", "a", "adapter", "NIO", "binding", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L832-L867
240,526
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM._ubridge_apply_filters
def _ubridge_apply_filters(self, adapter_number, port_number, filters): """ Apply filter like rate limiting :param adapter_number: adapter number :param port_number: port number :param filters: Array of filter dictionnary """ bridge_name = "IOL-BRIDGE-{}".format(self.application_id + 512) location = '{bridge_name} {bay} {unit}'.format( bridge_name=bridge_name, bay=adapter_number, unit=port_number) yield from self._ubridge_send('iol_bridge reset_packet_filters ' + location) for filter in self._build_filter_list(filters): cmd = 'iol_bridge add_packet_filter {} {}'.format( location, filter) yield from self._ubridge_send(cmd)
python
def _ubridge_apply_filters(self, adapter_number, port_number, filters): bridge_name = "IOL-BRIDGE-{}".format(self.application_id + 512) location = '{bridge_name} {bay} {unit}'.format( bridge_name=bridge_name, bay=adapter_number, unit=port_number) yield from self._ubridge_send('iol_bridge reset_packet_filters ' + location) for filter in self._build_filter_list(filters): cmd = 'iol_bridge add_packet_filter {} {}'.format( location, filter) yield from self._ubridge_send(cmd)
[ "def", "_ubridge_apply_filters", "(", "self", ",", "adapter_number", ",", "port_number", ",", "filters", ")", ":", "bridge_name", "=", "\"IOL-BRIDGE-{}\"", ".", "format", "(", "self", ".", "application_id", "+", "512", ")", "location", "=", "'{bridge_name} {bay} {...
Apply filter like rate limiting :param adapter_number: adapter number :param port_number: port number :param filters: Array of filter dictionnary
[ "Apply", "filter", "like", "rate", "limiting" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L883-L901
240,527
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.l1_keepalives
def l1_keepalives(self, state): """ Enables or disables layer 1 keepalive messages. :param state: boolean """ self._l1_keepalives = state if state: log.info('IOU "{name}" [{id}]: has activated layer 1 keepalive messages'.format(name=self._name, id=self._id)) else: log.info('IOU "{name}" [{id}]: has deactivated layer 1 keepalive messages'.format(name=self._name, id=self._id))
python
def l1_keepalives(self, state): self._l1_keepalives = state if state: log.info('IOU "{name}" [{id}]: has activated layer 1 keepalive messages'.format(name=self._name, id=self._id)) else: log.info('IOU "{name}" [{id}]: has deactivated layer 1 keepalive messages'.format(name=self._name, id=self._id))
[ "def", "l1_keepalives", "(", "self", ",", "state", ")", ":", "self", ".", "_l1_keepalives", "=", "state", "if", "state", ":", "log", ".", "info", "(", "'IOU \"{name}\" [{id}]: has activated layer 1 keepalive messages'", ".", "format", "(", "name", "=", "self", "...
Enables or disables layer 1 keepalive messages. :param state: boolean
[ "Enables", "or", "disables", "layer", "1", "keepalive", "messages", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L952-L963
240,528
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM._enable_l1_keepalives
def _enable_l1_keepalives(self, command): """ Enables L1 keepalive messages if supported. :param command: command line """ env = os.environ.copy() if "IOURC" not in os.environ: env["IOURC"] = self.iourc_path try: output = yield from gns3server.utils.asyncio.subprocess_check_output(self._path, "-h", cwd=self.working_dir, env=env, stderr=True) if re.search("-l\s+Enable Layer 1 keepalive messages", output): command.extend(["-l"]) else: raise IOUError("layer 1 keepalive messages are not supported by {}".format(os.path.basename(self._path))) except (OSError, subprocess.SubprocessError) as e: log.warning("could not determine if layer 1 keepalive messages are supported by {}: {}".format(os.path.basename(self._path), e))
python
def _enable_l1_keepalives(self, command): env = os.environ.copy() if "IOURC" not in os.environ: env["IOURC"] = self.iourc_path try: output = yield from gns3server.utils.asyncio.subprocess_check_output(self._path, "-h", cwd=self.working_dir, env=env, stderr=True) if re.search("-l\s+Enable Layer 1 keepalive messages", output): command.extend(["-l"]) else: raise IOUError("layer 1 keepalive messages are not supported by {}".format(os.path.basename(self._path))) except (OSError, subprocess.SubprocessError) as e: log.warning("could not determine if layer 1 keepalive messages are supported by {}: {}".format(os.path.basename(self._path), e))
[ "def", "_enable_l1_keepalives", "(", "self", ",", "command", ")", ":", "env", "=", "os", ".", "environ", ".", "copy", "(", ")", "if", "\"IOURC\"", "not", "in", "os", ".", "environ", ":", "env", "[", "\"IOURC\"", "]", "=", "self", ".", "iourc_path", "...
Enables L1 keepalive messages if supported. :param command: command line
[ "Enables", "L1", "keepalive", "messages", "if", "supported", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L966-L983
240,529
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.startup_config_content
def startup_config_content(self): """ Returns the content of the current startup-config file. """ config_file = self.startup_config_file if config_file is None: return None try: with open(config_file, "rb") as f: return f.read().decode("utf-8", errors="replace") except OSError as e: raise IOUError("Can't read startup-config file '{}': {}".format(config_file, e))
python
def startup_config_content(self): config_file = self.startup_config_file if config_file is None: return None try: with open(config_file, "rb") as f: return f.read().decode("utf-8", errors="replace") except OSError as e: raise IOUError("Can't read startup-config file '{}': {}".format(config_file, e))
[ "def", "startup_config_content", "(", "self", ")", ":", "config_file", "=", "self", ".", "startup_config_file", "if", "config_file", "is", "None", ":", "return", "None", "try", ":", "with", "open", "(", "config_file", ",", "\"rb\"", ")", "as", "f", ":", "r...
Returns the content of the current startup-config file.
[ "Returns", "the", "content", "of", "the", "current", "startup", "-", "config", "file", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L986-L999
240,530
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.startup_config_content
def startup_config_content(self, startup_config): """ Update the startup config :param startup_config: content of the startup configuration file """ try: startup_config_path = os.path.join(self.working_dir, "startup-config.cfg") if startup_config is None: startup_config = '' # We disallow erasing the startup config file if len(startup_config) == 0 and os.path.exists(startup_config_path): return with open(startup_config_path, 'w+', encoding='utf-8') as f: if len(startup_config) == 0: f.write('') else: startup_config = startup_config.replace("%h", self._name) f.write(startup_config) vlan_file = os.path.join(self.working_dir, "vlan.dat-{:05d}".format(self.application_id)) if os.path.exists(vlan_file): try: os.remove(vlan_file) except OSError as e: log.error("Could not delete VLAN file '{}': {}".format(vlan_file, e)) except OSError as e: raise IOUError("Can't write startup-config file '{}': {}".format(startup_config_path, e))
python
def startup_config_content(self, startup_config): try: startup_config_path = os.path.join(self.working_dir, "startup-config.cfg") if startup_config is None: startup_config = '' # We disallow erasing the startup config file if len(startup_config) == 0 and os.path.exists(startup_config_path): return with open(startup_config_path, 'w+', encoding='utf-8') as f: if len(startup_config) == 0: f.write('') else: startup_config = startup_config.replace("%h", self._name) f.write(startup_config) vlan_file = os.path.join(self.working_dir, "vlan.dat-{:05d}".format(self.application_id)) if os.path.exists(vlan_file): try: os.remove(vlan_file) except OSError as e: log.error("Could not delete VLAN file '{}': {}".format(vlan_file, e)) except OSError as e: raise IOUError("Can't write startup-config file '{}': {}".format(startup_config_path, e))
[ "def", "startup_config_content", "(", "self", ",", "startup_config", ")", ":", "try", ":", "startup_config_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "working_dir", ",", "\"startup-config.cfg\"", ")", "if", "startup_config", "is", "None", ":...
Update the startup config :param startup_config: content of the startup configuration file
[ "Update", "the", "startup", "config" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L1002-L1034
240,531
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.private_config_content
def private_config_content(self): """ Returns the content of the current private-config file. """ config_file = self.private_config_file if config_file is None: return None try: with open(config_file, "rb") as f: return f.read().decode("utf-8", errors="replace") except OSError as e: raise IOUError("Can't read private-config file '{}': {}".format(config_file, e))
python
def private_config_content(self): config_file = self.private_config_file if config_file is None: return None try: with open(config_file, "rb") as f: return f.read().decode("utf-8", errors="replace") except OSError as e: raise IOUError("Can't read private-config file '{}': {}".format(config_file, e))
[ "def", "private_config_content", "(", "self", ")", ":", "config_file", "=", "self", ".", "private_config_file", "if", "config_file", "is", "None", ":", "return", "None", "try", ":", "with", "open", "(", "config_file", ",", "\"rb\"", ")", "as", "f", ":", "r...
Returns the content of the current private-config file.
[ "Returns", "the", "content", "of", "the", "current", "private", "-", "config", "file", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L1037-L1050
240,532
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.private_config_content
def private_config_content(self, private_config): """ Update the private config :param private_config: content of the private configuration file """ try: private_config_path = os.path.join(self.working_dir, "private-config.cfg") if private_config is None: private_config = '' # We disallow erasing the private config file if len(private_config) == 0 and os.path.exists(private_config_path): return with open(private_config_path, 'w+', encoding='utf-8') as f: if len(private_config) == 0: f.write('') else: private_config = private_config.replace("%h", self._name) f.write(private_config) except OSError as e: raise IOUError("Can't write private-config file '{}': {}".format(private_config_path, e))
python
def private_config_content(self, private_config): try: private_config_path = os.path.join(self.working_dir, "private-config.cfg") if private_config is None: private_config = '' # We disallow erasing the private config file if len(private_config) == 0 and os.path.exists(private_config_path): return with open(private_config_path, 'w+', encoding='utf-8') as f: if len(private_config) == 0: f.write('') else: private_config = private_config.replace("%h", self._name) f.write(private_config) except OSError as e: raise IOUError("Can't write private-config file '{}': {}".format(private_config_path, e))
[ "def", "private_config_content", "(", "self", ",", "private_config", ")", ":", "try", ":", "private_config_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "working_dir", ",", "\"private-config.cfg\"", ")", "if", "private_config", "is", "None", ":...
Update the private config :param private_config: content of the private configuration file
[ "Update", "the", "private", "config" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L1053-L1077
240,533
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.startup_config_file
def startup_config_file(self): """ Returns the startup-config file for this IOU VM. :returns: path to config file. None if the file doesn't exist """ path = os.path.join(self.working_dir, 'startup-config.cfg') if os.path.exists(path): return path else: return None
python
def startup_config_file(self): path = os.path.join(self.working_dir, 'startup-config.cfg') if os.path.exists(path): return path else: return None
[ "def", "startup_config_file", "(", "self", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "working_dir", ",", "'startup-config.cfg'", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "path", "else"...
Returns the startup-config file for this IOU VM. :returns: path to config file. None if the file doesn't exist
[ "Returns", "the", "startup", "-", "config", "file", "for", "this", "IOU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L1080-L1091
240,534
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.private_config_file
def private_config_file(self): """ Returns the private-config file for this IOU VM. :returns: path to config file. None if the file doesn't exist """ path = os.path.join(self.working_dir, 'private-config.cfg') if os.path.exists(path): return path else: return None
python
def private_config_file(self): path = os.path.join(self.working_dir, 'private-config.cfg') if os.path.exists(path): return path else: return None
[ "def", "private_config_file", "(", "self", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "working_dir", ",", "'private-config.cfg'", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "path", "else"...
Returns the private-config file for this IOU VM. :returns: path to config file. None if the file doesn't exist
[ "Returns", "the", "private", "-", "config", "file", "for", "this", "IOU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L1094-L1105
240,535
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.relative_startup_config_file
def relative_startup_config_file(self): """ Returns the startup-config file relative to the project directory. It's compatible with pre 1.3 projects. :returns: path to startup-config file. None if the file doesn't exist """ path = os.path.join(self.working_dir, 'startup-config.cfg') if os.path.exists(path): return 'startup-config.cfg' else: return None
python
def relative_startup_config_file(self): path = os.path.join(self.working_dir, 'startup-config.cfg') if os.path.exists(path): return 'startup-config.cfg' else: return None
[ "def", "relative_startup_config_file", "(", "self", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "working_dir", ",", "'startup-config.cfg'", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "'start...
Returns the startup-config file relative to the project directory. It's compatible with pre 1.3 projects. :returns: path to startup-config file. None if the file doesn't exist
[ "Returns", "the", "startup", "-", "config", "file", "relative", "to", "the", "project", "directory", ".", "It", "s", "compatible", "with", "pre", "1", ".", "3", "projects", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L1108-L1120
240,536
GNS3/gns3-server
gns3server/compute/iou/iou_vm.py
IOUVM.relative_private_config_file
def relative_private_config_file(self): """ Returns the private-config file relative to the project directory. :returns: path to private-config file. None if the file doesn't exist """ path = os.path.join(self.working_dir, 'private-config.cfg') if os.path.exists(path): return 'private-config.cfg' else: return None
python
def relative_private_config_file(self): path = os.path.join(self.working_dir, 'private-config.cfg') if os.path.exists(path): return 'private-config.cfg' else: return None
[ "def", "relative_private_config_file", "(", "self", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "working_dir", ",", "'private-config.cfg'", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "'priva...
Returns the private-config file relative to the project directory. :returns: path to private-config file. None if the file doesn't exist
[ "Returns", "the", "private", "-", "config", "file", "relative", "to", "the", "project", "directory", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L1123-L1134
240,537
GNS3/gns3-server
gns3server/controller/drawing.py
Drawing.svg
def svg(self, value): """ Set SVG field value. If the svg has embed base64 element we will extract them to disk in order to avoid duplication of content """ if len(value) < 500: self._svg = value return try: root = ET.fromstring(value) except ET.ParseError as e: log.error("Can't parse SVG: {}".format(e)) return # SVG is the default namespace no need to prefix it ET.register_namespace('xmlns', "http://www.w3.org/2000/svg") ET.register_namespace('xmlns:xlink', "http://www.w3.org/1999/xlink") if len(root.findall("{http://www.w3.org/2000/svg}image")) == 1: href = "{http://www.w3.org/1999/xlink}href" elem = root.find("{http://www.w3.org/2000/svg}image") if elem.get(href, "").startswith("data:image/"): changed = True data = elem.get(href, "") extension = re.sub(r"[^a-z0-9]", "", data.split(";")[0].split("/")[1].lower()) data = base64.decodebytes(data.split(",", 1)[1].encode()) # We compute an hash of the image file to avoid duplication filename = hashlib.md5(data).hexdigest() + "." + extension elem.set(href, filename) file_path = os.path.join(self._project.pictures_directory, filename) if not os.path.exists(file_path): with open(file_path, "wb") as f: f.write(data) value = filename # We dump also large svg on disk to keep .gns3 small if len(value) > 1000: filename = hashlib.md5(value.encode()).hexdigest() + ".svg" file_path = os.path.join(self._project.pictures_directory, filename) if not os.path.exists(file_path): with open(file_path, "w+", encoding="utf-8") as f: f.write(value) self._svg = filename else: self._svg = value
python
def svg(self, value): if len(value) < 500: self._svg = value return try: root = ET.fromstring(value) except ET.ParseError as e: log.error("Can't parse SVG: {}".format(e)) return # SVG is the default namespace no need to prefix it ET.register_namespace('xmlns', "http://www.w3.org/2000/svg") ET.register_namespace('xmlns:xlink', "http://www.w3.org/1999/xlink") if len(root.findall("{http://www.w3.org/2000/svg}image")) == 1: href = "{http://www.w3.org/1999/xlink}href" elem = root.find("{http://www.w3.org/2000/svg}image") if elem.get(href, "").startswith("data:image/"): changed = True data = elem.get(href, "") extension = re.sub(r"[^a-z0-9]", "", data.split(";")[0].split("/")[1].lower()) data = base64.decodebytes(data.split(",", 1)[1].encode()) # We compute an hash of the image file to avoid duplication filename = hashlib.md5(data).hexdigest() + "." + extension elem.set(href, filename) file_path = os.path.join(self._project.pictures_directory, filename) if not os.path.exists(file_path): with open(file_path, "wb") as f: f.write(data) value = filename # We dump also large svg on disk to keep .gns3 small if len(value) > 1000: filename = hashlib.md5(value.encode()).hexdigest() + ".svg" file_path = os.path.join(self._project.pictures_directory, filename) if not os.path.exists(file_path): with open(file_path, "w+", encoding="utf-8") as f: f.write(value) self._svg = filename else: self._svg = value
[ "def", "svg", "(", "self", ",", "value", ")", ":", "if", "len", "(", "value", ")", "<", "500", ":", "self", ".", "_svg", "=", "value", "return", "try", ":", "root", "=", "ET", ".", "fromstring", "(", "value", ")", "except", "ET", ".", "ParseError...
Set SVG field value. If the svg has embed base64 element we will extract them to disk in order to avoid duplication of content
[ "Set", "SVG", "field", "value", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/drawing.py#L84-L134
240,538
GNS3/gns3-server
gns3server/controller/drawing.py
Drawing.update
def update(self, **kwargs): """ Update the drawing :param kwargs: Drawing properties """ # Update node properties with additional elements svg_changed = False for prop in kwargs: if prop == "drawing_id": pass # No good reason to change a drawing_id elif getattr(self, prop) != kwargs[prop]: if prop == "svg": # To avoid spamming client with large data we don't send the svg if the SVG didn't change svg_changed = True setattr(self, prop, kwargs[prop]) data = self.__json__() if not svg_changed: del data["svg"] self._project.controller.notification.emit("drawing.updated", data) self._project.dump()
python
def update(self, **kwargs): # Update node properties with additional elements svg_changed = False for prop in kwargs: if prop == "drawing_id": pass # No good reason to change a drawing_id elif getattr(self, prop) != kwargs[prop]: if prop == "svg": # To avoid spamming client with large data we don't send the svg if the SVG didn't change svg_changed = True setattr(self, prop, kwargs[prop]) data = self.__json__() if not svg_changed: del data["svg"] self._project.controller.notification.emit("drawing.updated", data) self._project.dump()
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Update node properties with additional elements", "svg_changed", "=", "False", "for", "prop", "in", "kwargs", ":", "if", "prop", "==", "\"drawing_id\"", ":", "pass", "# No good reason to change a dr...
Update the drawing :param kwargs: Drawing properties
[ "Update", "the", "drawing" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/drawing.py#L169-L190
240,539
GNS3/gns3-server
gns3server/compute/vpcs/__init__.py
VPCS.create_node
def create_node(self, *args, **kwargs): """ Creates a new VPCS VM. :returns: VPCSVM instance """ node = yield from super().create_node(*args, **kwargs) self._free_mac_ids.setdefault(node.project.id, list(range(0, 255))) try: self._used_mac_ids[node.id] = self._free_mac_ids[node.project.id].pop(0) except IndexError: raise VPCSError("Cannot create a new VPCS VM (limit of 255 VMs reached on this host)") return node
python
def create_node(self, *args, **kwargs): node = yield from super().create_node(*args, **kwargs) self._free_mac_ids.setdefault(node.project.id, list(range(0, 255))) try: self._used_mac_ids[node.id] = self._free_mac_ids[node.project.id].pop(0) except IndexError: raise VPCSError("Cannot create a new VPCS VM (limit of 255 VMs reached on this host)") return node
[ "def", "create_node", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "node", "=", "yield", "from", "super", "(", ")", ".", "create_node", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "_free_mac_ids", ".", "setdefa...
Creates a new VPCS VM. :returns: VPCSVM instance
[ "Creates", "a", "new", "VPCS", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/__init__.py#L41-L54
240,540
GNS3/gns3-server
gns3server/compute/vpcs/__init__.py
VPCS.close_node
def close_node(self, node_id, *args, **kwargs): """ Closes a VPCS VM. :returns: VPCSVM instance """ node = self.get_node(node_id) if node_id in self._used_mac_ids: i = self._used_mac_ids[node_id] self._free_mac_ids[node.project.id].insert(0, i) del self._used_mac_ids[node_id] yield from super().close_node(node_id, *args, **kwargs) return node
python
def close_node(self, node_id, *args, **kwargs): node = self.get_node(node_id) if node_id in self._used_mac_ids: i = self._used_mac_ids[node_id] self._free_mac_ids[node.project.id].insert(0, i) del self._used_mac_ids[node_id] yield from super().close_node(node_id, *args, **kwargs) return node
[ "def", "close_node", "(", "self", ",", "node_id", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "node", "=", "self", ".", "get_node", "(", "node_id", ")", "if", "node_id", "in", "self", ".", "_used_mac_ids", ":", "i", "=", "self", ".", "_use...
Closes a VPCS VM. :returns: VPCSVM instance
[ "Closes", "a", "VPCS", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/__init__.py#L57-L70
240,541
GNS3/gns3-server
gns3server/compute/dynamips/nios/nio.py
NIO.delete
def delete(self): """ Deletes this NIO. """ if self._input_filter or self._output_filter: yield from self.unbind_filter("both") yield from self._hypervisor.send("nio delete {}".format(self._name)) log.info("NIO {name} has been deleted".format(name=self._name))
python
def delete(self): if self._input_filter or self._output_filter: yield from self.unbind_filter("both") yield from self._hypervisor.send("nio delete {}".format(self._name)) log.info("NIO {name} has been deleted".format(name=self._name))
[ "def", "delete", "(", "self", ")", ":", "if", "self", ".", "_input_filter", "or", "self", ".", "_output_filter", ":", "yield", "from", "self", ".", "unbind_filter", "(", "\"both\"", ")", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "\"n...
Deletes this NIO.
[ "Deletes", "this", "NIO", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L61-L69
240,542
GNS3/gns3-server
gns3server/compute/dynamips/nios/nio.py
NIO.rename
def rename(self, new_name): """ Renames this NIO :param new_name: new NIO name """ yield from self._hypervisor.send("nio rename {name} {new_name}".format(name=self._name, new_name=new_name)) log.info("NIO {name} renamed to {new_name}".format(name=self._name, new_name=new_name)) self._name = new_name
python
def rename(self, new_name): yield from self._hypervisor.send("nio rename {name} {new_name}".format(name=self._name, new_name=new_name)) log.info("NIO {name} renamed to {new_name}".format(name=self._name, new_name=new_name)) self._name = new_name
[ "def", "rename", "(", "self", ",", "new_name", ")", ":", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "\"nio rename {name} {new_name}\"", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "new_name", "=", "new_name", ")", ")", ...
Renames this NIO :param new_name: new NIO name
[ "Renames", "this", "NIO" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L72-L82
240,543
GNS3/gns3-server
gns3server/compute/dynamips/nios/nio.py
NIO.bind_filter
def bind_filter(self, direction, filter_name): """ Adds a packet filter to this NIO. Filter "freq_drop" drops packets. Filter "capture" captures packets. :param direction: "in", "out" or "both" :param filter_name: name of the filter to apply """ if direction not in self._dynamips_direction: raise DynamipsError("Unknown direction {} to bind filter {}:".format(direction, filter_name)) dynamips_direction = self._dynamips_direction[direction] yield from self._hypervisor.send("nio bind_filter {name} {direction} {filter}".format(name=self._name, direction=dynamips_direction, filter=filter_name)) if direction == "in": self._input_filter = filter_name elif direction == "out": self._output_filter = filter_name elif direction == "both": self._input_filter = filter_name self._output_filter = filter_name
python
def bind_filter(self, direction, filter_name): if direction not in self._dynamips_direction: raise DynamipsError("Unknown direction {} to bind filter {}:".format(direction, filter_name)) dynamips_direction = self._dynamips_direction[direction] yield from self._hypervisor.send("nio bind_filter {name} {direction} {filter}".format(name=self._name, direction=dynamips_direction, filter=filter_name)) if direction == "in": self._input_filter = filter_name elif direction == "out": self._output_filter = filter_name elif direction == "both": self._input_filter = filter_name self._output_filter = filter_name
[ "def", "bind_filter", "(", "self", ",", "direction", ",", "filter_name", ")", ":", "if", "direction", "not", "in", "self", ".", "_dynamips_direction", ":", "raise", "DynamipsError", "(", "\"Unknown direction {} to bind filter {}:\"", ".", "format", "(", "direction",...
Adds a packet filter to this NIO. Filter "freq_drop" drops packets. Filter "capture" captures packets. :param direction: "in", "out" or "both" :param filter_name: name of the filter to apply
[ "Adds", "a", "packet", "filter", "to", "this", "NIO", ".", "Filter", "freq_drop", "drops", "packets", ".", "Filter", "capture", "captures", "packets", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L95-L119
240,544
GNS3/gns3-server
gns3server/compute/dynamips/nios/nio.py
NIO.unbind_filter
def unbind_filter(self, direction): """ Removes packet filter for this NIO. :param direction: "in", "out" or "both" """ if direction not in self._dynamips_direction: raise DynamipsError("Unknown direction {} to unbind filter:".format(direction)) dynamips_direction = self._dynamips_direction[direction] yield from self._hypervisor.send("nio unbind_filter {name} {direction}".format(name=self._name, direction=dynamips_direction)) if direction == "in": self._input_filter = None elif direction == "out": self._output_filter = None elif direction == "both": self._input_filter = None self._output_filter = None
python
def unbind_filter(self, direction): if direction not in self._dynamips_direction: raise DynamipsError("Unknown direction {} to unbind filter:".format(direction)) dynamips_direction = self._dynamips_direction[direction] yield from self._hypervisor.send("nio unbind_filter {name} {direction}".format(name=self._name, direction=dynamips_direction)) if direction == "in": self._input_filter = None elif direction == "out": self._output_filter = None elif direction == "both": self._input_filter = None self._output_filter = None
[ "def", "unbind_filter", "(", "self", ",", "direction", ")", ":", "if", "direction", "not", "in", "self", ".", "_dynamips_direction", ":", "raise", "DynamipsError", "(", "\"Unknown direction {} to unbind filter:\"", ".", "format", "(", "direction", ")", ")", "dynam...
Removes packet filter for this NIO. :param direction: "in", "out" or "both"
[ "Removes", "packet", "filter", "for", "this", "NIO", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L122-L142
240,545
GNS3/gns3-server
gns3server/compute/dynamips/nios/nio.py
NIO.setup_filter
def setup_filter(self, direction, options): """ Setups a packet filter bound with this NIO. Filter "freq_drop" has 1 argument "<frequency>". It will drop everything with a -1 frequency, drop every Nth packet with a positive frequency, or drop nothing. Filter "capture" has 2 arguments "<link_type_name> <output_file>". It will capture packets to the target output file. The link type name is a case-insensitive DLT_ name from the PCAP library constants with the DLT_ part removed.See http://www.tcpdump.org/linktypes.html for a list of all available DLT values. :param direction: "in", "out" or "both" :param options: options for the packet filter (string) """ if direction not in self._dynamips_direction: raise DynamipsError("Unknown direction {} to setup filter:".format(direction)) dynamips_direction = self._dynamips_direction[direction] yield from self._hypervisor.send("nio setup_filter {name} {direction} {options}".format(name=self._name, direction=dynamips_direction, options=options)) if direction == "in": self._input_filter_options = options elif direction == "out": self._output_filter_options = options elif direction == "both": self._input_filter_options = options self._output_filter_options = options
python
def setup_filter(self, direction, options): if direction not in self._dynamips_direction: raise DynamipsError("Unknown direction {} to setup filter:".format(direction)) dynamips_direction = self._dynamips_direction[direction] yield from self._hypervisor.send("nio setup_filter {name} {direction} {options}".format(name=self._name, direction=dynamips_direction, options=options)) if direction == "in": self._input_filter_options = options elif direction == "out": self._output_filter_options = options elif direction == "both": self._input_filter_options = options self._output_filter_options = options
[ "def", "setup_filter", "(", "self", ",", "direction", ",", "options", ")", ":", "if", "direction", "not", "in", "self", ".", "_dynamips_direction", ":", "raise", "DynamipsError", "(", "\"Unknown direction {} to setup filter:\"", ".", "format", "(", "direction", ")...
Setups a packet filter bound with this NIO. Filter "freq_drop" has 1 argument "<frequency>". It will drop everything with a -1 frequency, drop every Nth packet with a positive frequency, or drop nothing. Filter "capture" has 2 arguments "<link_type_name> <output_file>". It will capture packets to the target output file. The link type name is a case-insensitive DLT_ name from the PCAP library constants with the DLT_ part removed.See http://www.tcpdump.org/linktypes.html for a list of all available DLT values. :param direction: "in", "out" or "both" :param options: options for the packet filter (string)
[ "Setups", "a", "packet", "filter", "bound", "with", "this", "NIO", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L145-L177
240,546
GNS3/gns3-server
gns3server/compute/dynamips/nios/nio.py
NIO.get_stats
def get_stats(self): """ Gets statistics for this NIO. :returns: NIO statistics (string with packets in, packets out, bytes in, bytes out) """ stats = yield from self._hypervisor.send("nio get_stats {}".format(self._name)) return stats[0]
python
def get_stats(self): stats = yield from self._hypervisor.send("nio get_stats {}".format(self._name)) return stats[0]
[ "def", "get_stats", "(", "self", ")", ":", "stats", "=", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "\"nio get_stats {}\"", ".", "format", "(", "self", ".", "_name", ")", ")", "return", "stats", "[", "0", "]" ]
Gets statistics for this NIO. :returns: NIO statistics (string with packets in, packets out, bytes in, bytes out)
[ "Gets", "statistics", "for", "this", "NIO", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L200-L208
240,547
GNS3/gns3-server
gns3server/compute/dynamips/nios/nio.py
NIO.set_bandwidth
def set_bandwidth(self, bandwidth): """ Sets bandwidth constraint. :param bandwidth: bandwidth integer value (in Kb/s) """ yield from self._hypervisor.send("nio set_bandwidth {name} {bandwidth}".format(name=self._name, bandwidth=bandwidth)) self._bandwidth = bandwidth
python
def set_bandwidth(self, bandwidth): yield from self._hypervisor.send("nio set_bandwidth {name} {bandwidth}".format(name=self._name, bandwidth=bandwidth)) self._bandwidth = bandwidth
[ "def", "set_bandwidth", "(", "self", ",", "bandwidth", ")", ":", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "\"nio set_bandwidth {name} {bandwidth}\"", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "bandwidth", "=", "bandwidth...
Sets bandwidth constraint. :param bandwidth: bandwidth integer value (in Kb/s)
[ "Sets", "bandwidth", "constraint", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L229-L237
240,548
GNS3/gns3-server
gns3server/controller/node.py
Node.create
def create(self): """ Create the node on the compute server """ data = self._node_data() data["node_id"] = self._id if self._node_type == "docker": timeout = None else: timeout = 1200 trial = 0 while trial != 6: try: response = yield from self._compute.post("/projects/{}/{}/nodes".format(self._project.id, self._node_type), data=data, timeout=timeout) except ComputeConflict as e: if e.response.get("exception") == "ImageMissingError": res = yield from self._upload_missing_image(self._node_type, e.response["image"]) if not res: raise e else: raise e else: yield from self.parse_node_response(response.json) return True trial += 1
python
def create(self): data = self._node_data() data["node_id"] = self._id if self._node_type == "docker": timeout = None else: timeout = 1200 trial = 0 while trial != 6: try: response = yield from self._compute.post("/projects/{}/{}/nodes".format(self._project.id, self._node_type), data=data, timeout=timeout) except ComputeConflict as e: if e.response.get("exception") == "ImageMissingError": res = yield from self._upload_missing_image(self._node_type, e.response["image"]) if not res: raise e else: raise e else: yield from self.parse_node_response(response.json) return True trial += 1
[ "def", "create", "(", "self", ")", ":", "data", "=", "self", ".", "_node_data", "(", ")", "data", "[", "\"node_id\"", "]", "=", "self", ".", "_id", "if", "self", ".", "_node_type", "==", "\"docker\"", ":", "timeout", "=", "None", "else", ":", "timeou...
Create the node on the compute server
[ "Create", "the", "node", "on", "the", "compute", "server" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L326-L350
240,549
GNS3/gns3-server
gns3server/controller/node.py
Node.update
def update(self, **kwargs): """ Update the node on the compute server :param kwargs: Node properties """ # When updating properties used only on controller we don't need to call the compute update_compute = False old_json = self.__json__() compute_properties = None # Update node properties with additional elements for prop in kwargs: if getattr(self, prop) != kwargs[prop]: if prop not in self.CONTROLLER_ONLY_PROPERTIES: update_compute = True # We update properties on the compute and wait for the anwser from the compute node if prop == "properties": compute_properties = kwargs[prop] else: setattr(self, prop, kwargs[prop]) self._list_ports() # We send notif only if object has changed if old_json != self.__json__(): self.project.controller.notification.emit("node.updated", self.__json__()) if update_compute: data = self._node_data(properties=compute_properties) response = yield from self.put(None, data=data) yield from self.parse_node_response(response.json) self.project.dump()
python
def update(self, **kwargs): # When updating properties used only on controller we don't need to call the compute update_compute = False old_json = self.__json__() compute_properties = None # Update node properties with additional elements for prop in kwargs: if getattr(self, prop) != kwargs[prop]: if prop not in self.CONTROLLER_ONLY_PROPERTIES: update_compute = True # We update properties on the compute and wait for the anwser from the compute node if prop == "properties": compute_properties = kwargs[prop] else: setattr(self, prop, kwargs[prop]) self._list_ports() # We send notif only if object has changed if old_json != self.__json__(): self.project.controller.notification.emit("node.updated", self.__json__()) if update_compute: data = self._node_data(properties=compute_properties) response = yield from self.put(None, data=data) yield from self.parse_node_response(response.json) self.project.dump()
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# When updating properties used only on controller we don't need to call the compute", "update_compute", "=", "False", "old_json", "=", "self", ".", "__json__", "(", ")", "compute_properties", "=", "None"...
Update the node on the compute server :param kwargs: Node properties
[ "Update", "the", "node", "on", "the", "compute", "server" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L353-L386
240,550
GNS3/gns3-server
gns3server/controller/node.py
Node.parse_node_response
def parse_node_response(self, response): """ Update the object with the remote node object """ for key, value in response.items(): if key == "console": self._console = value elif key == "node_directory": self._node_directory = value elif key == "command_line": self._command_line = value elif key == "status": self._status = value elif key == "console_type": self._console_type = value elif key == "name": self.name = value elif key in ["node_id", "project_id", "console_host", "startup_config_content", "private_config_content", "startup_script"]: if key in self._properties: del self._properties[key] else: self._properties[key] = value self._list_ports() for link in self._links: yield from link.node_updated(self)
python
def parse_node_response(self, response): for key, value in response.items(): if key == "console": self._console = value elif key == "node_directory": self._node_directory = value elif key == "command_line": self._command_line = value elif key == "status": self._status = value elif key == "console_type": self._console_type = value elif key == "name": self.name = value elif key in ["node_id", "project_id", "console_host", "startup_config_content", "private_config_content", "startup_script"]: if key in self._properties: del self._properties[key] else: self._properties[key] = value self._list_ports() for link in self._links: yield from link.node_updated(self)
[ "def", "parse_node_response", "(", "self", ",", "response", ")", ":", "for", "key", ",", "value", "in", "response", ".", "items", "(", ")", ":", "if", "key", "==", "\"console\"", ":", "self", ".", "_console", "=", "value", "elif", "key", "==", "\"node_...
Update the object with the remote node object
[ "Update", "the", "object", "with", "the", "remote", "node", "object" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L389-L416
240,551
GNS3/gns3-server
gns3server/controller/node.py
Node._node_data
def _node_data(self, properties=None): """ Prepare node data to send to the remote controller :param properties: If properties is None use actual property otherwise use the parameter """ if properties: data = copy.copy(properties) else: data = copy.copy(self._properties) # We replace the startup script name by the content of the file mapping = { "base_script_file": "startup_script", "startup_config": "startup_config_content", "private_config": "private_config_content", } for k, v in mapping.items(): if k in list(self._properties.keys()): data[v] = self._base_config_file_content(self._properties[k]) del data[k] del self._properties[k] # We send the file only one time data["name"] = self._name if self._console: # console is optional for builtin nodes data["console"] = self._console if self._console_type: data["console_type"] = self._console_type # None properties are not be send. Because it can mean the emulator doesn't support it for key in list(data.keys()): if data[key] is None or data[key] is {} or key in self.CONTROLLER_ONLY_PROPERTIES: del data[key] return data
python
def _node_data(self, properties=None): if properties: data = copy.copy(properties) else: data = copy.copy(self._properties) # We replace the startup script name by the content of the file mapping = { "base_script_file": "startup_script", "startup_config": "startup_config_content", "private_config": "private_config_content", } for k, v in mapping.items(): if k in list(self._properties.keys()): data[v] = self._base_config_file_content(self._properties[k]) del data[k] del self._properties[k] # We send the file only one time data["name"] = self._name if self._console: # console is optional for builtin nodes data["console"] = self._console if self._console_type: data["console_type"] = self._console_type # None properties are not be send. Because it can mean the emulator doesn't support it for key in list(data.keys()): if data[key] is None or data[key] is {} or key in self.CONTROLLER_ONLY_PROPERTIES: del data[key] return data
[ "def", "_node_data", "(", "self", ",", "properties", "=", "None", ")", ":", "if", "properties", ":", "data", "=", "copy", ".", "copy", "(", "properties", ")", "else", ":", "data", "=", "copy", ".", "copy", "(", "self", ".", "_properties", ")", "# We ...
Prepare node data to send to the remote controller :param properties: If properties is None use actual property otherwise use the parameter
[ "Prepare", "node", "data", "to", "send", "to", "the", "remote", "controller" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L418-L450
240,552
GNS3/gns3-server
gns3server/controller/node.py
Node.reload
def reload(self): """ Suspend a node """ try: yield from self.post("/reload", timeout=240) except asyncio.TimeoutError: raise aiohttp.web.HTTPRequestTimeout(text="Timeout when reloading {}".format(self._name))
python
def reload(self): try: yield from self.post("/reload", timeout=240) except asyncio.TimeoutError: raise aiohttp.web.HTTPRequestTimeout(text="Timeout when reloading {}".format(self._name))
[ "def", "reload", "(", "self", ")", ":", "try", ":", "yield", "from", "self", ".", "post", "(", "\"/reload\"", ",", "timeout", "=", "240", ")", "except", "asyncio", ".", "TimeoutError", ":", "raise", "aiohttp", ".", "web", ".", "HTTPRequestTimeout", "(", ...
Suspend a node
[ "Suspend", "a", "node" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L498-L505
240,553
GNS3/gns3-server
gns3server/controller/node.py
Node._upload_missing_image
def _upload_missing_image(self, type, img): """ Search an image on local computer and upload it to remote compute if the image exists """ for directory in images_directories(type): image = os.path.join(directory, img) if os.path.exists(image): self.project.controller.notification.emit("log.info", {"message": "Uploading missing image {}".format(img)}) try: with open(image, 'rb') as f: yield from self._compute.post("/{}/images/{}".format(self._node_type, os.path.basename(img)), data=f, timeout=None) except OSError as e: raise aiohttp.web.HTTPConflict(text="Can't upload {}: {}".format(image, str(e))) self.project.controller.notification.emit("log.info", {"message": "Upload finished for {}".format(img)}) return True return False
python
def _upload_missing_image(self, type, img): for directory in images_directories(type): image = os.path.join(directory, img) if os.path.exists(image): self.project.controller.notification.emit("log.info", {"message": "Uploading missing image {}".format(img)}) try: with open(image, 'rb') as f: yield from self._compute.post("/{}/images/{}".format(self._node_type, os.path.basename(img)), data=f, timeout=None) except OSError as e: raise aiohttp.web.HTTPConflict(text="Can't upload {}: {}".format(image, str(e))) self.project.controller.notification.emit("log.info", {"message": "Upload finished for {}".format(img)}) return True return False
[ "def", "_upload_missing_image", "(", "self", ",", "type", ",", "img", ")", ":", "for", "directory", "in", "images_directories", "(", "type", ")", ":", "image", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "img", ")", "if", "os", ".", "...
Search an image on local computer and upload it to remote compute if the image exists
[ "Search", "an", "image", "on", "local", "computer", "and", "upload", "it", "to", "remote", "compute", "if", "the", "image", "exists" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L542-L558
240,554
GNS3/gns3-server
gns3server/controller/node.py
Node.dynamips_auto_idlepc
def dynamips_auto_idlepc(self): """ Compute the idle PC for a dynamips node """ return (yield from self._compute.get("/projects/{}/{}/nodes/{}/auto_idlepc".format(self._project.id, self._node_type, self._id), timeout=240)).json
python
def dynamips_auto_idlepc(self): return (yield from self._compute.get("/projects/{}/{}/nodes/{}/auto_idlepc".format(self._project.id, self._node_type, self._id), timeout=240)).json
[ "def", "dynamips_auto_idlepc", "(", "self", ")", ":", "return", "(", "yield", "from", "self", ".", "_compute", ".", "get", "(", "\"/projects/{}/{}/nodes/{}/auto_idlepc\"", ".", "format", "(", "self", ".", "_project", ".", "id", ",", "self", ".", "_node_type", ...
Compute the idle PC for a dynamips node
[ "Compute", "the", "idle", "PC", "for", "a", "dynamips", "node" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L561-L565
240,555
GNS3/gns3-server
gns3server/controller/node.py
Node.get_port
def get_port(self, adapter_number, port_number): """ Return the port for this adapter_number and port_number or returns None if the port is not found """ for port in self.ports: if port.adapter_number == adapter_number and port.port_number == port_number: return port return None
python
def get_port(self, adapter_number, port_number): for port in self.ports: if port.adapter_number == adapter_number and port.port_number == port_number: return port return None
[ "def", "get_port", "(", "self", ",", "adapter_number", ",", "port_number", ")", ":", "for", "port", "in", "self", ".", "ports", ":", "if", "port", ".", "adapter_number", "==", "adapter_number", "and", "port", ".", "port_number", "==", "port_number", ":", "...
Return the port for this adapter_number and port_number or returns None if the port is not found
[ "Return", "the", "port", "for", "this", "adapter_number", "and", "port_number", "or", "returns", "None", "if", "the", "port", "is", "not", "found" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L574-L582
240,556
GNS3/gns3-server
gns3server/compute/dynamips/nodes/c1700.py
C1700.set_chassis
def set_chassis(self, chassis): """ Sets the chassis. :param: chassis string: 1720, 1721, 1750, 1751 or 1760 """ yield from self._hypervisor.send('c1700 set_chassis "{name}" {chassis}'.format(name=self._name, chassis=chassis)) log.info('Router "{name}" [{id}]: chassis set to {chassis}'.format(name=self._name, id=self._id, chassis=chassis)) self._chassis = chassis self._setup_chassis()
python
def set_chassis(self, chassis): yield from self._hypervisor.send('c1700 set_chassis "{name}" {chassis}'.format(name=self._name, chassis=chassis)) log.info('Router "{name}" [{id}]: chassis set to {chassis}'.format(name=self._name, id=self._id, chassis=chassis)) self._chassis = chassis self._setup_chassis()
[ "def", "set_chassis", "(", "self", ",", "chassis", ")", ":", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'c1700 set_chassis \"{name}\" {chassis}'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "chassis", "=", "chassis", ")"...
Sets the chassis. :param: chassis string: 1720, 1721, 1750, 1751 or 1760
[ "Sets", "the", "chassis", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/c1700.py#L107-L122
240,557
GNS3/gns3-server
gns3server/controller/topology.py
load_topology
def load_topology(path): """ Open a topology file, patch it for last GNS3 release and return it """ log.debug("Read topology %s", path) try: with open(path, encoding="utf-8") as f: topo = json.load(f) except (OSError, UnicodeDecodeError, ValueError) as e: raise aiohttp.web.HTTPConflict(text="Could not load topology {}: {}".format(path, str(e))) if topo.get("revision", 0) > GNS3_FILE_FORMAT_REVISION: raise aiohttp.web.HTTPConflict(text="This project is designed for a more recent version of GNS3 please update GNS3 to version {} or later".format(topo["version"])) changed = False if "revision" not in topo or topo["revision"] < GNS3_FILE_FORMAT_REVISION: # If it's an old GNS3 file we need to convert it # first we backup the file try: shutil.copy(path, path + ".backup{}".format(topo.get("revision", 0))) except (OSError) as e: raise aiohttp.web.HTTPConflict(text="Can't write backup of the topology {}: {}".format(path, str(e))) changed = True if "revision" not in topo or topo["revision"] < 5: topo = _convert_1_3_later(topo, path) # Version before GNS3 2.0 alpha 4 if topo["revision"] < 6: topo = _convert_2_0_0_alpha(topo, path) # Version before GNS3 2.0 beta 3 if topo["revision"] < 7: topo = _convert_2_0_0_beta_2(topo, path) # Version before GNS3 2.1 if topo["revision"] < 8: topo = _convert_2_0_0(topo, path) try: _check_topology_schema(topo) except aiohttp.web.HTTPConflict as e: log.error("Can't load the topology %s", path) raise e if changed: try: with open(path, "w+", encoding="utf-8") as f: json.dump(topo, f, indent=4, sort_keys=True) except (OSError) as e: raise aiohttp.web.HTTPConflict(text="Can't write the topology {}: {}".format(path, str(e))) return topo
python
def load_topology(path): log.debug("Read topology %s", path) try: with open(path, encoding="utf-8") as f: topo = json.load(f) except (OSError, UnicodeDecodeError, ValueError) as e: raise aiohttp.web.HTTPConflict(text="Could not load topology {}: {}".format(path, str(e))) if topo.get("revision", 0) > GNS3_FILE_FORMAT_REVISION: raise aiohttp.web.HTTPConflict(text="This project is designed for a more recent version of GNS3 please update GNS3 to version {} or later".format(topo["version"])) changed = False if "revision" not in topo or topo["revision"] < GNS3_FILE_FORMAT_REVISION: # If it's an old GNS3 file we need to convert it # first we backup the file try: shutil.copy(path, path + ".backup{}".format(topo.get("revision", 0))) except (OSError) as e: raise aiohttp.web.HTTPConflict(text="Can't write backup of the topology {}: {}".format(path, str(e))) changed = True if "revision" not in topo or topo["revision"] < 5: topo = _convert_1_3_later(topo, path) # Version before GNS3 2.0 alpha 4 if topo["revision"] < 6: topo = _convert_2_0_0_alpha(topo, path) # Version before GNS3 2.0 beta 3 if topo["revision"] < 7: topo = _convert_2_0_0_beta_2(topo, path) # Version before GNS3 2.1 if topo["revision"] < 8: topo = _convert_2_0_0(topo, path) try: _check_topology_schema(topo) except aiohttp.web.HTTPConflict as e: log.error("Can't load the topology %s", path) raise e if changed: try: with open(path, "w+", encoding="utf-8") as f: json.dump(topo, f, indent=4, sort_keys=True) except (OSError) as e: raise aiohttp.web.HTTPConflict(text="Can't write the topology {}: {}".format(path, str(e))) return topo
[ "def", "load_topology", "(", "path", ")", ":", "log", ".", "debug", "(", "\"Read topology %s\"", ",", "path", ")", "try", ":", "with", "open", "(", "path", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "topo", "=", "json", ".", "load", "(",...
Open a topology file, patch it for last GNS3 release and return it
[ "Open", "a", "topology", "file", "patch", "it", "for", "last", "GNS3", "release", "and", "return", "it" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/topology.py#L115-L166
240,558
GNS3/gns3-server
gns3server/controller/topology.py
_convert_2_0_0
def _convert_2_0_0(topo, topo_path): """ Convert topologies from GNS3 2.0.0 to 2.1 Changes: * Remove startup_script_path from VPCS and base config file for IOU and Dynamips """ topo["revision"] = 8 for node in topo.get("topology", {}).get("nodes", []): if "properties" in node: if node["node_type"] == "vpcs": if "startup_script_path" in node["properties"]: del node["properties"]["startup_script_path"] if "startup_script" in node["properties"]: del node["properties"]["startup_script"] elif node["node_type"] == "dynamips" or node["node_type"] == "iou": if "startup_config" in node["properties"]: del node["properties"]["startup_config"] if "private_config" in node["properties"]: del node["properties"]["private_config"] if "startup_config_content" in node["properties"]: del node["properties"]["startup_config_content"] if "private_config_content" in node["properties"]: del node["properties"]["private_config_content"] return topo
python
def _convert_2_0_0(topo, topo_path): topo["revision"] = 8 for node in topo.get("topology", {}).get("nodes", []): if "properties" in node: if node["node_type"] == "vpcs": if "startup_script_path" in node["properties"]: del node["properties"]["startup_script_path"] if "startup_script" in node["properties"]: del node["properties"]["startup_script"] elif node["node_type"] == "dynamips" or node["node_type"] == "iou": if "startup_config" in node["properties"]: del node["properties"]["startup_config"] if "private_config" in node["properties"]: del node["properties"]["private_config"] if "startup_config_content" in node["properties"]: del node["properties"]["startup_config_content"] if "private_config_content" in node["properties"]: del node["properties"]["private_config_content"] return topo
[ "def", "_convert_2_0_0", "(", "topo", ",", "topo_path", ")", ":", "topo", "[", "\"revision\"", "]", "=", "8", "for", "node", "in", "topo", ".", "get", "(", "\"topology\"", ",", "{", "}", ")", ".", "get", "(", "\"nodes\"", ",", "[", "]", ")", ":", ...
Convert topologies from GNS3 2.0.0 to 2.1 Changes: * Remove startup_script_path from VPCS and base config file for IOU and Dynamips
[ "Convert", "topologies", "from", "GNS3", "2", ".", "0", ".", "0", "to", "2", ".", "1" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/topology.py#L169-L194
240,559
GNS3/gns3-server
gns3server/controller/topology.py
_convert_2_0_0_beta_2
def _convert_2_0_0_beta_2(topo, topo_path): """ Convert topologies from GNS3 2.0.0 beta 2 to beta 3. Changes: * Node id folders for dynamips """ topo_dir = os.path.dirname(topo_path) topo["revision"] = 7 for node in topo.get("topology", {}).get("nodes", []): if node["node_type"] == "dynamips": node_id = node["node_id"] dynamips_id = node["properties"]["dynamips_id"] dynamips_dir = os.path.join(topo_dir, "project-files", "dynamips") node_dir = os.path.join(dynamips_dir, node_id) try: os.makedirs(os.path.join(node_dir, "configs"), exist_ok=True) for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "*_i{}_*".format(dynamips_id))): shutil.move(path, os.path.join(node_dir, os.path.basename(path))) for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "configs", "i{}_*".format(dynamips_id))): shutil.move(path, os.path.join(node_dir, "configs", os.path.basename(path))) except OSError as e: raise aiohttp.web.HTTPConflict(text="Can't convert project {}: {}".format(topo_path, str(e))) return topo
python
def _convert_2_0_0_beta_2(topo, topo_path): topo_dir = os.path.dirname(topo_path) topo["revision"] = 7 for node in topo.get("topology", {}).get("nodes", []): if node["node_type"] == "dynamips": node_id = node["node_id"] dynamips_id = node["properties"]["dynamips_id"] dynamips_dir = os.path.join(topo_dir, "project-files", "dynamips") node_dir = os.path.join(dynamips_dir, node_id) try: os.makedirs(os.path.join(node_dir, "configs"), exist_ok=True) for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "*_i{}_*".format(dynamips_id))): shutil.move(path, os.path.join(node_dir, os.path.basename(path))) for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "configs", "i{}_*".format(dynamips_id))): shutil.move(path, os.path.join(node_dir, "configs", os.path.basename(path))) except OSError as e: raise aiohttp.web.HTTPConflict(text="Can't convert project {}: {}".format(topo_path, str(e))) return topo
[ "def", "_convert_2_0_0_beta_2", "(", "topo", ",", "topo_path", ")", ":", "topo_dir", "=", "os", ".", "path", ".", "dirname", "(", "topo_path", ")", "topo", "[", "\"revision\"", "]", "=", "7", "for", "node", "in", "topo", ".", "get", "(", "\"topology\"", ...
Convert topologies from GNS3 2.0.0 beta 2 to beta 3. Changes: * Node id folders for dynamips
[ "Convert", "topologies", "from", "GNS3", "2", ".", "0", ".", "0", "beta", "2", "to", "beta", "3", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/topology.py#L197-L222
240,560
GNS3/gns3-server
gns3server/controller/topology.py
_convert_2_0_0_alpha
def _convert_2_0_0_alpha(topo, topo_path): """ Convert topologies from GNS3 2.0.0 alpha to 2.0.0 final. Changes: * No more serial console * No more option for VMware / VirtualBox remote console (always use telnet) """ topo["revision"] = 6 for node in topo.get("topology", {}).get("nodes", []): if node.get("console_type") == "serial": node["console_type"] = "telnet" if node["node_type"] in ("vmware", "virtualbox"): prop = node.get("properties") if "enable_remote_console" in prop: del prop["enable_remote_console"] return topo
python
def _convert_2_0_0_alpha(topo, topo_path): topo["revision"] = 6 for node in topo.get("topology", {}).get("nodes", []): if node.get("console_type") == "serial": node["console_type"] = "telnet" if node["node_type"] in ("vmware", "virtualbox"): prop = node.get("properties") if "enable_remote_console" in prop: del prop["enable_remote_console"] return topo
[ "def", "_convert_2_0_0_alpha", "(", "topo", ",", "topo_path", ")", ":", "topo", "[", "\"revision\"", "]", "=", "6", "for", "node", "in", "topo", ".", "get", "(", "\"topology\"", ",", "{", "}", ")", ".", "get", "(", "\"nodes\"", ",", "[", "]", ")", ...
Convert topologies from GNS3 2.0.0 alpha to 2.0.0 final. Changes: * No more serial console * No more option for VMware / VirtualBox remote console (always use telnet)
[ "Convert", "topologies", "from", "GNS3", "2", ".", "0", ".", "0", "alpha", "to", "2", ".", "0", ".", "0", "final", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/topology.py#L225-L241
240,561
GNS3/gns3-server
gns3server/controller/topology.py
_convert_label
def _convert_label(label): """ Convert a label from 1.X to the new format """ style = qt_font_to_style(label.get("font"), label.get("color")) return { "text": html.escape(label["text"]), "rotation": 0, "style": style, "x": int(label["x"]), "y": int(label["y"]) }
python
def _convert_label(label): style = qt_font_to_style(label.get("font"), label.get("color")) return { "text": html.escape(label["text"]), "rotation": 0, "style": style, "x": int(label["x"]), "y": int(label["y"]) }
[ "def", "_convert_label", "(", "label", ")", ":", "style", "=", "qt_font_to_style", "(", "label", ".", "get", "(", "\"font\"", ")", ",", "label", ".", "get", "(", "\"color\"", ")", ")", "return", "{", "\"text\"", ":", "html", ".", "escape", "(", "label"...
Convert a label from 1.X to the new format
[ "Convert", "a", "label", "from", "1", ".", "X", "to", "the", "new", "format" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/topology.py#L573-L584
240,562
GNS3/gns3-server
gns3server/controller/topology.py
_convert_snapshots
def _convert_snapshots(topo_dir): """ Convert 1.x snapshot to the new format """ old_snapshots_dir = os.path.join(topo_dir, "project-files", "snapshots") if os.path.exists(old_snapshots_dir): new_snapshots_dir = os.path.join(topo_dir, "snapshots") os.makedirs(new_snapshots_dir) for snapshot in os.listdir(old_snapshots_dir): snapshot_dir = os.path.join(old_snapshots_dir, snapshot) if os.path.isdir(snapshot_dir): is_gns3_topo = False # In .gns3project fileformat the .gns3 should be name project.gns3 for file in os.listdir(snapshot_dir): if file.endswith(".gns3"): shutil.move(os.path.join(snapshot_dir, file), os.path.join(snapshot_dir, "project.gns3")) is_gns3_topo = True if is_gns3_topo: snapshot_arc = os.path.join(new_snapshots_dir, snapshot + ".gns3project") with zipfile.ZipFile(snapshot_arc, 'w', allowZip64=True) as myzip: for root, dirs, files in os.walk(snapshot_dir): for file in files: myzip.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), snapshot_dir), compress_type=zipfile.ZIP_DEFLATED) shutil.rmtree(old_snapshots_dir)
python
def _convert_snapshots(topo_dir): old_snapshots_dir = os.path.join(topo_dir, "project-files", "snapshots") if os.path.exists(old_snapshots_dir): new_snapshots_dir = os.path.join(topo_dir, "snapshots") os.makedirs(new_snapshots_dir) for snapshot in os.listdir(old_snapshots_dir): snapshot_dir = os.path.join(old_snapshots_dir, snapshot) if os.path.isdir(snapshot_dir): is_gns3_topo = False # In .gns3project fileformat the .gns3 should be name project.gns3 for file in os.listdir(snapshot_dir): if file.endswith(".gns3"): shutil.move(os.path.join(snapshot_dir, file), os.path.join(snapshot_dir, "project.gns3")) is_gns3_topo = True if is_gns3_topo: snapshot_arc = os.path.join(new_snapshots_dir, snapshot + ".gns3project") with zipfile.ZipFile(snapshot_arc, 'w', allowZip64=True) as myzip: for root, dirs, files in os.walk(snapshot_dir): for file in files: myzip.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), snapshot_dir), compress_type=zipfile.ZIP_DEFLATED) shutil.rmtree(old_snapshots_dir)
[ "def", "_convert_snapshots", "(", "topo_dir", ")", ":", "old_snapshots_dir", "=", "os", ".", "path", ".", "join", "(", "topo_dir", ",", "\"project-files\"", ",", "\"snapshots\"", ")", "if", "os", ".", "path", ".", "exists", "(", "old_snapshots_dir", ")", ":"...
Convert 1.x snapshot to the new format
[ "Convert", "1", ".", "x", "snapshot", "to", "the", "new", "format" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/topology.py#L638-L665
240,563
GNS3/gns3-server
gns3server/controller/topology.py
_convert_qemu_node
def _convert_qemu_node(node, old_node): """ Convert qemu node from 1.X to 2.0 """ # In 2.0 the internet VM is replaced by the NAT node if old_node.get("properties", {}).get("hda_disk_image_md5sum") == "8ebc5a6ec53a1c05b7aa101b5ceefe31": node["console"] = None node["console_type"] = None node["node_type"] = "nat" del old_node["properties"] node["properties"] = { "ports": [ { "interface": "eth1", "name": "nat0", "port_number": 0, "type": "ethernet" } ] } if node["symbol"] is None: node["symbol"] = ":/symbols/cloud.svg" return node node["node_type"] = "qemu" if node["symbol"] is None: node["symbol"] = ":/symbols/qemu_guest.svg" return node
python
def _convert_qemu_node(node, old_node): # In 2.0 the internet VM is replaced by the NAT node if old_node.get("properties", {}).get("hda_disk_image_md5sum") == "8ebc5a6ec53a1c05b7aa101b5ceefe31": node["console"] = None node["console_type"] = None node["node_type"] = "nat" del old_node["properties"] node["properties"] = { "ports": [ { "interface": "eth1", "name": "nat0", "port_number": 0, "type": "ethernet" } ] } if node["symbol"] is None: node["symbol"] = ":/symbols/cloud.svg" return node node["node_type"] = "qemu" if node["symbol"] is None: node["symbol"] = ":/symbols/qemu_guest.svg" return node
[ "def", "_convert_qemu_node", "(", "node", ",", "old_node", ")", ":", "# In 2.0 the internet VM is replaced by the NAT node", "if", "old_node", ".", "get", "(", "\"properties\"", ",", "{", "}", ")", ".", "get", "(", "\"hda_disk_image_md5sum\"", ")", "==", "\"8ebc5a6e...
Convert qemu node from 1.X to 2.0
[ "Convert", "qemu", "node", "from", "1", ".", "X", "to", "2", ".", "0" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/topology.py#L668-L696
240,564
GNS3/gns3-server
gns3server/controller/project.py
open_required
def open_required(func): """ Use this decorator to raise an error if the project is not opened """ def wrapper(self, *args, **kwargs): if self._status == "closed": raise aiohttp.web.HTTPForbidden(text="The project is not opened") return func(self, *args, **kwargs) return wrapper
python
def open_required(func): def wrapper(self, *args, **kwargs): if self._status == "closed": raise aiohttp.web.HTTPForbidden(text="The project is not opened") return func(self, *args, **kwargs) return wrapper
[ "def", "open_required", "(", "func", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_status", "==", "\"closed\"", ":", "raise", "aiohttp", ".", "web", ".", "HTTPForbidden", "(", "text...
Use this decorator to raise an error if the project is not opened
[ "Use", "this", "decorator", "to", "raise", "an", "error", "if", "the", "project", "is", "not", "opened" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L47-L56
240,565
GNS3/gns3-server
gns3server/controller/project.py
Project.captures_directory
def captures_directory(self): """ Location of the captures files """ path = os.path.join(self._path, "project-files", "captures") os.makedirs(path, exist_ok=True) return path
python
def captures_directory(self): path = os.path.join(self._path, "project-files", "captures") os.makedirs(path, exist_ok=True) return path
[ "def", "captures_directory", "(", "self", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_path", ",", "\"project-files\"", ",", "\"captures\"", ")", "os", ".", "makedirs", "(", "path", ",", "exist_ok", "=", "True", ")", "retu...
Location of the captures files
[ "Location", "of", "the", "captures", "files" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L325-L331
240,566
GNS3/gns3-server
gns3server/controller/project.py
Project.remove_allocated_node_name
def remove_allocated_node_name(self, name): """ Removes an allocated node name :param name: allocated node name """ if name in self._allocated_node_names: self._allocated_node_names.remove(name)
python
def remove_allocated_node_name(self, name): if name in self._allocated_node_names: self._allocated_node_names.remove(name)
[ "def", "remove_allocated_node_name", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "_allocated_node_names", ":", "self", ".", "_allocated_node_names", ".", "remove", "(", "name", ")" ]
Removes an allocated node name :param name: allocated node name
[ "Removes", "an", "allocated", "node", "name" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L349-L357
240,567
GNS3/gns3-server
gns3server/controller/project.py
Project.update_allocated_node_name
def update_allocated_node_name(self, base_name): """ Updates a node name or generate a new if no node name is available. :param base_name: new node base name """ if base_name is None: return None base_name = re.sub(r"[ ]", "", base_name) if base_name in self._allocated_node_names: base_name = re.sub(r"[0-9]+$", "{0}", base_name) if '{0}' in base_name or '{id}' in base_name: # base name is a template, replace {0} or {id} by an unique identifier for number in range(1, 1000000): try: name = base_name.format(number, id=number, name="Node") except KeyError as e: raise aiohttp.web.HTTPConflict(text="{" + e.args[0] + "} is not a valid replacement string in the node name") except (ValueError, IndexError) as e: raise aiohttp.web.HTTPConflict(text="{} is not a valid replacement string in the node name".format(base_name)) if name not in self._allocated_node_names: self._allocated_node_names.add(name) return name else: if base_name not in self._allocated_node_names: self._allocated_node_names.add(base_name) return base_name # base name is not unique, let's find a unique name by appending a number for number in range(1, 1000000): name = base_name + str(number) if name not in self._allocated_node_names: self._allocated_node_names.add(name) return name raise aiohttp.web.HTTPConflict(text="A node name could not be allocated (node limit reached?)")
python
def update_allocated_node_name(self, base_name): if base_name is None: return None base_name = re.sub(r"[ ]", "", base_name) if base_name in self._allocated_node_names: base_name = re.sub(r"[0-9]+$", "{0}", base_name) if '{0}' in base_name or '{id}' in base_name: # base name is a template, replace {0} or {id} by an unique identifier for number in range(1, 1000000): try: name = base_name.format(number, id=number, name="Node") except KeyError as e: raise aiohttp.web.HTTPConflict(text="{" + e.args[0] + "} is not a valid replacement string in the node name") except (ValueError, IndexError) as e: raise aiohttp.web.HTTPConflict(text="{} is not a valid replacement string in the node name".format(base_name)) if name not in self._allocated_node_names: self._allocated_node_names.add(name) return name else: if base_name not in self._allocated_node_names: self._allocated_node_names.add(base_name) return base_name # base name is not unique, let's find a unique name by appending a number for number in range(1, 1000000): name = base_name + str(number) if name not in self._allocated_node_names: self._allocated_node_names.add(name) return name raise aiohttp.web.HTTPConflict(text="A node name could not be allocated (node limit reached?)")
[ "def", "update_allocated_node_name", "(", "self", ",", "base_name", ")", ":", "if", "base_name", "is", "None", ":", "return", "None", "base_name", "=", "re", ".", "sub", "(", "r\"[ ]\"", ",", "\"\"", ",", "base_name", ")", "if", "base_name", "in", "self", ...
Updates a node name or generate a new if no node name is available. :param base_name: new node base name
[ "Updates", "a", "node", "name", "or", "generate", "a", "new", "if", "no", "node", "name", "is", "available", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L359-L395
240,568
GNS3/gns3-server
gns3server/controller/project.py
Project.add_node_from_appliance
def add_node_from_appliance(self, appliance_id, x=0, y=0, compute_id=None): """ Create a node from an appliance """ try: template = self.controller.appliances[appliance_id].data except KeyError: msg = "Appliance {} doesn't exist".format(appliance_id) log.error(msg) raise aiohttp.web.HTTPNotFound(text=msg) template["x"] = x template["y"] = y node_type = template.pop("node_type") compute = self.controller.get_compute(template.pop("server", compute_id)) name = template.pop("name") default_name_format = template.pop("default_name_format", "{name}-{0}") name = default_name_format.replace("{name}", name) node_id = str(uuid.uuid4()) node = yield from self.add_node(compute, name, node_id, node_type=node_type, **template) return node
python
def add_node_from_appliance(self, appliance_id, x=0, y=0, compute_id=None): try: template = self.controller.appliances[appliance_id].data except KeyError: msg = "Appliance {} doesn't exist".format(appliance_id) log.error(msg) raise aiohttp.web.HTTPNotFound(text=msg) template["x"] = x template["y"] = y node_type = template.pop("node_type") compute = self.controller.get_compute(template.pop("server", compute_id)) name = template.pop("name") default_name_format = template.pop("default_name_format", "{name}-{0}") name = default_name_format.replace("{name}", name) node_id = str(uuid.uuid4()) node = yield from self.add_node(compute, name, node_id, node_type=node_type, **template) return node
[ "def", "add_node_from_appliance", "(", "self", ",", "appliance_id", ",", "x", "=", "0", ",", "y", "=", "0", ",", "compute_id", "=", "None", ")", ":", "try", ":", "template", "=", "self", ".", "controller", ".", "appliances", "[", "appliance_id", "]", "...
Create a node from an appliance
[ "Create", "a", "node", "from", "an", "appliance" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L406-L425
240,569
GNS3/gns3-server
gns3server/controller/project.py
Project.add_node
def add_node(self, compute, name, node_id, dump=True, node_type=None, **kwargs): """ Create a node or return an existing node :param dump: Dump topology to disk :param kwargs: See the documentation of node """ if node_id in self._nodes: return self._nodes[node_id] node = Node(self, compute, name, node_id=node_id, node_type=node_type, **kwargs) if compute not in self._project_created_on_compute: # For a local server we send the project path if compute.id == "local": yield from compute.post("/projects", data={ "name": self._name, "project_id": self._id, "path": self._path }) else: yield from compute.post("/projects", data={ "name": self._name, "project_id": self._id, }) self._project_created_on_compute.add(compute) yield from node.create() self._nodes[node.id] = node self.controller.notification.emit("node.created", node.__json__()) if dump: self.dump() return node
python
def add_node(self, compute, name, node_id, dump=True, node_type=None, **kwargs): if node_id in self._nodes: return self._nodes[node_id] node = Node(self, compute, name, node_id=node_id, node_type=node_type, **kwargs) if compute not in self._project_created_on_compute: # For a local server we send the project path if compute.id == "local": yield from compute.post("/projects", data={ "name": self._name, "project_id": self._id, "path": self._path }) else: yield from compute.post("/projects", data={ "name": self._name, "project_id": self._id, }) self._project_created_on_compute.add(compute) yield from node.create() self._nodes[node.id] = node self.controller.notification.emit("node.created", node.__json__()) if dump: self.dump() return node
[ "def", "add_node", "(", "self", ",", "compute", ",", "name", ",", "node_id", ",", "dump", "=", "True", ",", "node_type", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "node_id", "in", "self", ".", "_nodes", ":", "return", "self", ".", "_nod...
Create a node or return an existing node :param dump: Dump topology to disk :param kwargs: See the documentation of node
[ "Create", "a", "node", "or", "return", "an", "existing", "node" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L429-L461
240,570
GNS3/gns3-server
gns3server/controller/project.py
Project.__delete_node_links
def __delete_node_links(self, node): """ Delete all link connected to this node. The operation use a lock to avoid cleaning links from multiple nodes at the same time. """ for link in list(self._links.values()): if node in link.nodes: yield from self.delete_link(link.id, force_delete=True)
python
def __delete_node_links(self, node): for link in list(self._links.values()): if node in link.nodes: yield from self.delete_link(link.id, force_delete=True)
[ "def", "__delete_node_links", "(", "self", ",", "node", ")", ":", "for", "link", "in", "list", "(", "self", ".", "_links", ".", "values", "(", ")", ")", ":", "if", "node", "in", "link", ".", "nodes", ":", "yield", "from", "self", ".", "delete_link", ...
Delete all link connected to this node. The operation use a lock to avoid cleaning links from multiple nodes at the same time.
[ "Delete", "all", "link", "connected", "to", "this", "node", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L464-L473
240,571
GNS3/gns3-server
gns3server/controller/project.py
Project.get_node
def get_node(self, node_id): """ Return the node or raise a 404 if the node is unknown """ try: return self._nodes[node_id] except KeyError: raise aiohttp.web.HTTPNotFound(text="Node ID {} doesn't exist".format(node_id))
python
def get_node(self, node_id): try: return self._nodes[node_id] except KeyError: raise aiohttp.web.HTTPNotFound(text="Node ID {} doesn't exist".format(node_id))
[ "def", "get_node", "(", "self", ",", "node_id", ")", ":", "try", ":", "return", "self", ".", "_nodes", "[", "node_id", "]", "except", "KeyError", ":", "raise", "aiohttp", ".", "web", ".", "HTTPNotFound", "(", "text", "=", "\"Node ID {} doesn't exist\"", "....
Return the node or raise a 404 if the node is unknown
[ "Return", "the", "node", "or", "raise", "a", "404", "if", "the", "node", "is", "unknown" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L487-L494
240,572
GNS3/gns3-server
gns3server/controller/project.py
Project.add_drawing
def add_drawing(self, drawing_id=None, dump=True, **kwargs): """ Create an drawing or return an existing drawing :param dump: Dump the topology to disk :param kwargs: See the documentation of drawing """ if drawing_id not in self._drawings: drawing = Drawing(self, drawing_id=drawing_id, **kwargs) self._drawings[drawing.id] = drawing self.controller.notification.emit("drawing.created", drawing.__json__()) if dump: self.dump() return drawing return self._drawings[drawing_id]
python
def add_drawing(self, drawing_id=None, dump=True, **kwargs): if drawing_id not in self._drawings: drawing = Drawing(self, drawing_id=drawing_id, **kwargs) self._drawings[drawing.id] = drawing self.controller.notification.emit("drawing.created", drawing.__json__()) if dump: self.dump() return drawing return self._drawings[drawing_id]
[ "def", "add_drawing", "(", "self", ",", "drawing_id", "=", "None", ",", "dump", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "drawing_id", "not", "in", "self", ".", "_drawings", ":", "drawing", "=", "Drawing", "(", "self", ",", "drawing_id", ...
Create an drawing or return an existing drawing :param dump: Dump the topology to disk :param kwargs: See the documentation of drawing
[ "Create", "an", "drawing", "or", "return", "an", "existing", "drawing" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L512-L526
240,573
GNS3/gns3-server
gns3server/controller/project.py
Project.get_drawing
def get_drawing(self, drawing_id): """ Return the Drawing or raise a 404 if the drawing is unknown """ try: return self._drawings[drawing_id] except KeyError: raise aiohttp.web.HTTPNotFound(text="Drawing ID {} doesn't exist".format(drawing_id))
python
def get_drawing(self, drawing_id): try: return self._drawings[drawing_id] except KeyError: raise aiohttp.web.HTTPNotFound(text="Drawing ID {} doesn't exist".format(drawing_id))
[ "def", "get_drawing", "(", "self", ",", "drawing_id", ")", ":", "try", ":", "return", "self", ".", "_drawings", "[", "drawing_id", "]", "except", "KeyError", ":", "raise", "aiohttp", ".", "web", ".", "HTTPNotFound", "(", "text", "=", "\"Drawing ID {} doesn't...
Return the Drawing or raise a 404 if the drawing is unknown
[ "Return", "the", "Drawing", "or", "raise", "a", "404", "if", "the", "drawing", "is", "unknown" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L529-L536
240,574
GNS3/gns3-server
gns3server/controller/project.py
Project.add_link
def add_link(self, link_id=None, dump=True): """ Create a link. By default the link is empty :param dump: Dump topology to disk """ if link_id and link_id in self._links: return self._links[link_id] link = UDPLink(self, link_id=link_id) self._links[link.id] = link if dump: self.dump() return link
python
def add_link(self, link_id=None, dump=True): if link_id and link_id in self._links: return self._links[link_id] link = UDPLink(self, link_id=link_id) self._links[link.id] = link if dump: self.dump() return link
[ "def", "add_link", "(", "self", ",", "link_id", "=", "None", ",", "dump", "=", "True", ")", ":", "if", "link_id", "and", "link_id", "in", "self", ".", "_links", ":", "return", "self", ".", "_links", "[", "link_id", "]", "link", "=", "UDPLink", "(", ...
Create a link. By default the link is empty :param dump: Dump topology to disk
[ "Create", "a", "link", ".", "By", "default", "the", "link", "is", "empty" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L548-L560
240,575
GNS3/gns3-server
gns3server/controller/project.py
Project.get_link
def get_link(self, link_id): """ Return the Link or raise a 404 if the link is unknown """ try: return self._links[link_id] except KeyError: raise aiohttp.web.HTTPNotFound(text="Link ID {} doesn't exist".format(link_id))
python
def get_link(self, link_id): try: return self._links[link_id] except KeyError: raise aiohttp.web.HTTPNotFound(text="Link ID {} doesn't exist".format(link_id))
[ "def", "get_link", "(", "self", ",", "link_id", ")", ":", "try", ":", "return", "self", ".", "_links", "[", "link_id", "]", "except", "KeyError", ":", "raise", "aiohttp", ".", "web", ".", "HTTPNotFound", "(", "text", "=", "\"Link ID {} doesn't exist\"", "....
Return the Link or raise a 404 if the link is unknown
[ "Return", "the", "Link", "or", "raise", "a", "404", "if", "the", "link", "is", "unknown" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L576-L583
240,576
GNS3/gns3-server
gns3server/controller/project.py
Project.get_snapshot
def get_snapshot(self, snapshot_id): """ Return the snapshot or raise a 404 if the snapshot is unknown """ try: return self._snapshots[snapshot_id] except KeyError: raise aiohttp.web.HTTPNotFound(text="Snapshot ID {} doesn't exist".format(snapshot_id))
python
def get_snapshot(self, snapshot_id): try: return self._snapshots[snapshot_id] except KeyError: raise aiohttp.web.HTTPNotFound(text="Snapshot ID {} doesn't exist".format(snapshot_id))
[ "def", "get_snapshot", "(", "self", ",", "snapshot_id", ")", ":", "try", ":", "return", "self", ".", "_snapshots", "[", "snapshot_id", "]", "except", "KeyError", ":", "raise", "aiohttp", ".", "web", ".", "HTTPNotFound", "(", "text", "=", "\"Snapshot ID {} do...
Return the snapshot or raise a 404 if the snapshot is unknown
[ "Return", "the", "snapshot", "or", "raise", "a", "404", "if", "the", "snapshot", "is", "unknown" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L600-L607
240,577
GNS3/gns3-server
gns3server/controller/project.py
Project.snapshot
def snapshot(self, name): """ Snapshot the project :param name: Name of the snapshot """ if name in [snap.name for snap in self.snapshots.values()]: raise aiohttp.web_exceptions.HTTPConflict(text="The snapshot {} already exist".format(name)) snapshot = Snapshot(self, name=name) try: if os.path.exists(snapshot.path): raise aiohttp.web_exceptions.HTTPConflict(text="The snapshot {} already exist".format(name)) os.makedirs(os.path.join(self.path, "snapshots"), exist_ok=True) with tempfile.TemporaryDirectory() as tmpdir: zipstream = yield from export_project(self, tmpdir, keep_compute_id=True, allow_all_nodes=True) try: with open(snapshot.path, "wb") as f: for data in zipstream: f.write(data) except OSError as e: raise aiohttp.web.HTTPConflict(text="Could not write snapshot file '{}': {}".format(snapshot.path, e)) except OSError as e: raise aiohttp.web.HTTPInternalServerError(text="Could not create project directory: {}".format(e)) self._snapshots[snapshot.id] = snapshot return snapshot
python
def snapshot(self, name): if name in [snap.name for snap in self.snapshots.values()]: raise aiohttp.web_exceptions.HTTPConflict(text="The snapshot {} already exist".format(name)) snapshot = Snapshot(self, name=name) try: if os.path.exists(snapshot.path): raise aiohttp.web_exceptions.HTTPConflict(text="The snapshot {} already exist".format(name)) os.makedirs(os.path.join(self.path, "snapshots"), exist_ok=True) with tempfile.TemporaryDirectory() as tmpdir: zipstream = yield from export_project(self, tmpdir, keep_compute_id=True, allow_all_nodes=True) try: with open(snapshot.path, "wb") as f: for data in zipstream: f.write(data) except OSError as e: raise aiohttp.web.HTTPConflict(text="Could not write snapshot file '{}': {}".format(snapshot.path, e)) except OSError as e: raise aiohttp.web.HTTPInternalServerError(text="Could not create project directory: {}".format(e)) self._snapshots[snapshot.id] = snapshot return snapshot
[ "def", "snapshot", "(", "self", ",", "name", ")", ":", "if", "name", "in", "[", "snap", ".", "name", "for", "snap", "in", "self", ".", "snapshots", ".", "values", "(", ")", "]", ":", "raise", "aiohttp", ".", "web_exceptions", ".", "HTTPConflict", "("...
Snapshot the project :param name: Name of the snapshot
[ "Snapshot", "the", "project" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L611-L640
240,578
GNS3/gns3-server
gns3server/controller/project.py
Project._cleanPictures
def _cleanPictures(self): """ Delete unused images """ # Project have been deleted if not os.path.exists(self.path): return try: pictures = set(os.listdir(self.pictures_directory)) for drawing in self._drawings.values(): try: pictures.remove(drawing.ressource_filename) except KeyError: pass for pict in pictures: os.remove(os.path.join(self.pictures_directory, pict)) except OSError as e: log.warning(str(e))
python
def _cleanPictures(self): # Project have been deleted if not os.path.exists(self.path): return try: pictures = set(os.listdir(self.pictures_directory)) for drawing in self._drawings.values(): try: pictures.remove(drawing.ressource_filename) except KeyError: pass for pict in pictures: os.remove(os.path.join(self.pictures_directory, pict)) except OSError as e: log.warning(str(e))
[ "def", "_cleanPictures", "(", "self", ")", ":", "# Project have been deleted", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "path", ")", ":", "return", "try", ":", "pictures", "=", "set", "(", "os", ".", "listdir", "(", "self", ".",...
Delete unused images
[ "Delete", "unused", "images" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L663-L682
240,579
GNS3/gns3-server
gns3server/controller/project.py
Project.delete_on_computes
def delete_on_computes(self): """ Delete the project on computes but not on controller """ for compute in list(self._project_created_on_compute): if compute.id != "local": yield from compute.delete("/projects/{}".format(self._id)) self._project_created_on_compute.remove(compute)
python
def delete_on_computes(self): for compute in list(self._project_created_on_compute): if compute.id != "local": yield from compute.delete("/projects/{}".format(self._id)) self._project_created_on_compute.remove(compute)
[ "def", "delete_on_computes", "(", "self", ")", ":", "for", "compute", "in", "list", "(", "self", ".", "_project_created_on_compute", ")", ":", "if", "compute", ".", "id", "!=", "\"local\"", ":", "yield", "from", "compute", ".", "delete", "(", "\"/projects/{}...
Delete the project on computes but not on controller
[ "Delete", "the", "project", "on", "computes", "but", "not", "on", "controller" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L701-L708
240,580
GNS3/gns3-server
gns3server/controller/project.py
Project.duplicate
def duplicate(self, name=None, location=None): """ Duplicate a project It's the save as feature of the 1.X. It's implemented on top of the export / import features. It will generate a gns3p and reimport it. It's a little slower but we have only one implementation to maintain. :param name: Name of the new project. A new one will be generated in case of conflicts :param location: Parent directory of the new project """ # If the project was not open we open it temporary previous_status = self._status if self._status == "closed": yield from self.open() self.dump() try: with tempfile.TemporaryDirectory() as tmpdir: zipstream = yield from export_project(self, tmpdir, keep_compute_id=True, allow_all_nodes=True) with open(os.path.join(tmpdir, "project.gns3p"), "wb") as f: for data in zipstream: f.write(data) with open(os.path.join(tmpdir, "project.gns3p"), "rb") as f: project = yield from import_project(self._controller, str(uuid.uuid4()), f, location=location, name=name, keep_compute_id=True) except (OSError, UnicodeEncodeError) as e: raise aiohttp.web.HTTPConflict(text="Can not duplicate project: {}".format(str(e))) if previous_status == "closed": yield from self.close() return project
python
def duplicate(self, name=None, location=None): # If the project was not open we open it temporary previous_status = self._status if self._status == "closed": yield from self.open() self.dump() try: with tempfile.TemporaryDirectory() as tmpdir: zipstream = yield from export_project(self, tmpdir, keep_compute_id=True, allow_all_nodes=True) with open(os.path.join(tmpdir, "project.gns3p"), "wb") as f: for data in zipstream: f.write(data) with open(os.path.join(tmpdir, "project.gns3p"), "rb") as f: project = yield from import_project(self._controller, str(uuid.uuid4()), f, location=location, name=name, keep_compute_id=True) except (OSError, UnicodeEncodeError) as e: raise aiohttp.web.HTTPConflict(text="Can not duplicate project: {}".format(str(e))) if previous_status == "closed": yield from self.close() return project
[ "def", "duplicate", "(", "self", ",", "name", "=", "None", ",", "location", "=", "None", ")", ":", "# If the project was not open we open it temporary", "previous_status", "=", "self", ".", "_status", "if", "self", ".", "_status", "==", "\"closed\"", ":", "yield...
Duplicate a project It's the save as feature of the 1.X. It's implemented on top of the export / import features. It will generate a gns3p and reimport it. It's a little slower but we have only one implementation to maintain. :param name: Name of the new project. A new one will be generated in case of conflicts :param location: Parent directory of the new project
[ "Duplicate", "a", "project" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L844-L875
240,581
GNS3/gns3-server
gns3server/controller/project.py
Project.is_running
def is_running(self): """ If a node is started or paused return True """ for node in self._nodes.values(): # Some node type are always running we ignore them if node.status != "stopped" and not node.is_always_running(): return True return False
python
def is_running(self): for node in self._nodes.values(): # Some node type are always running we ignore them if node.status != "stopped" and not node.is_always_running(): return True return False
[ "def", "is_running", "(", "self", ")", ":", "for", "node", "in", "self", ".", "_nodes", ".", "values", "(", ")", ":", "# Some node type are always running we ignore them", "if", "node", ".", "status", "!=", "\"stopped\"", "and", "not", "node", ".", "is_always_...
If a node is started or paused return True
[ "If", "a", "node", "is", "started", "or", "paused", "return", "True" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L877-L885
240,582
GNS3/gns3-server
gns3server/controller/project.py
Project.dump
def dump(self): """ Dump topology to disk """ try: topo = project_to_topology(self) path = self._topology_file() log.debug("Write %s", path) with open(path + ".tmp", "w+", encoding="utf-8") as f: json.dump(topo, f, indent=4, sort_keys=True) shutil.move(path + ".tmp", path) except OSError as e: raise aiohttp.web.HTTPInternalServerError(text="Could not write topology: {}".format(e))
python
def dump(self): try: topo = project_to_topology(self) path = self._topology_file() log.debug("Write %s", path) with open(path + ".tmp", "w+", encoding="utf-8") as f: json.dump(topo, f, indent=4, sort_keys=True) shutil.move(path + ".tmp", path) except OSError as e: raise aiohttp.web.HTTPInternalServerError(text="Could not write topology: {}".format(e))
[ "def", "dump", "(", "self", ")", ":", "try", ":", "topo", "=", "project_to_topology", "(", "self", ")", "path", "=", "self", ".", "_topology_file", "(", ")", "log", ".", "debug", "(", "\"Write %s\"", ",", "path", ")", "with", "open", "(", "path", "+"...
Dump topology to disk
[ "Dump", "topology", "to", "disk" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L887-L899
240,583
GNS3/gns3-server
gns3server/controller/project.py
Project.start_all
def start_all(self): """ Start all nodes """ pool = Pool(concurrency=3) for node in self.nodes.values(): pool.append(node.start) yield from pool.join()
python
def start_all(self): pool = Pool(concurrency=3) for node in self.nodes.values(): pool.append(node.start) yield from pool.join()
[ "def", "start_all", "(", "self", ")", ":", "pool", "=", "Pool", "(", "concurrency", "=", "3", ")", "for", "node", "in", "self", ".", "nodes", ".", "values", "(", ")", ":", "pool", ".", "append", "(", "node", ".", "start", ")", "yield", "from", "p...
Start all nodes
[ "Start", "all", "nodes" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L902-L909
240,584
GNS3/gns3-server
gns3server/controller/project.py
Project.stop_all
def stop_all(self): """ Stop all nodes """ pool = Pool(concurrency=3) for node in self.nodes.values(): pool.append(node.stop) yield from pool.join()
python
def stop_all(self): pool = Pool(concurrency=3) for node in self.nodes.values(): pool.append(node.stop) yield from pool.join()
[ "def", "stop_all", "(", "self", ")", ":", "pool", "=", "Pool", "(", "concurrency", "=", "3", ")", "for", "node", "in", "self", ".", "nodes", ".", "values", "(", ")", ":", "pool", ".", "append", "(", "node", ".", "stop", ")", "yield", "from", "poo...
Stop all nodes
[ "Stop", "all", "nodes" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L912-L919
240,585
GNS3/gns3-server
gns3server/controller/project.py
Project.suspend_all
def suspend_all(self): """ Suspend all nodes """ pool = Pool(concurrency=3) for node in self.nodes.values(): pool.append(node.suspend) yield from pool.join()
python
def suspend_all(self): pool = Pool(concurrency=3) for node in self.nodes.values(): pool.append(node.suspend) yield from pool.join()
[ "def", "suspend_all", "(", "self", ")", ":", "pool", "=", "Pool", "(", "concurrency", "=", "3", ")", "for", "node", "in", "self", ".", "nodes", ".", "values", "(", ")", ":", "pool", ".", "append", "(", "node", ".", "suspend", ")", "yield", "from", ...
Suspend all nodes
[ "Suspend", "all", "nodes" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L922-L929
240,586
GNS3/gns3-server
gns3server/utils/asyncio/input_stream.py
InputStream._get_match
def _get_match(self, prefix): """ Return the key that maps to this prefix. """ # (hard coded) If we match a CPR response, return Keys.CPRResponse. # (This one doesn't fit in the ANSI_SEQUENCES, because it contains # integer variables.) if _cpr_response_re.match(prefix): return Keys.CPRResponse elif _mouse_event_re.match(prefix): return Keys.Vt100MouseEvent # Otherwise, use the mappings. try: return ANSI_SEQUENCES[prefix] except KeyError: return None
python
def _get_match(self, prefix): # (hard coded) If we match a CPR response, return Keys.CPRResponse. # (This one doesn't fit in the ANSI_SEQUENCES, because it contains # integer variables.) if _cpr_response_re.match(prefix): return Keys.CPRResponse elif _mouse_event_re.match(prefix): return Keys.Vt100MouseEvent # Otherwise, use the mappings. try: return ANSI_SEQUENCES[prefix] except KeyError: return None
[ "def", "_get_match", "(", "self", ",", "prefix", ")", ":", "# (hard coded) If we match a CPR response, return Keys.CPRResponse.", "# (This one doesn't fit in the ANSI_SEQUENCES, because it contains", "# integer variables.)", "if", "_cpr_response_re", ".", "match", "(", "prefix", ")...
Return the key that maps to this prefix.
[ "Return", "the", "key", "that", "maps", "to", "this", "prefix", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/input_stream.py#L259-L276
240,587
GNS3/gns3-server
gns3server/utils/asyncio/input_stream.py
InputStream._call_handler
def _call_handler(self, key, insert_text): """ Callback to handler. """ if isinstance(key, tuple): for k in key: self._call_handler(k, insert_text) else: if key == Keys.BracketedPaste: self._in_bracketed_paste = True self._paste_buffer = '' else: self.feed_key_callback(KeyPress(key, insert_text))
python
def _call_handler(self, key, insert_text): if isinstance(key, tuple): for k in key: self._call_handler(k, insert_text) else: if key == Keys.BracketedPaste: self._in_bracketed_paste = True self._paste_buffer = '' else: self.feed_key_callback(KeyPress(key, insert_text))
[ "def", "_call_handler", "(", "self", ",", "key", ",", "insert_text", ")", ":", "if", "isinstance", "(", "key", ",", "tuple", ")", ":", "for", "k", "in", "key", ":", "self", ".", "_call_handler", "(", "k", ",", "insert_text", ")", "else", ":", "if", ...
Callback to handler.
[ "Callback", "to", "handler", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/input_stream.py#L328-L340
240,588
GNS3/gns3-server
gns3server/utils/asyncio/input_stream.py
InputStream.feed
def feed(self, data): """ Feed the input stream. :param data: Input string (unicode). """ assert isinstance(data, six.text_type) if _DEBUG_RENDERER_INPUT: self.LOG.write(repr(data).encode('utf-8') + b'\n') self.LOG.flush() # Handle bracketed paste. (We bypass the parser that matches all other # key presses and keep reading input until we see the end mark.) # This is much faster then parsing character by character. if self._in_bracketed_paste: self._paste_buffer += data end_mark = '\x1b[201~' if end_mark in self._paste_buffer: end_index = self._paste_buffer.index(end_mark) # Feed content to key bindings. paste_content = self._paste_buffer[:end_index] self.feed_key_callback(KeyPress(Keys.BracketedPaste, paste_content)) # Quit bracketed paste mode and handle remaining input. self._in_bracketed_paste = False remaining = self._paste_buffer[end_index + len(end_mark):] self._paste_buffer = '' self.feed(remaining) # Handle normal input character by character. else: for i, c in enumerate(data): if self._in_bracketed_paste: # Quit loop and process from this position when the parser # entered bracketed paste. self.feed(data[i:]) break else: # Replace \r by \n. (Some clients send \r instead of \n # when enter is pressed. E.g. telnet and some other # terminals.) # XXX: We should remove this in a future version. It *is* # now possible to recognise the difference. # (We remove ICRNL/INLCR/IGNCR below.) # However, this breaks IPython and maybe other applications, # because they bind ControlJ (\n) for handling the Enter key. # When this is removed, replace Enter=ControlJ by # Enter=ControlM in keys.py. if c == '\r': c = '\n' self._input_parser.send(c)
python
def feed(self, data): assert isinstance(data, six.text_type) if _DEBUG_RENDERER_INPUT: self.LOG.write(repr(data).encode('utf-8') + b'\n') self.LOG.flush() # Handle bracketed paste. (We bypass the parser that matches all other # key presses and keep reading input until we see the end mark.) # This is much faster then parsing character by character. if self._in_bracketed_paste: self._paste_buffer += data end_mark = '\x1b[201~' if end_mark in self._paste_buffer: end_index = self._paste_buffer.index(end_mark) # Feed content to key bindings. paste_content = self._paste_buffer[:end_index] self.feed_key_callback(KeyPress(Keys.BracketedPaste, paste_content)) # Quit bracketed paste mode and handle remaining input. self._in_bracketed_paste = False remaining = self._paste_buffer[end_index + len(end_mark):] self._paste_buffer = '' self.feed(remaining) # Handle normal input character by character. else: for i, c in enumerate(data): if self._in_bracketed_paste: # Quit loop and process from this position when the parser # entered bracketed paste. self.feed(data[i:]) break else: # Replace \r by \n. (Some clients send \r instead of \n # when enter is pressed. E.g. telnet and some other # terminals.) # XXX: We should remove this in a future version. It *is* # now possible to recognise the difference. # (We remove ICRNL/INLCR/IGNCR below.) # However, this breaks IPython and maybe other applications, # because they bind ControlJ (\n) for handling the Enter key. # When this is removed, replace Enter=ControlJ by # Enter=ControlM in keys.py. if c == '\r': c = '\n' self._input_parser.send(c)
[ "def", "feed", "(", "self", ",", "data", ")", ":", "assert", "isinstance", "(", "data", ",", "six", ".", "text_type", ")", "if", "_DEBUG_RENDERER_INPUT", ":", "self", ".", "LOG", ".", "write", "(", "repr", "(", "data", ")", ".", "encode", "(", "'utf-...
Feed the input stream. :param data: Input string (unicode).
[ "Feed", "the", "input", "stream", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/input_stream.py#L342-L398
240,589
GNS3/gns3-server
gns3server/compute/docker/__init__.py
Docker.query
def query(self, method, path, data={}, params={}): """ Make a query to the docker daemon and decode the request :param method: HTTP method :param path: Endpoint in API :param data: Dictionary with the body. Will be transformed to a JSON :param params: Parameters added as a query arg """ response = yield from self.http_query(method, path, data=data, params=params) body = yield from response.read() if body and len(body): if response.headers['CONTENT-TYPE'] == 'application/json': body = json.loads(body.decode("utf-8")) else: body = body.decode("utf-8") log.debug("Query Docker %s %s params=%s data=%s Response: %s", method, path, params, data, body) return body
python
def query(self, method, path, data={}, params={}): response = yield from self.http_query(method, path, data=data, params=params) body = yield from response.read() if body and len(body): if response.headers['CONTENT-TYPE'] == 'application/json': body = json.loads(body.decode("utf-8")) else: body = body.decode("utf-8") log.debug("Query Docker %s %s params=%s data=%s Response: %s", method, path, params, data, body) return body
[ "def", "query", "(", "self", ",", "method", ",", "path", ",", "data", "=", "{", "}", ",", "params", "=", "{", "}", ")", ":", "response", "=", "yield", "from", "self", ".", "http_query", "(", "method", ",", "path", ",", "data", "=", "data", ",", ...
Make a query to the docker daemon and decode the request :param method: HTTP method :param path: Endpoint in API :param data: Dictionary with the body. Will be transformed to a JSON :param params: Parameters added as a query arg
[ "Make", "a", "query", "to", "the", "docker", "daemon", "and", "decode", "the", "request" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/__init__.py#L96-L114
240,590
GNS3/gns3-server
gns3server/compute/docker/__init__.py
Docker.http_query
def http_query(self, method, path, data={}, params={}, timeout=300): """ Make a query to the docker daemon :param method: HTTP method :param path: Endpoint in API :param data: Dictionnary with the body. Will be transformed to a JSON :param params: Parameters added as a query arg :param timeout: Timeout :returns: HTTP response """ data = json.dumps(data) if timeout is None: timeout = 60 * 60 * 24 * 31 # One month timeout if path == 'version': url = "http://docker/v1.12/" + path # API of docker v1.0 else: url = "http://docker/v" + DOCKER_MINIMUM_API_VERSION + "/" + path try: if path != "version": # version is use by check connection yield from self._check_connection() if self._session is None or self._session.closed: connector = self.connector() self._session = aiohttp.ClientSession(connector=connector) response = yield from self._session.request( method, url, params=params, data=data, headers={"content-type": "application/json", }, timeout=timeout ) except (aiohttp.ClientResponseError, aiohttp.ClientOSError) as e: raise DockerError("Docker has returned an error: {}".format(str(e))) except (asyncio.TimeoutError): raise DockerError("Docker timeout " + method + " " + path) if response.status >= 300: body = yield from response.read() try: body = json.loads(body.decode("utf-8"))["message"] except ValueError: pass log.debug("Query Docker %s %s params=%s data=%s Response: %s", method, path, params, data, body) if response.status == 304: raise DockerHttp304Error("Docker has returned an error: {} {}".format(response.status, body)) elif response.status == 404: raise DockerHttp404Error("Docker has returned an error: {} {}".format(response.status, body)) else: raise DockerError("Docker has returned an error: {} {}".format(response.status, body)) return response
python
def http_query(self, method, path, data={}, params={}, timeout=300): data = json.dumps(data) if timeout is None: timeout = 60 * 60 * 24 * 31 # One month timeout if path == 'version': url = "http://docker/v1.12/" + path # API of docker v1.0 else: url = "http://docker/v" + DOCKER_MINIMUM_API_VERSION + "/" + path try: if path != "version": # version is use by check connection yield from self._check_connection() if self._session is None or self._session.closed: connector = self.connector() self._session = aiohttp.ClientSession(connector=connector) response = yield from self._session.request( method, url, params=params, data=data, headers={"content-type": "application/json", }, timeout=timeout ) except (aiohttp.ClientResponseError, aiohttp.ClientOSError) as e: raise DockerError("Docker has returned an error: {}".format(str(e))) except (asyncio.TimeoutError): raise DockerError("Docker timeout " + method + " " + path) if response.status >= 300: body = yield from response.read() try: body = json.loads(body.decode("utf-8"))["message"] except ValueError: pass log.debug("Query Docker %s %s params=%s data=%s Response: %s", method, path, params, data, body) if response.status == 304: raise DockerHttp304Error("Docker has returned an error: {} {}".format(response.status, body)) elif response.status == 404: raise DockerHttp404Error("Docker has returned an error: {} {}".format(response.status, body)) else: raise DockerError("Docker has returned an error: {} {}".format(response.status, body)) return response
[ "def", "http_query", "(", "self", ",", "method", ",", "path", ",", "data", "=", "{", "}", ",", "params", "=", "{", "}", ",", "timeout", "=", "300", ")", ":", "data", "=", "json", ".", "dumps", "(", "data", ")", "if", "timeout", "is", "None", ":...
Make a query to the docker daemon :param method: HTTP method :param path: Endpoint in API :param data: Dictionnary with the body. Will be transformed to a JSON :param params: Parameters added as a query arg :param timeout: Timeout :returns: HTTP response
[ "Make", "a", "query", "to", "the", "docker", "daemon" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/__init__.py#L117-L167
240,591
GNS3/gns3-server
gns3server/compute/docker/__init__.py
Docker.websocket_query
def websocket_query(self, path, params={}): """ Open a websocket connection :param path: Endpoint in API :param params: Parameters added as a query arg :returns: Websocket """ url = "http://docker/v" + self._api_version + "/" + path connection = yield from self._session.ws_connect(url, origin="http://docker", autoping=True) return connection
python
def websocket_query(self, path, params={}): url = "http://docker/v" + self._api_version + "/" + path connection = yield from self._session.ws_connect(url, origin="http://docker", autoping=True) return connection
[ "def", "websocket_query", "(", "self", ",", "path", ",", "params", "=", "{", "}", ")", ":", "url", "=", "\"http://docker/v\"", "+", "self", ".", "_api_version", "+", "\"/\"", "+", "path", "connection", "=", "yield", "from", "self", ".", "_session", ".", ...
Open a websocket connection :param path: Endpoint in API :param params: Parameters added as a query arg :returns: Websocket
[ "Open", "a", "websocket", "connection" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/__init__.py#L170-L183
240,592
GNS3/gns3-server
gns3server/compute/docker/__init__.py
Docker.list_images
def list_images(self): """Gets Docker image list. :returns: list of dicts :rtype: list """ images = [] for image in (yield from self.query("GET", "images/json", params={"all": 0})): if image['RepoTags']: for tag in image['RepoTags']: if tag != "<none>:<none>": images.append({'image': tag}) return sorted(images, key=lambda i: i['image'])
python
def list_images(self): images = [] for image in (yield from self.query("GET", "images/json", params={"all": 0})): if image['RepoTags']: for tag in image['RepoTags']: if tag != "<none>:<none>": images.append({'image': tag}) return sorted(images, key=lambda i: i['image'])
[ "def", "list_images", "(", "self", ")", ":", "images", "=", "[", "]", "for", "image", "in", "(", "yield", "from", "self", ".", "query", "(", "\"GET\"", ",", "\"images/json\"", ",", "params", "=", "{", "\"all\"", ":", "0", "}", ")", ")", ":", "if", ...
Gets Docker image list. :returns: list of dicts :rtype: list
[ "Gets", "Docker", "image", "list", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/__init__.py#L228-L240
240,593
GNS3/gns3-server
gns3server/compute/qemu/__init__.py
Qemu.get_kvm_archs
def get_kvm_archs(): """ Gets a list of architectures for which KVM is available on this server. :returns: List of architectures for which KVM is available on this server. """ kvm = [] if not os.path.exists("/dev/kvm"): return kvm arch = platform.machine() if arch == "x86_64": kvm.append("x86_64") kvm.append("i386") elif arch == "i386": kvm.append("i386") else: kvm.append(platform.machine()) return kvm
python
def get_kvm_archs(): kvm = [] if not os.path.exists("/dev/kvm"): return kvm arch = platform.machine() if arch == "x86_64": kvm.append("x86_64") kvm.append("i386") elif arch == "i386": kvm.append("i386") else: kvm.append(platform.machine()) return kvm
[ "def", "get_kvm_archs", "(", ")", ":", "kvm", "=", "[", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "\"/dev/kvm\"", ")", ":", "return", "kvm", "arch", "=", "platform", ".", "machine", "(", ")", "if", "arch", "==", "\"x86_64\"", ":", "k...
Gets a list of architectures for which KVM is available on this server. :returns: List of architectures for which KVM is available on this server.
[ "Gets", "a", "list", "of", "architectures", "for", "which", "KVM", "is", "available", "on", "this", "server", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/__init__.py#L45-L64
240,594
GNS3/gns3-server
gns3server/compute/qemu/__init__.py
Qemu.paths_list
def paths_list(): """ Gets a folder list of possibly available QEMU binaries on the host. :returns: List of folders where Qemu binaries MAY reside. """ paths = set() try: paths.add(os.getcwd()) except FileNotFoundError: log.warning("The current working directory doesn't exist") if "PATH" in os.environ: paths.update(os.environ["PATH"].split(os.pathsep)) else: log.warning("The PATH environment variable doesn't exist") # look for Qemu binaries in the current working directory and $PATH if sys.platform.startswith("win"): # add specific Windows paths if hasattr(sys, "frozen"): # add any qemu dir in the same location as gns3server.exe to the list of paths exec_dir = os.path.dirname(os.path.abspath(sys.executable)) for f in os.listdir(exec_dir): if f.lower().startswith("qemu"): paths.add(os.path.join(exec_dir, f)) if "PROGRAMFILES(X86)" in os.environ and os.path.exists(os.environ["PROGRAMFILES(X86)"]): paths.add(os.path.join(os.environ["PROGRAMFILES(X86)"], "qemu")) if "PROGRAMFILES" in os.environ and os.path.exists(os.environ["PROGRAMFILES"]): paths.add(os.path.join(os.environ["PROGRAMFILES"], "qemu")) elif sys.platform.startswith("darwin"): if hasattr(sys, "frozen"): # add specific locations on Mac OS X regardless of what's in $PATH paths.update(["/usr/bin", "/usr/local/bin", "/opt/local/bin"]) try: exec_dir = os.path.dirname(os.path.abspath(sys.executable)) paths.add(os.path.abspath(os.path.join(exec_dir, "../Resources/qemu/bin/"))) # If the user run the server by hand from outside except FileNotFoundError: paths.add("/Applications/GNS3.app/Contents/Resources/qemu/bin") return paths
python
def paths_list(): paths = set() try: paths.add(os.getcwd()) except FileNotFoundError: log.warning("The current working directory doesn't exist") if "PATH" in os.environ: paths.update(os.environ["PATH"].split(os.pathsep)) else: log.warning("The PATH environment variable doesn't exist") # look for Qemu binaries in the current working directory and $PATH if sys.platform.startswith("win"): # add specific Windows paths if hasattr(sys, "frozen"): # add any qemu dir in the same location as gns3server.exe to the list of paths exec_dir = os.path.dirname(os.path.abspath(sys.executable)) for f in os.listdir(exec_dir): if f.lower().startswith("qemu"): paths.add(os.path.join(exec_dir, f)) if "PROGRAMFILES(X86)" in os.environ and os.path.exists(os.environ["PROGRAMFILES(X86)"]): paths.add(os.path.join(os.environ["PROGRAMFILES(X86)"], "qemu")) if "PROGRAMFILES" in os.environ and os.path.exists(os.environ["PROGRAMFILES"]): paths.add(os.path.join(os.environ["PROGRAMFILES"], "qemu")) elif sys.platform.startswith("darwin"): if hasattr(sys, "frozen"): # add specific locations on Mac OS X regardless of what's in $PATH paths.update(["/usr/bin", "/usr/local/bin", "/opt/local/bin"]) try: exec_dir = os.path.dirname(os.path.abspath(sys.executable)) paths.add(os.path.abspath(os.path.join(exec_dir, "../Resources/qemu/bin/"))) # If the user run the server by hand from outside except FileNotFoundError: paths.add("/Applications/GNS3.app/Contents/Resources/qemu/bin") return paths
[ "def", "paths_list", "(", ")", ":", "paths", "=", "set", "(", ")", "try", ":", "paths", ".", "add", "(", "os", ".", "getcwd", "(", ")", ")", "except", "FileNotFoundError", ":", "log", ".", "warning", "(", "\"The current working directory doesn't exist\"", ...
Gets a folder list of possibly available QEMU binaries on the host. :returns: List of folders where Qemu binaries MAY reside.
[ "Gets", "a", "folder", "list", "of", "possibly", "available", "QEMU", "binaries", "on", "the", "host", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/__init__.py#L67-L107
240,595
GNS3/gns3-server
gns3server/compute/qemu/__init__.py
Qemu.binary_list
def binary_list(archs=None): """ Gets QEMU binaries list available on the host. :returns: Array of dictionary {"path": Qemu binary path, "version": version of Qemu} """ qemus = [] for path in Qemu.paths_list(): try: for f in os.listdir(path): if f.endswith("-spice"): continue if (f.startswith("qemu-system") or f.startswith("qemu-kvm") or f == "qemu" or f == "qemu.exe") and \ os.access(os.path.join(path, f), os.X_OK) and \ os.path.isfile(os.path.join(path, f)): if archs is not None: for arch in archs: if f.endswith(arch) or f.endswith("{}.exe".format(arch)) or f.endswith("{}w.exe".format(arch)): qemu_path = os.path.join(path, f) version = yield from Qemu.get_qemu_version(qemu_path) qemus.append({"path": qemu_path, "version": version}) else: qemu_path = os.path.join(path, f) version = yield from Qemu.get_qemu_version(qemu_path) qemus.append({"path": qemu_path, "version": version}) except OSError: continue return qemus
python
def binary_list(archs=None): qemus = [] for path in Qemu.paths_list(): try: for f in os.listdir(path): if f.endswith("-spice"): continue if (f.startswith("qemu-system") or f.startswith("qemu-kvm") or f == "qemu" or f == "qemu.exe") and \ os.access(os.path.join(path, f), os.X_OK) and \ os.path.isfile(os.path.join(path, f)): if archs is not None: for arch in archs: if f.endswith(arch) or f.endswith("{}.exe".format(arch)) or f.endswith("{}w.exe".format(arch)): qemu_path = os.path.join(path, f) version = yield from Qemu.get_qemu_version(qemu_path) qemus.append({"path": qemu_path, "version": version}) else: qemu_path = os.path.join(path, f) version = yield from Qemu.get_qemu_version(qemu_path) qemus.append({"path": qemu_path, "version": version}) except OSError: continue return qemus
[ "def", "binary_list", "(", "archs", "=", "None", ")", ":", "qemus", "=", "[", "]", "for", "path", "in", "Qemu", ".", "paths_list", "(", ")", ":", "try", ":", "for", "f", "in", "os", ".", "listdir", "(", "path", ")", ":", "if", "f", ".", "endswi...
Gets QEMU binaries list available on the host. :returns: Array of dictionary {"path": Qemu binary path, "version": version of Qemu}
[ "Gets", "QEMU", "binaries", "list", "available", "on", "the", "host", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/__init__.py#L110-L140
240,596
GNS3/gns3-server
gns3server/compute/qemu/__init__.py
Qemu.img_binary_list
def img_binary_list(): """ Gets QEMU-img binaries list available on the host. :returns: Array of dictionary {"path": Qemu-img binary path, "version": version of Qemu-img} """ qemu_imgs = [] for path in Qemu.paths_list(): try: for f in os.listdir(path): if (f == "qemu-img" or f == "qemu-img.exe") and \ os.access(os.path.join(path, f), os.X_OK) and \ os.path.isfile(os.path.join(path, f)): qemu_path = os.path.join(path, f) version = yield from Qemu._get_qemu_img_version(qemu_path) qemu_imgs.append({"path": qemu_path, "version": version}) except OSError: continue return qemu_imgs
python
def img_binary_list(): qemu_imgs = [] for path in Qemu.paths_list(): try: for f in os.listdir(path): if (f == "qemu-img" or f == "qemu-img.exe") and \ os.access(os.path.join(path, f), os.X_OK) and \ os.path.isfile(os.path.join(path, f)): qemu_path = os.path.join(path, f) version = yield from Qemu._get_qemu_img_version(qemu_path) qemu_imgs.append({"path": qemu_path, "version": version}) except OSError: continue return qemu_imgs
[ "def", "img_binary_list", "(", ")", ":", "qemu_imgs", "=", "[", "]", "for", "path", "in", "Qemu", ".", "paths_list", "(", ")", ":", "try", ":", "for", "f", "in", "os", ".", "listdir", "(", "path", ")", ":", "if", "(", "f", "==", "\"qemu-img\"", "...
Gets QEMU-img binaries list available on the host. :returns: Array of dictionary {"path": Qemu-img binary path, "version": version of Qemu-img}
[ "Gets", "QEMU", "-", "img", "binaries", "list", "available", "on", "the", "host", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/__init__.py#L143-L162
240,597
GNS3/gns3-server
gns3server/compute/qemu/__init__.py
Qemu.get_qemu_version
def get_qemu_version(qemu_path): """ Gets the Qemu version. :param qemu_path: path to Qemu executable. """ if sys.platform.startswith("win"): # Qemu on Windows doesn't return anything with parameter -version # look for a version number in version.txt file in the same directory instead version_file = os.path.join(os.path.dirname(qemu_path), "version.txt") if os.path.isfile(version_file): try: with open(version_file, "rb") as file: version = file.read().decode("utf-8").strip() match = re.search("[0-9\.]+", version) if match: return version except (UnicodeDecodeError, OSError) as e: log.warn("could not read {}: {}".format(version_file, e)) return "" else: try: output = yield from subprocess_check_output(qemu_path, "-version") match = re.search("version\s+([0-9a-z\-\.]+)", output) if match: version = match.group(1) return version else: raise QemuError("Could not determine the Qemu version for {}".format(qemu_path)) except subprocess.SubprocessError as e: raise QemuError("Error while looking for the Qemu version: {}".format(e))
python
def get_qemu_version(qemu_path): if sys.platform.startswith("win"): # Qemu on Windows doesn't return anything with parameter -version # look for a version number in version.txt file in the same directory instead version_file = os.path.join(os.path.dirname(qemu_path), "version.txt") if os.path.isfile(version_file): try: with open(version_file, "rb") as file: version = file.read().decode("utf-8").strip() match = re.search("[0-9\.]+", version) if match: return version except (UnicodeDecodeError, OSError) as e: log.warn("could not read {}: {}".format(version_file, e)) return "" else: try: output = yield from subprocess_check_output(qemu_path, "-version") match = re.search("version\s+([0-9a-z\-\.]+)", output) if match: version = match.group(1) return version else: raise QemuError("Could not determine the Qemu version for {}".format(qemu_path)) except subprocess.SubprocessError as e: raise QemuError("Error while looking for the Qemu version: {}".format(e))
[ "def", "get_qemu_version", "(", "qemu_path", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", ":", "# Qemu on Windows doesn't return anything with parameter -version", "# look for a version number in version.txt file in the same directory instead", ...
Gets the Qemu version. :param qemu_path: path to Qemu executable.
[ "Gets", "the", "Qemu", "version", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/__init__.py#L166-L197
240,598
GNS3/gns3-server
gns3server/compute/qemu/__init__.py
Qemu._get_qemu_img_version
def _get_qemu_img_version(qemu_img_path): """ Gets the Qemu-img version. :param qemu_img_path: path to Qemu-img executable. """ try: output = yield from subprocess_check_output(qemu_img_path, "--version") match = re.search("version\s+([0-9a-z\-\.]+)", output) if match: version = match.group(1) return version else: raise QemuError("Could not determine the Qemu-img version for {}".format(qemu_img_path)) except subprocess.SubprocessError as e: raise QemuError("Error while looking for the Qemu-img version: {}".format(e))
python
def _get_qemu_img_version(qemu_img_path): try: output = yield from subprocess_check_output(qemu_img_path, "--version") match = re.search("version\s+([0-9a-z\-\.]+)", output) if match: version = match.group(1) return version else: raise QemuError("Could not determine the Qemu-img version for {}".format(qemu_img_path)) except subprocess.SubprocessError as e: raise QemuError("Error while looking for the Qemu-img version: {}".format(e))
[ "def", "_get_qemu_img_version", "(", "qemu_img_path", ")", ":", "try", ":", "output", "=", "yield", "from", "subprocess_check_output", "(", "qemu_img_path", ",", "\"--version\"", ")", "match", "=", "re", ".", "search", "(", "\"version\\s+([0-9a-z\\-\\.]+)\"", ",", ...
Gets the Qemu-img version. :param qemu_img_path: path to Qemu-img executable.
[ "Gets", "the", "Qemu", "-", "img", "version", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/__init__.py#L201-L217
240,599
GNS3/gns3-server
gns3server/compute/qemu/__init__.py
Qemu.create_disk
def create_disk(self, qemu_img, path, options): """ Create a qemu disk with qemu-img :param qemu_img: qemu-img binary path :param path: Image path :param options: Disk image creation options """ try: img_format = options.pop("format") img_size = options.pop("size") if not os.path.isabs(path): directory = self.get_images_directory() os.makedirs(directory, exist_ok=True) path = os.path.join(directory, os.path.basename(path)) try: if os.path.exists(path): raise QemuError("Could not create disk image {} already exist".format(path)) except UnicodeEncodeError: raise QemuError("Could not create disk image {}, " "path contains characters not supported by filesystem".format(path)) command = [qemu_img, "create", "-f", img_format] for option in sorted(options.keys()): command.extend(["-o", "{}={}".format(option, options[option])]) command.append(path) command.append("{}M".format(img_size)) process = yield from asyncio.create_subprocess_exec(*command) yield from process.wait() except (OSError, subprocess.SubprocessError) as e: raise QemuError("Could not create disk image {}:{}".format(path, e))
python
def create_disk(self, qemu_img, path, options): try: img_format = options.pop("format") img_size = options.pop("size") if not os.path.isabs(path): directory = self.get_images_directory() os.makedirs(directory, exist_ok=True) path = os.path.join(directory, os.path.basename(path)) try: if os.path.exists(path): raise QemuError("Could not create disk image {} already exist".format(path)) except UnicodeEncodeError: raise QemuError("Could not create disk image {}, " "path contains characters not supported by filesystem".format(path)) command = [qemu_img, "create", "-f", img_format] for option in sorted(options.keys()): command.extend(["-o", "{}={}".format(option, options[option])]) command.append(path) command.append("{}M".format(img_size)) process = yield from asyncio.create_subprocess_exec(*command) yield from process.wait() except (OSError, subprocess.SubprocessError) as e: raise QemuError("Could not create disk image {}:{}".format(path, e))
[ "def", "create_disk", "(", "self", ",", "qemu_img", ",", "path", ",", "options", ")", ":", "try", ":", "img_format", "=", "options", ".", "pop", "(", "\"format\"", ")", "img_size", "=", "options", ".", "pop", "(", "\"size\"", ")", "if", "not", "os", ...
Create a qemu disk with qemu-img :param qemu_img: qemu-img binary path :param path: Image path :param options: Disk image creation options
[ "Create", "a", "qemu", "disk", "with", "qemu", "-", "img" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/__init__.py#L233-L267