id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
226,500 | GNS3/gns3-server | gns3server/controller/gns3vm/virtualbox_gns3_vm.py | VirtualBoxGNS3VM.set_vcpus | def set_vcpus(self, vcpus):
"""
Set the number of vCPU cores for the GNS3 VM.
:param vcpus: number of vCPU cores
"""
yield from self._execute("modifyvm", [self._vmname, "--cpus", str(vcpus)], timeout=3)
log.info("GNS3 VM vCPU count set to {}".format(vcpus)) | python | def set_vcpus(self, vcpus):
"""
Set the number of vCPU cores for the GNS3 VM.
:param vcpus: number of vCPU cores
"""
yield from self._execute("modifyvm", [self._vmname, "--cpus", str(vcpus)], timeout=3)
log.info("GNS3 VM vCPU count set to {}".format(vcpus)) | [
"def",
"set_vcpus",
"(",
"self",
",",
"vcpus",
")",
":",
"yield",
"from",
"self",
".",
"_execute",
"(",
"\"modifyvm\"",
",",
"[",
"self",
".",
"_vmname",
",",
"\"--cpus\"",
",",
"str",
"(",
"vcpus",
")",
"]",
",",
"timeout",
"=",
"3",
")",
"log",
"... | Set the number of vCPU cores for the GNS3 VM.
:param vcpus: number of vCPU cores | [
"Set",
"the",
"number",
"of",
"vCPU",
"cores",
"for",
"the",
"GNS3",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/virtualbox_gns3_vm.py#L293-L301 |
226,501 | GNS3/gns3-server | gns3server/controller/gns3vm/virtualbox_gns3_vm.py | VirtualBoxGNS3VM.set_ram | def set_ram(self, ram):
"""
Set the RAM amount for the GNS3 VM.
:param ram: amount of memory
"""
yield from self._execute("modifyvm", [self._vmname, "--memory", str(ram)], timeout=3)
log.info("GNS3 VM RAM amount set to {}".format(ram)) | python | def set_ram(self, ram):
"""
Set the RAM amount for the GNS3 VM.
:param ram: amount of memory
"""
yield from self._execute("modifyvm", [self._vmname, "--memory", str(ram)], timeout=3)
log.info("GNS3 VM RAM amount set to {}".format(ram)) | [
"def",
"set_ram",
"(",
"self",
",",
"ram",
")",
":",
"yield",
"from",
"self",
".",
"_execute",
"(",
"\"modifyvm\"",
",",
"[",
"self",
".",
"_vmname",
",",
"\"--memory\"",
",",
"str",
"(",
"ram",
")",
"]",
",",
"timeout",
"=",
"3",
")",
"log",
".",
... | Set the RAM amount for the GNS3 VM.
:param ram: amount of memory | [
"Set",
"the",
"RAM",
"amount",
"for",
"the",
"GNS3",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/virtualbox_gns3_vm.py#L304-L312 |
226,502 | GNS3/gns3-server | gns3server/compute/port_manager.py | PortManager.console_host | def console_host(self, new_host):
"""
If allow remote connection we need to bind console host to 0.0.0.0
"""
server_config = Config.instance().get_section_config("Server")
remote_console_connections = server_config.getboolean("allow_remote_console")
if remote_console_connections:
log.warning("Remote console connections are allowed")
self._console_host = "0.0.0.0"
else:
self._console_host = new_host | python | def console_host(self, new_host):
"""
If allow remote connection we need to bind console host to 0.0.0.0
"""
server_config = Config.instance().get_section_config("Server")
remote_console_connections = server_config.getboolean("allow_remote_console")
if remote_console_connections:
log.warning("Remote console connections are allowed")
self._console_host = "0.0.0.0"
else:
self._console_host = new_host | [
"def",
"console_host",
"(",
"self",
",",
"new_host",
")",
":",
"server_config",
"=",
"Config",
".",
"instance",
"(",
")",
".",
"get_section_config",
"(",
"\"Server\"",
")",
"remote_console_connections",
"=",
"server_config",
".",
"getboolean",
"(",
"\"allow_remote... | If allow remote connection we need to bind console host to 0.0.0.0 | [
"If",
"allow",
"remote",
"connection",
"we",
"need",
"to",
"bind",
"console",
"host",
"to",
"0",
".",
"0",
".",
"0",
".",
"0"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/port_manager.py#L76-L86 |
226,503 | GNS3/gns3-server | gns3server/compute/port_manager.py | PortManager.find_unused_port | def find_unused_port(start_port, end_port, host="127.0.0.1", socket_type="TCP", ignore_ports=None):
"""
Finds an unused port in a range.
:param start_port: first port in the range
:param end_port: last port in the range
:param host: host/address for bind()
:param socket_type: TCP (default) or UDP
:param ignore_ports: list of port to ignore within the range
"""
if end_port < start_port:
raise HTTPConflict(text="Invalid port range {}-{}".format(start_port, end_port))
last_exception = None
for port in range(start_port, end_port + 1):
if ignore_ports and (port in ignore_ports or port in BANNED_PORTS):
continue
try:
PortManager._check_port(host, port, socket_type)
if host != "0.0.0.0":
PortManager._check_port("0.0.0.0", port, socket_type)
return port
except OSError as e:
last_exception = e
if port + 1 == end_port:
break
else:
continue
raise HTTPConflict(text="Could not find a free port between {} and {} on host {}, last exception: {}".format(start_port,
end_port,
host,
last_exception)) | python | def find_unused_port(start_port, end_port, host="127.0.0.1", socket_type="TCP", ignore_ports=None):
"""
Finds an unused port in a range.
:param start_port: first port in the range
:param end_port: last port in the range
:param host: host/address for bind()
:param socket_type: TCP (default) or UDP
:param ignore_ports: list of port to ignore within the range
"""
if end_port < start_port:
raise HTTPConflict(text="Invalid port range {}-{}".format(start_port, end_port))
last_exception = None
for port in range(start_port, end_port + 1):
if ignore_ports and (port in ignore_ports or port in BANNED_PORTS):
continue
try:
PortManager._check_port(host, port, socket_type)
if host != "0.0.0.0":
PortManager._check_port("0.0.0.0", port, socket_type)
return port
except OSError as e:
last_exception = e
if port + 1 == end_port:
break
else:
continue
raise HTTPConflict(text="Could not find a free port between {} and {} on host {}, last exception: {}".format(start_port,
end_port,
host,
last_exception)) | [
"def",
"find_unused_port",
"(",
"start_port",
",",
"end_port",
",",
"host",
"=",
"\"127.0.0.1\"",
",",
"socket_type",
"=",
"\"TCP\"",
",",
"ignore_ports",
"=",
"None",
")",
":",
"if",
"end_port",
"<",
"start_port",
":",
"raise",
"HTTPConflict",
"(",
"text",
... | Finds an unused port in a range.
:param start_port: first port in the range
:param end_port: last port in the range
:param host: host/address for bind()
:param socket_type: TCP (default) or UDP
:param ignore_ports: list of port to ignore within the range | [
"Finds",
"an",
"unused",
"port",
"in",
"a",
"range",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/port_manager.py#L131-L165 |
226,504 | GNS3/gns3-server | gns3server/compute/port_manager.py | PortManager._check_port | def _check_port(host, port, socket_type):
"""
Check if an a port is available and raise an OSError if port is not available
:returns: boolean
"""
if socket_type == "UDP":
socket_type = socket.SOCK_DGRAM
else:
socket_type = socket.SOCK_STREAM
for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket_type, 0, socket.AI_PASSIVE):
af, socktype, proto, _, sa = res
with socket.socket(af, socktype, proto) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(sa) # the port is available if bind is a success
return True | python | def _check_port(host, port, socket_type):
"""
Check if an a port is available and raise an OSError if port is not available
:returns: boolean
"""
if socket_type == "UDP":
socket_type = socket.SOCK_DGRAM
else:
socket_type = socket.SOCK_STREAM
for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket_type, 0, socket.AI_PASSIVE):
af, socktype, proto, _, sa = res
with socket.socket(af, socktype, proto) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(sa) # the port is available if bind is a success
return True | [
"def",
"_check_port",
"(",
"host",
",",
"port",
",",
"socket_type",
")",
":",
"if",
"socket_type",
"==",
"\"UDP\"",
":",
"socket_type",
"=",
"socket",
".",
"SOCK_DGRAM",
"else",
":",
"socket_type",
"=",
"socket",
".",
"SOCK_STREAM",
"for",
"res",
"in",
"so... | Check if an a port is available and raise an OSError if port is not available
:returns: boolean | [
"Check",
"if",
"an",
"a",
"port",
"is",
"available",
"and",
"raise",
"an",
"OSError",
"if",
"port",
"is",
"not",
"available"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/port_manager.py#L168-L184 |
226,505 | GNS3/gns3-server | gns3server/compute/port_manager.py | PortManager.get_free_tcp_port | def get_free_tcp_port(self, project, port_range_start=None, port_range_end=None):
"""
Get an available TCP port and reserve it
:param project: Project instance
"""
# use the default range is not specific one is given
if port_range_start is None and port_range_end is None:
port_range_start = self._console_port_range[0]
port_range_end = self._console_port_range[1]
port = self.find_unused_port(port_range_start,
port_range_end,
host=self._console_host,
socket_type="TCP",
ignore_ports=self._used_tcp_ports)
self._used_tcp_ports.add(port)
project.record_tcp_port(port)
log.debug("TCP port {} has been allocated".format(port))
return port | python | def get_free_tcp_port(self, project, port_range_start=None, port_range_end=None):
"""
Get an available TCP port and reserve it
:param project: Project instance
"""
# use the default range is not specific one is given
if port_range_start is None and port_range_end is None:
port_range_start = self._console_port_range[0]
port_range_end = self._console_port_range[1]
port = self.find_unused_port(port_range_start,
port_range_end,
host=self._console_host,
socket_type="TCP",
ignore_ports=self._used_tcp_ports)
self._used_tcp_ports.add(port)
project.record_tcp_port(port)
log.debug("TCP port {} has been allocated".format(port))
return port | [
"def",
"get_free_tcp_port",
"(",
"self",
",",
"project",
",",
"port_range_start",
"=",
"None",
",",
"port_range_end",
"=",
"None",
")",
":",
"# use the default range is not specific one is given",
"if",
"port_range_start",
"is",
"None",
"and",
"port_range_end",
"is",
... | Get an available TCP port and reserve it
:param project: Project instance | [
"Get",
"an",
"available",
"TCP",
"port",
"and",
"reserve",
"it"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/port_manager.py#L186-L207 |
226,506 | GNS3/gns3-server | gns3server/compute/port_manager.py | PortManager.reserve_tcp_port | def reserve_tcp_port(self, port, project, port_range_start=None, port_range_end=None):
"""
Reserve a specific TCP port number. If not available replace it
by another.
:param port: TCP port number
:param project: Project instance
:param port_range_start: Port range to use
:param port_range_end: Port range to use
:returns: The TCP port
"""
# use the default range is not specific one is given
if port_range_start is None and port_range_end is None:
port_range_start = self._console_port_range[0]
port_range_end = self._console_port_range[1]
if port in self._used_tcp_ports:
old_port = port
port = self.get_free_tcp_port(project, port_range_start=port_range_start, port_range_end=port_range_end)
msg = "TCP port {} already in use on host {}. Port has been replaced by {}".format(old_port, self._console_host, port)
log.debug(msg)
#project.emit("log.warning", {"message": msg})
return port
if port < port_range_start or port > port_range_end:
old_port = port
port = self.get_free_tcp_port(project, port_range_start=port_range_start, port_range_end=port_range_end)
msg = "TCP port {} is outside the range {}-{} on host {}. Port has been replaced by {}".format(old_port, port_range_start, port_range_end, self._console_host, port)
log.debug(msg)
#project.emit("log.warning", {"message": msg})
return port
try:
PortManager._check_port(self._console_host, port, "TCP")
except OSError:
old_port = port
port = self.get_free_tcp_port(project, port_range_start=port_range_start, port_range_end=port_range_end)
msg = "TCP port {} already in use on host {}. Port has been replaced by {}".format(old_port, self._console_host, port)
log.debug(msg)
#project.emit("log.warning", {"message": msg})
return port
self._used_tcp_ports.add(port)
project.record_tcp_port(port)
log.debug("TCP port {} has been reserved".format(port))
return port | python | def reserve_tcp_port(self, port, project, port_range_start=None, port_range_end=None):
"""
Reserve a specific TCP port number. If not available replace it
by another.
:param port: TCP port number
:param project: Project instance
:param port_range_start: Port range to use
:param port_range_end: Port range to use
:returns: The TCP port
"""
# use the default range is not specific one is given
if port_range_start is None and port_range_end is None:
port_range_start = self._console_port_range[0]
port_range_end = self._console_port_range[1]
if port in self._used_tcp_ports:
old_port = port
port = self.get_free_tcp_port(project, port_range_start=port_range_start, port_range_end=port_range_end)
msg = "TCP port {} already in use on host {}. Port has been replaced by {}".format(old_port, self._console_host, port)
log.debug(msg)
#project.emit("log.warning", {"message": msg})
return port
if port < port_range_start or port > port_range_end:
old_port = port
port = self.get_free_tcp_port(project, port_range_start=port_range_start, port_range_end=port_range_end)
msg = "TCP port {} is outside the range {}-{} on host {}. Port has been replaced by {}".format(old_port, port_range_start, port_range_end, self._console_host, port)
log.debug(msg)
#project.emit("log.warning", {"message": msg})
return port
try:
PortManager._check_port(self._console_host, port, "TCP")
except OSError:
old_port = port
port = self.get_free_tcp_port(project, port_range_start=port_range_start, port_range_end=port_range_end)
msg = "TCP port {} already in use on host {}. Port has been replaced by {}".format(old_port, self._console_host, port)
log.debug(msg)
#project.emit("log.warning", {"message": msg})
return port
self._used_tcp_ports.add(port)
project.record_tcp_port(port)
log.debug("TCP port {} has been reserved".format(port))
return port | [
"def",
"reserve_tcp_port",
"(",
"self",
",",
"port",
",",
"project",
",",
"port_range_start",
"=",
"None",
",",
"port_range_end",
"=",
"None",
")",
":",
"# use the default range is not specific one is given",
"if",
"port_range_start",
"is",
"None",
"and",
"port_range_... | Reserve a specific TCP port number. If not available replace it
by another.
:param port: TCP port number
:param project: Project instance
:param port_range_start: Port range to use
:param port_range_end: Port range to use
:returns: The TCP port | [
"Reserve",
"a",
"specific",
"TCP",
"port",
"number",
".",
"If",
"not",
"available",
"replace",
"it",
"by",
"another",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/port_manager.py#L209-L253 |
226,507 | GNS3/gns3-server | gns3server/compute/port_manager.py | PortManager.release_tcp_port | def release_tcp_port(self, port, project):
"""
Release a specific TCP port number
:param port: TCP port number
:param project: Project instance
"""
if port in self._used_tcp_ports:
self._used_tcp_ports.remove(port)
project.remove_tcp_port(port)
log.debug("TCP port {} has been released".format(port)) | python | def release_tcp_port(self, port, project):
"""
Release a specific TCP port number
:param port: TCP port number
:param project: Project instance
"""
if port in self._used_tcp_ports:
self._used_tcp_ports.remove(port)
project.remove_tcp_port(port)
log.debug("TCP port {} has been released".format(port)) | [
"def",
"release_tcp_port",
"(",
"self",
",",
"port",
",",
"project",
")",
":",
"if",
"port",
"in",
"self",
".",
"_used_tcp_ports",
":",
"self",
".",
"_used_tcp_ports",
".",
"remove",
"(",
"port",
")",
"project",
".",
"remove_tcp_port",
"(",
"port",
")",
... | Release a specific TCP port number
:param port: TCP port number
:param project: Project instance | [
"Release",
"a",
"specific",
"TCP",
"port",
"number"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/port_manager.py#L255-L266 |
226,508 | GNS3/gns3-server | gns3server/compute/port_manager.py | PortManager.get_free_udp_port | def get_free_udp_port(self, project):
"""
Get an available UDP port and reserve it
:param project: Project instance
"""
port = self.find_unused_port(self._udp_port_range[0],
self._udp_port_range[1],
host=self._udp_host,
socket_type="UDP",
ignore_ports=self._used_udp_ports)
self._used_udp_ports.add(port)
project.record_udp_port(port)
log.debug("UDP port {} has been allocated".format(port))
return port | python | def get_free_udp_port(self, project):
"""
Get an available UDP port and reserve it
:param project: Project instance
"""
port = self.find_unused_port(self._udp_port_range[0],
self._udp_port_range[1],
host=self._udp_host,
socket_type="UDP",
ignore_ports=self._used_udp_ports)
self._used_udp_ports.add(port)
project.record_udp_port(port)
log.debug("UDP port {} has been allocated".format(port))
return port | [
"def",
"get_free_udp_port",
"(",
"self",
",",
"project",
")",
":",
"port",
"=",
"self",
".",
"find_unused_port",
"(",
"self",
".",
"_udp_port_range",
"[",
"0",
"]",
",",
"self",
".",
"_udp_port_range",
"[",
"1",
"]",
",",
"host",
"=",
"self",
".",
"_ud... | Get an available UDP port and reserve it
:param project: Project instance | [
"Get",
"an",
"available",
"UDP",
"port",
"and",
"reserve",
"it"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/port_manager.py#L268-L283 |
226,509 | GNS3/gns3-server | gns3server/compute/port_manager.py | PortManager.reserve_udp_port | def reserve_udp_port(self, port, project):
"""
Reserve a specific UDP port number
:param port: UDP port number
:param project: Project instance
"""
if port in self._used_udp_ports:
raise HTTPConflict(text="UDP port {} already in use on host {}".format(port, self._console_host))
if port < self._udp_port_range[0] or port > self._udp_port_range[1]:
raise HTTPConflict(text="UDP port {} is outside the range {}-{}".format(port, self._udp_port_range[0], self._udp_port_range[1]))
self._used_udp_ports.add(port)
project.record_udp_port(port)
log.debug("UDP port {} has been reserved".format(port)) | python | def reserve_udp_port(self, port, project):
"""
Reserve a specific UDP port number
:param port: UDP port number
:param project: Project instance
"""
if port in self._used_udp_ports:
raise HTTPConflict(text="UDP port {} already in use on host {}".format(port, self._console_host))
if port < self._udp_port_range[0] or port > self._udp_port_range[1]:
raise HTTPConflict(text="UDP port {} is outside the range {}-{}".format(port, self._udp_port_range[0], self._udp_port_range[1]))
self._used_udp_ports.add(port)
project.record_udp_port(port)
log.debug("UDP port {} has been reserved".format(port)) | [
"def",
"reserve_udp_port",
"(",
"self",
",",
"port",
",",
"project",
")",
":",
"if",
"port",
"in",
"self",
".",
"_used_udp_ports",
":",
"raise",
"HTTPConflict",
"(",
"text",
"=",
"\"UDP port {} already in use on host {}\"",
".",
"format",
"(",
"port",
",",
"se... | Reserve a specific UDP port number
:param port: UDP port number
:param project: Project instance | [
"Reserve",
"a",
"specific",
"UDP",
"port",
"number"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/port_manager.py#L285-L299 |
226,510 | GNS3/gns3-server | gns3server/compute/port_manager.py | PortManager.release_udp_port | def release_udp_port(self, port, project):
"""
Release a specific UDP port number
:param port: UDP port number
:param project: Project instance
"""
if port in self._used_udp_ports:
self._used_udp_ports.remove(port)
project.remove_udp_port(port)
log.debug("UDP port {} has been released".format(port)) | python | def release_udp_port(self, port, project):
"""
Release a specific UDP port number
:param port: UDP port number
:param project: Project instance
"""
if port in self._used_udp_ports:
self._used_udp_ports.remove(port)
project.remove_udp_port(port)
log.debug("UDP port {} has been released".format(port)) | [
"def",
"release_udp_port",
"(",
"self",
",",
"port",
",",
"project",
")",
":",
"if",
"port",
"in",
"self",
".",
"_used_udp_ports",
":",
"self",
".",
"_used_udp_ports",
".",
"remove",
"(",
"port",
")",
"project",
".",
"remove_udp_port",
"(",
"port",
")",
... | Release a specific UDP port number
:param port: UDP port number
:param project: Project instance | [
"Release",
"a",
"specific",
"UDP",
"port",
"number"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/port_manager.py#L301-L312 |
226,511 | GNS3/gns3-server | gns3server/compute/iou/__init__.py | IOU.create_node | def create_node(self, *args, **kwargs):
"""
Creates a new IOU VM.
:returns: IOUVM instance
"""
with (yield from self._iou_id_lock):
# wait for a node to be completely created before adding a new one
# this is important otherwise we allocate the same application ID
# when creating multiple IOU node at the same time
application_id = get_next_application_id(self.nodes)
node = yield from super().create_node(*args, application_id=application_id, **kwargs)
return node | python | def create_node(self, *args, **kwargs):
"""
Creates a new IOU VM.
:returns: IOUVM instance
"""
with (yield from self._iou_id_lock):
# wait for a node to be completely created before adding a new one
# this is important otherwise we allocate the same application ID
# when creating multiple IOU node at the same time
application_id = get_next_application_id(self.nodes)
node = yield from super().create_node(*args, application_id=application_id, **kwargs)
return node | [
"def",
"create_node",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"(",
"yield",
"from",
"self",
".",
"_iou_id_lock",
")",
":",
"# wait for a node to be completely created before adding a new one",
"# this is important otherwise we allocate ... | Creates a new IOU VM.
:returns: IOUVM instance | [
"Creates",
"a",
"new",
"IOU",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/__init__.py#L45-L58 |
226,512 | GNS3/gns3-server | scripts/random_query.py | create_link | async def create_link(project, nodes):
"""
Create all possible link of a node
"""
node1 = random.choice(list(nodes.values()))
for port in range(0, 8):
node2 = random.choice(list(nodes.values()))
if node1 == node2:
continue
data = {"nodes":
[
{
"adapter_number": 0,
"node_id": node1["node_id"],
"port_number": port
},
{
"adapter_number": 0,
"node_id": node2["node_id"],
"port_number": port
}
]
}
try:
await post("/projects/{}/links".format(project["project_id"]), body=data)
except (HTTPConflict, HTTPNotFound):
pass | python | async def create_link(project, nodes):
"""
Create all possible link of a node
"""
node1 = random.choice(list(nodes.values()))
for port in range(0, 8):
node2 = random.choice(list(nodes.values()))
if node1 == node2:
continue
data = {"nodes":
[
{
"adapter_number": 0,
"node_id": node1["node_id"],
"port_number": port
},
{
"adapter_number": 0,
"node_id": node2["node_id"],
"port_number": port
}
]
}
try:
await post("/projects/{}/links".format(project["project_id"]), body=data)
except (HTTPConflict, HTTPNotFound):
pass | [
"async",
"def",
"create_link",
"(",
"project",
",",
"nodes",
")",
":",
"node1",
"=",
"random",
".",
"choice",
"(",
"list",
"(",
"nodes",
".",
"values",
"(",
")",
")",
")",
"for",
"port",
"in",
"range",
"(",
"0",
",",
"8",
")",
":",
"node2",
"=",
... | Create all possible link of a node | [
"Create",
"all",
"possible",
"link",
"of",
"a",
"node"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/scripts/random_query.py#L155-L184 |
226,513 | GNS3/gns3-server | gns3server/utils/asyncio/pool.py | Pool.join | def join(self):
"""
Wait for all task to finish
"""
pending = set()
exceptions = set()
while len(self._tasks) > 0 or len(pending) > 0:
while len(self._tasks) > 0 and len(pending) < self._concurrency:
task, args, kwargs = self._tasks.pop(0)
pending.add(task(*args, **kwargs))
(done, pending) = yield from asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
for task in done:
if task.exception():
exceptions.add(task.exception())
if len(exceptions) > 0:
raise exceptions.pop() | python | def join(self):
"""
Wait for all task to finish
"""
pending = set()
exceptions = set()
while len(self._tasks) > 0 or len(pending) > 0:
while len(self._tasks) > 0 and len(pending) < self._concurrency:
task, args, kwargs = self._tasks.pop(0)
pending.add(task(*args, **kwargs))
(done, pending) = yield from asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
for task in done:
if task.exception():
exceptions.add(task.exception())
if len(exceptions) > 0:
raise exceptions.pop() | [
"def",
"join",
"(",
"self",
")",
":",
"pending",
"=",
"set",
"(",
")",
"exceptions",
"=",
"set",
"(",
")",
"while",
"len",
"(",
"self",
".",
"_tasks",
")",
">",
"0",
"or",
"len",
"(",
"pending",
")",
">",
"0",
":",
"while",
"len",
"(",
"self",
... | Wait for all task to finish | [
"Wait",
"for",
"all",
"task",
"to",
"finish"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/pool.py#L34-L49 |
226,514 | GNS3/gns3-server | gns3server/compute/base_node.py | BaseNode.name | def name(self, new_name):
"""
Sets the name of this node.
:param new_name: name
"""
log.info("{module}: {name} [{id}] renamed to {new_name}".format(module=self.manager.module_name,
name=self.name,
id=self.id,
new_name=new_name))
self._name = new_name | python | def name(self, new_name):
"""
Sets the name of this node.
:param new_name: name
"""
log.info("{module}: {name} [{id}] renamed to {new_name}".format(module=self.manager.module_name,
name=self.name,
id=self.id,
new_name=new_name))
self._name = new_name | [
"def",
"name",
"(",
"self",
",",
"new_name",
")",
":",
"log",
".",
"info",
"(",
"\"{module}: {name} [{id}] renamed to {new_name}\"",
".",
"format",
"(",
"module",
"=",
"self",
".",
"manager",
".",
"module_name",
",",
"name",
"=",
"self",
".",
"name",
",",
... | Sets the name of this node.
:param new_name: name | [
"Sets",
"the",
"name",
"of",
"this",
"node",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L176-L187 |
226,515 | GNS3/gns3-server | gns3server/compute/base_node.py | BaseNode.create | def create(self):
"""
Creates the node.
"""
log.info("{module}: {name} [{id}] created".format(module=self.manager.module_name,
name=self.name,
id=self.id)) | python | def create(self):
"""
Creates the node.
"""
log.info("{module}: {name} [{id}] created".format(module=self.manager.module_name,
name=self.name,
id=self.id)) | [
"def",
"create",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"\"{module}: {name} [{id}] created\"",
".",
"format",
"(",
"module",
"=",
"self",
".",
"manager",
".",
"module_name",
",",
"name",
"=",
"self",
".",
"name",
",",
"id",
"=",
"self",
".",
"... | Creates the node. | [
"Creates",
"the",
"node",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L254-L261 |
226,516 | GNS3/gns3-server | gns3server/compute/base_node.py | BaseNode.stop | def stop(self):
"""
Stop the node process.
"""
if self._wrapper_telnet_server:
self._wrapper_telnet_server.close()
yield from self._wrapper_telnet_server.wait_closed()
self.status = "stopped" | python | def stop(self):
"""
Stop the node process.
"""
if self._wrapper_telnet_server:
self._wrapper_telnet_server.close()
yield from self._wrapper_telnet_server.wait_closed()
self.status = "stopped" | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"_wrapper_telnet_server",
":",
"self",
".",
"_wrapper_telnet_server",
".",
"close",
"(",
")",
"yield",
"from",
"self",
".",
"_wrapper_telnet_server",
".",
"wait_closed",
"(",
")",
"self",
".",
"status"... | Stop the node process. | [
"Stop",
"the",
"node",
"process",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L286-L293 |
226,517 | GNS3/gns3-server | gns3server/compute/base_node.py | BaseNode.close | def close(self):
"""
Close the node process.
"""
if self._closed:
return False
log.info("{module}: '{name}' [{id}]: is closing".format(module=self.manager.module_name,
name=self.name,
id=self.id))
if self._console:
self._manager.port_manager.release_tcp_port(self._console, self._project)
self._console = None
if self._wrap_console:
self._manager.port_manager.release_tcp_port(self._internal_console_port, self._project)
self._internal_console_port = None
if self._aux:
self._manager.port_manager.release_tcp_port(self._aux, self._project)
self._aux = None
self._closed = True
return True | python | def close(self):
"""
Close the node process.
"""
if self._closed:
return False
log.info("{module}: '{name}' [{id}]: is closing".format(module=self.manager.module_name,
name=self.name,
id=self.id))
if self._console:
self._manager.port_manager.release_tcp_port(self._console, self._project)
self._console = None
if self._wrap_console:
self._manager.port_manager.release_tcp_port(self._internal_console_port, self._project)
self._internal_console_port = None
if self._aux:
self._manager.port_manager.release_tcp_port(self._aux, self._project)
self._aux = None
self._closed = True
return True | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_closed",
":",
"return",
"False",
"log",
".",
"info",
"(",
"\"{module}: '{name}' [{id}]: is closing\"",
".",
"format",
"(",
"module",
"=",
"self",
".",
"manager",
".",
"module_name",
",",
"name",
"... | Close the node process. | [
"Close",
"the",
"node",
"process",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L303-L327 |
226,518 | GNS3/gns3-server | gns3server/compute/base_node.py | BaseNode.start_wrap_console | def start_wrap_console(self):
"""
Start a telnet proxy for the console allowing multiple client
connected at the same time
"""
if not self._wrap_console or self._console_type != "telnet":
return
remaining_trial = 60
while True:
try:
(reader, writer) = yield from asyncio.open_connection(host="127.0.0.1", port=self._internal_console_port)
break
except (OSError, ConnectionRefusedError) as e:
if remaining_trial <= 0:
raise e
yield from asyncio.sleep(0.1)
remaining_trial -= 1
yield from AsyncioTelnetServer.write_client_intro(writer, echo=True)
server = AsyncioTelnetServer(reader=reader, writer=writer, binary=True, echo=True)
self._wrapper_telnet_server = yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console) | python | def start_wrap_console(self):
"""
Start a telnet proxy for the console allowing multiple client
connected at the same time
"""
if not self._wrap_console or self._console_type != "telnet":
return
remaining_trial = 60
while True:
try:
(reader, writer) = yield from asyncio.open_connection(host="127.0.0.1", port=self._internal_console_port)
break
except (OSError, ConnectionRefusedError) as e:
if remaining_trial <= 0:
raise e
yield from asyncio.sleep(0.1)
remaining_trial -= 1
yield from AsyncioTelnetServer.write_client_intro(writer, echo=True)
server = AsyncioTelnetServer(reader=reader, writer=writer, binary=True, echo=True)
self._wrapper_telnet_server = yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console) | [
"def",
"start_wrap_console",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_wrap_console",
"or",
"self",
".",
"_console_type",
"!=",
"\"telnet\"",
":",
"return",
"remaining_trial",
"=",
"60",
"while",
"True",
":",
"try",
":",
"(",
"reader",
",",
"write... | Start a telnet proxy for the console allowing multiple client
connected at the same time | [
"Start",
"a",
"telnet",
"proxy",
"for",
"the",
"console",
"allowing",
"multiple",
"client",
"connected",
"at",
"the",
"same",
"time"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L330-L349 |
226,519 | GNS3/gns3-server | gns3server/compute/base_node.py | BaseNode.aux | def aux(self, aux):
"""
Changes the aux port
:params aux: Console port (integer) or None to free the port
"""
if aux == self._aux:
return
if self._aux:
self._manager.port_manager.release_tcp_port(self._aux, self._project)
self._aux = None
if aux is not None:
self._aux = self._manager.port_manager.reserve_tcp_port(aux, self._project)
log.info("{module}: '{name}' [{id}]: aux port set to {port}".format(module=self.manager.module_name,
name=self.name,
id=self.id,
port=aux)) | python | def aux(self, aux):
"""
Changes the aux port
:params aux: Console port (integer) or None to free the port
"""
if aux == self._aux:
return
if self._aux:
self._manager.port_manager.release_tcp_port(self._aux, self._project)
self._aux = None
if aux is not None:
self._aux = self._manager.port_manager.reserve_tcp_port(aux, self._project)
log.info("{module}: '{name}' [{id}]: aux port set to {port}".format(module=self.manager.module_name,
name=self.name,
id=self.id,
port=aux)) | [
"def",
"aux",
"(",
"self",
",",
"aux",
")",
":",
"if",
"aux",
"==",
"self",
".",
"_aux",
":",
"return",
"if",
"self",
".",
"_aux",
":",
"self",
".",
"_manager",
".",
"port_manager",
".",
"release_tcp_port",
"(",
"self",
".",
"_aux",
",",
"self",
".... | Changes the aux port
:params aux: Console port (integer) or None to free the port | [
"Changes",
"the",
"aux",
"port"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L376-L394 |
226,520 | GNS3/gns3-server | gns3server/compute/base_node.py | BaseNode.console | def console(self, console):
"""
Changes the console port
:params console: Console port (integer) or None to free the port
"""
if console == self._console:
return
if self._console_type == "vnc" and console is not None and console < 5900:
raise NodeError("VNC console require a port superior or equal to 5900 currently it's {}".format(console))
if self._console:
self._manager.port_manager.release_tcp_port(self._console, self._project)
self._console = None
if console is not None:
if self.console_type == "vnc":
self._console = self._manager.port_manager.reserve_tcp_port(console, self._project, port_range_start=5900, port_range_end=6000)
else:
self._console = self._manager.port_manager.reserve_tcp_port(console, self._project)
log.info("{module}: '{name}' [{id}]: console port set to {port}".format(module=self.manager.module_name,
name=self.name,
id=self.id,
port=console)) | python | def console(self, console):
"""
Changes the console port
:params console: Console port (integer) or None to free the port
"""
if console == self._console:
return
if self._console_type == "vnc" and console is not None and console < 5900:
raise NodeError("VNC console require a port superior or equal to 5900 currently it's {}".format(console))
if self._console:
self._manager.port_manager.release_tcp_port(self._console, self._project)
self._console = None
if console is not None:
if self.console_type == "vnc":
self._console = self._manager.port_manager.reserve_tcp_port(console, self._project, port_range_start=5900, port_range_end=6000)
else:
self._console = self._manager.port_manager.reserve_tcp_port(console, self._project)
log.info("{module}: '{name}' [{id}]: console port set to {port}".format(module=self.manager.module_name,
name=self.name,
id=self.id,
port=console)) | [
"def",
"console",
"(",
"self",
",",
"console",
")",
":",
"if",
"console",
"==",
"self",
".",
"_console",
":",
"return",
"if",
"self",
".",
"_console_type",
"==",
"\"vnc\"",
"and",
"console",
"is",
"not",
"None",
"and",
"console",
"<",
"5900",
":",
"rai... | Changes the console port
:params console: Console port (integer) or None to free the port | [
"Changes",
"the",
"console",
"port"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L407-L432 |
226,521 | GNS3/gns3-server | gns3server/compute/base_node.py | BaseNode.console_type | def console_type(self, console_type):
"""
Sets the console type for this node.
:param console_type: console type (string)
"""
if console_type != self._console_type:
# get a new port if the console type change
self._manager.port_manager.release_tcp_port(self._console, self._project)
if console_type == "vnc":
# VNC is a special case and the range must be 5900-6000
self._console = self._manager.port_manager.get_free_tcp_port(self._project, 5900, 6000)
else:
self._console = self._manager.port_manager.get_free_tcp_port(self._project)
self._console_type = console_type
log.info("{module}: '{name}' [{id}]: console type set to {console_type}".format(module=self.manager.module_name,
name=self.name,
id=self.id,
console_type=console_type)) | python | def console_type(self, console_type):
"""
Sets the console type for this node.
:param console_type: console type (string)
"""
if console_type != self._console_type:
# get a new port if the console type change
self._manager.port_manager.release_tcp_port(self._console, self._project)
if console_type == "vnc":
# VNC is a special case and the range must be 5900-6000
self._console = self._manager.port_manager.get_free_tcp_port(self._project, 5900, 6000)
else:
self._console = self._manager.port_manager.get_free_tcp_port(self._project)
self._console_type = console_type
log.info("{module}: '{name}' [{id}]: console type set to {console_type}".format(module=self.manager.module_name,
name=self.name,
id=self.id,
console_type=console_type)) | [
"def",
"console_type",
"(",
"self",
",",
"console_type",
")",
":",
"if",
"console_type",
"!=",
"self",
".",
"_console_type",
":",
"# get a new port if the console type change",
"self",
".",
"_manager",
".",
"port_manager",
".",
"release_tcp_port",
"(",
"self",
".",
... | Sets the console type for this node.
:param console_type: console type (string) | [
"Sets",
"the",
"console",
"type",
"for",
"this",
"node",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L445-L465 |
226,522 | GNS3/gns3-server | gns3server/compute/base_node.py | BaseNode.ubridge | def ubridge(self):
"""
Returns the uBridge hypervisor.
:returns: instance of uBridge
"""
if self._ubridge_hypervisor and not self._ubridge_hypervisor.is_running():
self._ubridge_hypervisor = None
return self._ubridge_hypervisor | python | def ubridge(self):
"""
Returns the uBridge hypervisor.
:returns: instance of uBridge
"""
if self._ubridge_hypervisor and not self._ubridge_hypervisor.is_running():
self._ubridge_hypervisor = None
return self._ubridge_hypervisor | [
"def",
"ubridge",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ubridge_hypervisor",
"and",
"not",
"self",
".",
"_ubridge_hypervisor",
".",
"is_running",
"(",
")",
":",
"self",
".",
"_ubridge_hypervisor",
"=",
"None",
"return",
"self",
".",
"_ubridge_hypervisor"... | Returns the uBridge hypervisor.
:returns: instance of uBridge | [
"Returns",
"the",
"uBridge",
"hypervisor",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L468-L477 |
226,523 | GNS3/gns3-server | gns3server/compute/base_node.py | BaseNode.ubridge_path | def ubridge_path(self):
"""
Returns the uBridge executable path.
:returns: path to uBridge
"""
path = self._manager.config.get_section_config("Server").get("ubridge_path", "ubridge")
path = shutil.which(path)
return path | python | def ubridge_path(self):
"""
Returns the uBridge executable path.
:returns: path to uBridge
"""
path = self._manager.config.get_section_config("Server").get("ubridge_path", "ubridge")
path = shutil.which(path)
return path | [
"def",
"ubridge_path",
"(",
"self",
")",
":",
"path",
"=",
"self",
".",
"_manager",
".",
"config",
".",
"get_section_config",
"(",
"\"Server\"",
")",
".",
"get",
"(",
"\"ubridge_path\"",
",",
"\"ubridge\"",
")",
"path",
"=",
"shutil",
".",
"which",
"(",
... | Returns the uBridge executable path.
:returns: path to uBridge | [
"Returns",
"the",
"uBridge",
"executable",
"path",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L490-L499 |
226,524 | GNS3/gns3-server | gns3server/compute/base_node.py | BaseNode._ubridge_send | def _ubridge_send(self, command):
"""
Sends a command to uBridge hypervisor.
:param command: command to send
"""
if not self._ubridge_hypervisor or not self._ubridge_hypervisor.is_running():
yield from self._start_ubridge()
if not self._ubridge_hypervisor or not self._ubridge_hypervisor.is_running():
raise NodeError("Cannot send command '{}': uBridge is not running".format(command))
try:
yield from self._ubridge_hypervisor.send(command)
except UbridgeError as e:
raise UbridgeError("{}: {}".format(e, self._ubridge_hypervisor.read_stdout())) | python | def _ubridge_send(self, command):
"""
Sends a command to uBridge hypervisor.
:param command: command to send
"""
if not self._ubridge_hypervisor or not self._ubridge_hypervisor.is_running():
yield from self._start_ubridge()
if not self._ubridge_hypervisor or not self._ubridge_hypervisor.is_running():
raise NodeError("Cannot send command '{}': uBridge is not running".format(command))
try:
yield from self._ubridge_hypervisor.send(command)
except UbridgeError as e:
raise UbridgeError("{}: {}".format(e, self._ubridge_hypervisor.read_stdout())) | [
"def",
"_ubridge_send",
"(",
"self",
",",
"command",
")",
":",
"if",
"not",
"self",
".",
"_ubridge_hypervisor",
"or",
"not",
"self",
".",
"_ubridge_hypervisor",
".",
"is_running",
"(",
")",
":",
"yield",
"from",
"self",
".",
"_start_ubridge",
"(",
")",
"if... | Sends a command to uBridge hypervisor.
:param command: command to send | [
"Sends",
"a",
"command",
"to",
"uBridge",
"hypervisor",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L502-L516 |
226,525 | GNS3/gns3-server | gns3server/compute/base_node.py | BaseNode._stop_ubridge | def _stop_ubridge(self):
"""
Stops uBridge.
"""
if self._ubridge_hypervisor and self._ubridge_hypervisor.is_running():
log.info("Stopping uBridge hypervisor {}:{}".format(self._ubridge_hypervisor.host, self._ubridge_hypervisor.port))
yield from self._ubridge_hypervisor.stop()
self._ubridge_hypervisor = None | python | def _stop_ubridge(self):
"""
Stops uBridge.
"""
if self._ubridge_hypervisor and self._ubridge_hypervisor.is_running():
log.info("Stopping uBridge hypervisor {}:{}".format(self._ubridge_hypervisor.host, self._ubridge_hypervisor.port))
yield from self._ubridge_hypervisor.stop()
self._ubridge_hypervisor = None | [
"def",
"_stop_ubridge",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ubridge_hypervisor",
"and",
"self",
".",
"_ubridge_hypervisor",
".",
"is_running",
"(",
")",
":",
"log",
".",
"info",
"(",
"\"Stopping uBridge hypervisor {}:{}\"",
".",
"format",
"(",
"self",
... | Stops uBridge. | [
"Stops",
"uBridge",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L545-L553 |
226,526 | GNS3/gns3-server | gns3server/compute/base_node.py | BaseNode.add_ubridge_udp_connection | def add_ubridge_udp_connection(self, bridge_name, source_nio, destination_nio):
"""
Creates an UDP connection in uBridge.
:param bridge_name: bridge name in uBridge
:param source_nio: source NIO instance
:param destination_nio: destination NIO instance
"""
yield from self._ubridge_send("bridge create {name}".format(name=bridge_name))
if not isinstance(destination_nio, NIOUDP):
raise NodeError("Destination NIO is not UDP")
yield from self._ubridge_send('bridge add_nio_udp {name} {lport} {rhost} {rport}'.format(name=bridge_name,
lport=source_nio.lport,
rhost=source_nio.rhost,
rport=source_nio.rport))
yield from self._ubridge_send('bridge add_nio_udp {name} {lport} {rhost} {rport}'.format(name=bridge_name,
lport=destination_nio.lport,
rhost=destination_nio.rhost,
rport=destination_nio.rport))
if destination_nio.capturing:
yield from self._ubridge_send('bridge start_capture {name} "{pcap_file}"'.format(name=bridge_name,
pcap_file=destination_nio.pcap_output_file))
yield from self._ubridge_send('bridge start {name}'.format(name=bridge_name))
yield from self._ubridge_apply_filters(bridge_name, destination_nio.filters) | python | def add_ubridge_udp_connection(self, bridge_name, source_nio, destination_nio):
"""
Creates an UDP connection in uBridge.
:param bridge_name: bridge name in uBridge
:param source_nio: source NIO instance
:param destination_nio: destination NIO instance
"""
yield from self._ubridge_send("bridge create {name}".format(name=bridge_name))
if not isinstance(destination_nio, NIOUDP):
raise NodeError("Destination NIO is not UDP")
yield from self._ubridge_send('bridge add_nio_udp {name} {lport} {rhost} {rport}'.format(name=bridge_name,
lport=source_nio.lport,
rhost=source_nio.rhost,
rport=source_nio.rport))
yield from self._ubridge_send('bridge add_nio_udp {name} {lport} {rhost} {rport}'.format(name=bridge_name,
lport=destination_nio.lport,
rhost=destination_nio.rhost,
rport=destination_nio.rport))
if destination_nio.capturing:
yield from self._ubridge_send('bridge start_capture {name} "{pcap_file}"'.format(name=bridge_name,
pcap_file=destination_nio.pcap_output_file))
yield from self._ubridge_send('bridge start {name}'.format(name=bridge_name))
yield from self._ubridge_apply_filters(bridge_name, destination_nio.filters) | [
"def",
"add_ubridge_udp_connection",
"(",
"self",
",",
"bridge_name",
",",
"source_nio",
",",
"destination_nio",
")",
":",
"yield",
"from",
"self",
".",
"_ubridge_send",
"(",
"\"bridge create {name}\"",
".",
"format",
"(",
"name",
"=",
"bridge_name",
")",
")",
"... | Creates an UDP connection in uBridge.
:param bridge_name: bridge name in uBridge
:param source_nio: source NIO instance
:param destination_nio: destination NIO instance | [
"Creates",
"an",
"UDP",
"connection",
"in",
"uBridge",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L556-L585 |
226,527 | GNS3/gns3-server | gns3server/compute/base_node.py | BaseNode._ubridge_apply_filters | def _ubridge_apply_filters(self, bridge_name, filters):
"""
Apply packet filters
:param bridge_name: bridge name in uBridge
:param filters: Array of filter dictionary
"""
yield from self._ubridge_send('bridge reset_packet_filters ' + bridge_name)
for packet_filter in self._build_filter_list(filters):
cmd = 'bridge add_packet_filter {} {}'.format(bridge_name, packet_filter)
try:
yield from self._ubridge_send(cmd)
except UbridgeError as e:
match = re.search("Cannot compile filter '(.*)': syntax error", str(e))
if match:
message = "Warning: ignoring BPF packet filter '{}' due to syntax error".format(self.name, match.group(1))
log.warning(message)
self.project.emit("log.warning", {"message": message})
else:
raise | python | def _ubridge_apply_filters(self, bridge_name, filters):
"""
Apply packet filters
:param bridge_name: bridge name in uBridge
:param filters: Array of filter dictionary
"""
yield from self._ubridge_send('bridge reset_packet_filters ' + bridge_name)
for packet_filter in self._build_filter_list(filters):
cmd = 'bridge add_packet_filter {} {}'.format(bridge_name, packet_filter)
try:
yield from self._ubridge_send(cmd)
except UbridgeError as e:
match = re.search("Cannot compile filter '(.*)': syntax error", str(e))
if match:
message = "Warning: ignoring BPF packet filter '{}' due to syntax error".format(self.name, match.group(1))
log.warning(message)
self.project.emit("log.warning", {"message": message})
else:
raise | [
"def",
"_ubridge_apply_filters",
"(",
"self",
",",
"bridge_name",
",",
"filters",
")",
":",
"yield",
"from",
"self",
".",
"_ubridge_send",
"(",
"'bridge reset_packet_filters '",
"+",
"bridge_name",
")",
"for",
"packet_filter",
"in",
"self",
".",
"_build_filter_list"... | Apply packet filters
:param bridge_name: bridge name in uBridge
:param filters: Array of filter dictionary | [
"Apply",
"packet",
"filters"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L600-L619 |
226,528 | GNS3/gns3-server | gns3server/compute/base_node.py | BaseNode._add_ubridge_ethernet_connection | def _add_ubridge_ethernet_connection(self, bridge_name, ethernet_interface, block_host_traffic=False):
"""
Creates a connection with an Ethernet interface in uBridge.
:param bridge_name: bridge name in uBridge
:param ethernet_interface: Ethernet interface name
:param block_host_traffic: block network traffic originating from the host OS (Windows only)
"""
if sys.platform.startswith("linux") and block_host_traffic is False:
# on Linux we use RAW sockets by default excepting if host traffic must be blocked
yield from self._ubridge_send('bridge add_nio_linux_raw {name} "{interface}"'.format(name=bridge_name, interface=ethernet_interface))
elif sys.platform.startswith("win"):
# on Windows we use Winpcap/Npcap
windows_interfaces = interfaces()
npf_id = None
source_mac = None
for interface in windows_interfaces:
# Winpcap/Npcap uses a NPF ID to identify an interface on Windows
if "netcard" in interface and ethernet_interface in interface["netcard"]:
npf_id = interface["id"]
source_mac = interface["mac_address"]
elif ethernet_interface in interface["name"]:
npf_id = interface["id"]
source_mac = interface["mac_address"]
if npf_id:
yield from self._ubridge_send('bridge add_nio_ethernet {name} "{interface}"'.format(name=bridge_name,
interface=npf_id))
else:
raise NodeError("Could not find NPF id for interface {}".format(ethernet_interface))
if block_host_traffic:
if source_mac:
yield from self._ubridge_send('bridge set_pcap_filter {name} "not ether src {mac}"'.format(name=bridge_name, mac=source_mac))
log.info('PCAP filter applied on "{interface}" for source MAC {mac}'.format(interface=ethernet_interface, mac=source_mac))
else:
log.warning("Could not block host network traffic on {} (no MAC address found)".format(ethernet_interface))
else:
# on other platforms we just rely on the pcap library
yield from self._ubridge_send('bridge add_nio_ethernet {name} "{interface}"'.format(name=bridge_name, interface=ethernet_interface))
source_mac = None
for interface in interfaces():
if interface["name"] == ethernet_interface:
source_mac = interface["mac_address"]
if source_mac:
yield from self._ubridge_send('bridge set_pcap_filter {name} "not ether src {mac}"'.format(name=bridge_name, mac=source_mac))
log.info('PCAP filter applied on "{interface}" for source MAC {mac}'.format(interface=ethernet_interface, mac=source_mac)) | python | def _add_ubridge_ethernet_connection(self, bridge_name, ethernet_interface, block_host_traffic=False):
"""
Creates a connection with an Ethernet interface in uBridge.
:param bridge_name: bridge name in uBridge
:param ethernet_interface: Ethernet interface name
:param block_host_traffic: block network traffic originating from the host OS (Windows only)
"""
if sys.platform.startswith("linux") and block_host_traffic is False:
# on Linux we use RAW sockets by default excepting if host traffic must be blocked
yield from self._ubridge_send('bridge add_nio_linux_raw {name} "{interface}"'.format(name=bridge_name, interface=ethernet_interface))
elif sys.platform.startswith("win"):
# on Windows we use Winpcap/Npcap
windows_interfaces = interfaces()
npf_id = None
source_mac = None
for interface in windows_interfaces:
# Winpcap/Npcap uses a NPF ID to identify an interface on Windows
if "netcard" in interface and ethernet_interface in interface["netcard"]:
npf_id = interface["id"]
source_mac = interface["mac_address"]
elif ethernet_interface in interface["name"]:
npf_id = interface["id"]
source_mac = interface["mac_address"]
if npf_id:
yield from self._ubridge_send('bridge add_nio_ethernet {name} "{interface}"'.format(name=bridge_name,
interface=npf_id))
else:
raise NodeError("Could not find NPF id for interface {}".format(ethernet_interface))
if block_host_traffic:
if source_mac:
yield from self._ubridge_send('bridge set_pcap_filter {name} "not ether src {mac}"'.format(name=bridge_name, mac=source_mac))
log.info('PCAP filter applied on "{interface}" for source MAC {mac}'.format(interface=ethernet_interface, mac=source_mac))
else:
log.warning("Could not block host network traffic on {} (no MAC address found)".format(ethernet_interface))
else:
# on other platforms we just rely on the pcap library
yield from self._ubridge_send('bridge add_nio_ethernet {name} "{interface}"'.format(name=bridge_name, interface=ethernet_interface))
source_mac = None
for interface in interfaces():
if interface["name"] == ethernet_interface:
source_mac = interface["mac_address"]
if source_mac:
yield from self._ubridge_send('bridge set_pcap_filter {name} "not ether src {mac}"'.format(name=bridge_name, mac=source_mac))
log.info('PCAP filter applied on "{interface}" for source MAC {mac}'.format(interface=ethernet_interface, mac=source_mac)) | [
"def",
"_add_ubridge_ethernet_connection",
"(",
"self",
",",
"bridge_name",
",",
"ethernet_interface",
",",
"block_host_traffic",
"=",
"False",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"linux\"",
")",
"and",
"block_host_traffic",
"is",
"Fa... | Creates a connection with an Ethernet interface in uBridge.
:param bridge_name: bridge name in uBridge
:param ethernet_interface: Ethernet interface name
:param block_host_traffic: block network traffic originating from the host OS (Windows only) | [
"Creates",
"a",
"connection",
"with",
"an",
"Ethernet",
"interface",
"in",
"uBridge",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L643-L689 |
226,529 | GNS3/gns3-server | gns3server/compute/base_node.py | BaseNode.check_available_ram | def check_available_ram(self, requested_ram):
"""
Sends a warning notification if there is not enough RAM on the system to allocate requested RAM.
:param requested_ram: requested amount of RAM in MB
"""
available_ram = int(psutil.virtual_memory().available / (1024 * 1024))
percentage_left = psutil.virtual_memory().percent
if requested_ram > available_ram:
message = '"{}" requires {}MB of RAM to run but there is only {}MB - {}% of RAM left on "{}"'.format(self.name,
requested_ram,
available_ram,
percentage_left,
platform.node())
self.project.emit("log.warning", {"message": message}) | python | def check_available_ram(self, requested_ram):
"""
Sends a warning notification if there is not enough RAM on the system to allocate requested RAM.
:param requested_ram: requested amount of RAM in MB
"""
available_ram = int(psutil.virtual_memory().available / (1024 * 1024))
percentage_left = psutil.virtual_memory().percent
if requested_ram > available_ram:
message = '"{}" requires {}MB of RAM to run but there is only {}MB - {}% of RAM left on "{}"'.format(self.name,
requested_ram,
available_ram,
percentage_left,
platform.node())
self.project.emit("log.warning", {"message": message}) | [
"def",
"check_available_ram",
"(",
"self",
",",
"requested_ram",
")",
":",
"available_ram",
"=",
"int",
"(",
"psutil",
".",
"virtual_memory",
"(",
")",
".",
"available",
"/",
"(",
"1024",
"*",
"1024",
")",
")",
"percentage_left",
"=",
"psutil",
".",
"virtu... | Sends a warning notification if there is not enough RAM on the system to allocate requested RAM.
:param requested_ram: requested amount of RAM in MB | [
"Sends",
"a",
"warning",
"notification",
"if",
"there",
"is",
"not",
"enough",
"RAM",
"on",
"the",
"system",
"to",
"allocate",
"requested",
"RAM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L722-L737 |
226,530 | GNS3/gns3-server | gns3server/compute/qemu/qcow2.py | Qcow2.backing_file | def backing_file(self):
"""
When using linked clone this will return the path to the base image
:returns: None if it's not a linked clone, the path otherwise
"""
with open(self._path, 'rb') as f:
f.seek(self.backing_file_offset)
content = f.read(self.backing_file_size)
path = content.decode()
if len(path) == 0:
return None
return path | python | def backing_file(self):
"""
When using linked clone this will return the path to the base image
:returns: None if it's not a linked clone, the path otherwise
"""
with open(self._path, 'rb') as f:
f.seek(self.backing_file_offset)
content = f.read(self.backing_file_size)
path = content.decode()
if len(path) == 0:
return None
return path | [
"def",
"backing_file",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"_path",
",",
"'rb'",
")",
"as",
"f",
":",
"f",
".",
"seek",
"(",
"self",
".",
"backing_file_offset",
")",
"content",
"=",
"f",
".",
"read",
"(",
"self",
".",
"backing_... | When using linked clone this will return the path to the base image
:returns: None if it's not a linked clone, the path otherwise | [
"When",
"using",
"linked",
"clone",
"this",
"will",
"return",
"the",
"path",
"to",
"the",
"base",
"image"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qcow2.py#L74-L88 |
226,531 | GNS3/gns3-server | gns3server/compute/qemu/qcow2.py | Qcow2.rebase | def rebase(self, qemu_img, base_image):
"""
Rebase a linked clone in order to use the correct disk
:param qemu_img: Path to the qemu-img binary
:param base_image: Path to the base image
"""
if not os.path.exists(base_image):
raise FileNotFoundError(base_image)
command = [qemu_img, "rebase", "-u", "-b", base_image, self._path]
process = yield from asyncio.create_subprocess_exec(*command)
retcode = yield from process.wait()
if retcode != 0:
raise Qcow2Error("Could not rebase the image")
self._reload() | python | def rebase(self, qemu_img, base_image):
"""
Rebase a linked clone in order to use the correct disk
:param qemu_img: Path to the qemu-img binary
:param base_image: Path to the base image
"""
if not os.path.exists(base_image):
raise FileNotFoundError(base_image)
command = [qemu_img, "rebase", "-u", "-b", base_image, self._path]
process = yield from asyncio.create_subprocess_exec(*command)
retcode = yield from process.wait()
if retcode != 0:
raise Qcow2Error("Could not rebase the image")
self._reload() | [
"def",
"rebase",
"(",
"self",
",",
"qemu_img",
",",
"base_image",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"base_image",
")",
":",
"raise",
"FileNotFoundError",
"(",
"base_image",
")",
"command",
"=",
"[",
"qemu_img",
",",
"\"rebase\... | Rebase a linked clone in order to use the correct disk
:param qemu_img: Path to the qemu-img binary
:param base_image: Path to the base image | [
"Rebase",
"a",
"linked",
"clone",
"in",
"order",
"to",
"use",
"the",
"correct",
"disk"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qcow2.py#L91-L106 |
226,532 | GNS3/gns3-server | gns3server/utils/qt.py | qt_font_to_style | def qt_font_to_style(font, color):
"""
Convert a Qt font to CSS style
"""
if font is None:
font = "TypeWriter,10,-1,5,75,0,0,0,0,0"
font_info = font.split(",")
style = "font-family: {};font-size: {};".format(font_info[0], font_info[1])
if font_info[4] == "75":
style += "font-weight: bold;"
if font_info[5] == "1":
style += "font-style: italic;"
if color is None:
color = "000000"
if len(color) == 9:
style += "fill: #" + color[-6:] + ";"
style += "fill-opacity: {};".format(round(1.0 / 255 * int(color[:3][-2:], base=16), 2))
else:
style += "fill: #" + color[-6:] + ";"
style += "fill-opacity: {};".format(1.0)
return style | python | def qt_font_to_style(font, color):
"""
Convert a Qt font to CSS style
"""
if font is None:
font = "TypeWriter,10,-1,5,75,0,0,0,0,0"
font_info = font.split(",")
style = "font-family: {};font-size: {};".format(font_info[0], font_info[1])
if font_info[4] == "75":
style += "font-weight: bold;"
if font_info[5] == "1":
style += "font-style: italic;"
if color is None:
color = "000000"
if len(color) == 9:
style += "fill: #" + color[-6:] + ";"
style += "fill-opacity: {};".format(round(1.0 / 255 * int(color[:3][-2:], base=16), 2))
else:
style += "fill: #" + color[-6:] + ";"
style += "fill-opacity: {};".format(1.0)
return style | [
"def",
"qt_font_to_style",
"(",
"font",
",",
"color",
")",
":",
"if",
"font",
"is",
"None",
":",
"font",
"=",
"\"TypeWriter,10,-1,5,75,0,0,0,0,0\"",
"font_info",
"=",
"font",
".",
"split",
"(",
"\",\"",
")",
"style",
"=",
"\"font-family: {};font-size: {};\"",
".... | Convert a Qt font to CSS style | [
"Convert",
"a",
"Qt",
"font",
"to",
"CSS",
"style"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/qt.py#L23-L44 |
226,533 | GNS3/gns3-server | gns3server/controller/gns3vm/remote_gns3_vm.py | RemoteGNS3VM.list | def list(self):
"""
List all VMs
"""
res = []
for compute in self._controller.computes.values():
if compute.id not in ["local", "vm"]:
res.append({"vmname": compute.name})
return res | python | def list(self):
"""
List all VMs
"""
res = []
for compute in self._controller.computes.values():
if compute.id not in ["local", "vm"]:
res.append({"vmname": compute.name})
return res | [
"def",
"list",
"(",
"self",
")",
":",
"res",
"=",
"[",
"]",
"for",
"compute",
"in",
"self",
".",
"_controller",
".",
"computes",
".",
"values",
"(",
")",
":",
"if",
"compute",
".",
"id",
"not",
"in",
"[",
"\"local\"",
",",
"\"vm\"",
"]",
":",
"re... | List all VMs | [
"List",
"all",
"VMs"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/remote_gns3_vm.py#L36-L46 |
226,534 | GNS3/gns3-server | gns3server/compute/dynamips/__init__.py | Dynamips.take_dynamips_id | def take_dynamips_id(self, project_id, dynamips_id):
"""
Reserve a dynamips id or raise an error
:param project_id: UUID of the project
:param dynamips_id: Asked id
"""
self._dynamips_ids.setdefault(project_id, set())
if dynamips_id in self._dynamips_ids[project_id]:
raise DynamipsError("Dynamips identifier {} is already used by another router".format(dynamips_id))
self._dynamips_ids[project_id].add(dynamips_id) | python | def take_dynamips_id(self, project_id, dynamips_id):
"""
Reserve a dynamips id or raise an error
:param project_id: UUID of the project
:param dynamips_id: Asked id
"""
self._dynamips_ids.setdefault(project_id, set())
if dynamips_id in self._dynamips_ids[project_id]:
raise DynamipsError("Dynamips identifier {} is already used by another router".format(dynamips_id))
self._dynamips_ids[project_id].add(dynamips_id) | [
"def",
"take_dynamips_id",
"(",
"self",
",",
"project_id",
",",
"dynamips_id",
")",
":",
"self",
".",
"_dynamips_ids",
".",
"setdefault",
"(",
"project_id",
",",
"set",
"(",
")",
")",
"if",
"dynamips_id",
"in",
"self",
".",
"_dynamips_ids",
"[",
"project_id"... | Reserve a dynamips id or raise an error
:param project_id: UUID of the project
:param dynamips_id: Asked id | [
"Reserve",
"a",
"dynamips",
"id",
"or",
"raise",
"an",
"error"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/__init__.py#L145-L155 |
226,535 | GNS3/gns3-server | gns3server/compute/dynamips/__init__.py | Dynamips.release_dynamips_id | def release_dynamips_id(self, project_id, dynamips_id):
"""
A Dynamips id can be reused by another VM
:param project_id: UUID of the project
:param dynamips_id: Asked id
"""
self._dynamips_ids.setdefault(project_id, set())
if dynamips_id in self._dynamips_ids[project_id]:
self._dynamips_ids[project_id].remove(dynamips_id) | python | def release_dynamips_id(self, project_id, dynamips_id):
"""
A Dynamips id can be reused by another VM
:param project_id: UUID of the project
:param dynamips_id: Asked id
"""
self._dynamips_ids.setdefault(project_id, set())
if dynamips_id in self._dynamips_ids[project_id]:
self._dynamips_ids[project_id].remove(dynamips_id) | [
"def",
"release_dynamips_id",
"(",
"self",
",",
"project_id",
",",
"dynamips_id",
")",
":",
"self",
".",
"_dynamips_ids",
".",
"setdefault",
"(",
"project_id",
",",
"set",
"(",
")",
")",
"if",
"dynamips_id",
"in",
"self",
".",
"_dynamips_ids",
"[",
"project_... | A Dynamips id can be reused by another VM
:param project_id: UUID of the project
:param dynamips_id: Asked id | [
"A",
"Dynamips",
"id",
"can",
"be",
"reused",
"by",
"another",
"VM"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/__init__.py#L157-L166 |
226,536 | GNS3/gns3-server | gns3server/compute/dynamips/__init__.py | Dynamips.project_closing | def project_closing(self, project):
"""
Called when a project is about to be closed.
:param project: Project instance
"""
yield from super().project_closing(project)
# delete the Dynamips devices corresponding to the project
tasks = []
for device in self._devices.values():
if device.project.id == project.id:
tasks.append(asyncio.async(device.delete()))
if tasks:
done, _ = yield from asyncio.wait(tasks)
for future in done:
try:
future.result()
except (Exception, GeneratorExit) as e:
log.error("Could not delete device {}".format(e), exc_info=1) | python | def project_closing(self, project):
"""
Called when a project is about to be closed.
:param project: Project instance
"""
yield from super().project_closing(project)
# delete the Dynamips devices corresponding to the project
tasks = []
for device in self._devices.values():
if device.project.id == project.id:
tasks.append(asyncio.async(device.delete()))
if tasks:
done, _ = yield from asyncio.wait(tasks)
for future in done:
try:
future.result()
except (Exception, GeneratorExit) as e:
log.error("Could not delete device {}".format(e), exc_info=1) | [
"def",
"project_closing",
"(",
"self",
",",
"project",
")",
":",
"yield",
"from",
"super",
"(",
")",
".",
"project_closing",
"(",
"project",
")",
"# delete the Dynamips devices corresponding to the project",
"tasks",
"=",
"[",
"]",
"for",
"device",
"in",
"self",
... | Called when a project is about to be closed.
:param project: Project instance | [
"Called",
"when",
"a",
"project",
"is",
"about",
"to",
"be",
"closed",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/__init__.py#L187-L207 |
226,537 | GNS3/gns3-server | gns3server/compute/dynamips/__init__.py | Dynamips.start_new_hypervisor | def start_new_hypervisor(self, working_dir=None):
"""
Creates a new Dynamips process and start it.
:param working_dir: working directory
:returns: the new hypervisor instance
"""
if not self._dynamips_path:
self.find_dynamips()
if not working_dir:
working_dir = tempfile.gettempdir()
# FIXME: hypervisor should always listen to 127.0.0.1
# See https://github.com/GNS3/dynamips/issues/62
server_config = self.config.get_section_config("Server")
server_host = server_config.get("host")
try:
info = socket.getaddrinfo(server_host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
if not info:
raise DynamipsError("getaddrinfo returns an empty list on {}".format(server_host))
for res in info:
af, socktype, proto, _, sa = res
# let the OS find an unused port for the Dynamips hypervisor
with socket.socket(af, socktype, proto) as sock:
sock.bind(sa)
port = sock.getsockname()[1]
break
except OSError as e:
raise DynamipsError("Could not find free port for the Dynamips hypervisor: {}".format(e))
port_manager = PortManager.instance()
hypervisor = Hypervisor(self._dynamips_path, working_dir, server_host, port, port_manager.console_host)
log.info("Creating new hypervisor {}:{} with working directory {}".format(hypervisor.host, hypervisor.port, working_dir))
yield from hypervisor.start()
log.info("Hypervisor {}:{} has successfully started".format(hypervisor.host, hypervisor.port))
yield from hypervisor.connect()
if parse_version(hypervisor.version) < parse_version('0.2.11'):
raise DynamipsError("Dynamips version must be >= 0.2.11, detected version is {}".format(hypervisor.version))
return hypervisor | python | def start_new_hypervisor(self, working_dir=None):
"""
Creates a new Dynamips process and start it.
:param working_dir: working directory
:returns: the new hypervisor instance
"""
if not self._dynamips_path:
self.find_dynamips()
if not working_dir:
working_dir = tempfile.gettempdir()
# FIXME: hypervisor should always listen to 127.0.0.1
# See https://github.com/GNS3/dynamips/issues/62
server_config = self.config.get_section_config("Server")
server_host = server_config.get("host")
try:
info = socket.getaddrinfo(server_host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
if not info:
raise DynamipsError("getaddrinfo returns an empty list on {}".format(server_host))
for res in info:
af, socktype, proto, _, sa = res
# let the OS find an unused port for the Dynamips hypervisor
with socket.socket(af, socktype, proto) as sock:
sock.bind(sa)
port = sock.getsockname()[1]
break
except OSError as e:
raise DynamipsError("Could not find free port for the Dynamips hypervisor: {}".format(e))
port_manager = PortManager.instance()
hypervisor = Hypervisor(self._dynamips_path, working_dir, server_host, port, port_manager.console_host)
log.info("Creating new hypervisor {}:{} with working directory {}".format(hypervisor.host, hypervisor.port, working_dir))
yield from hypervisor.start()
log.info("Hypervisor {}:{} has successfully started".format(hypervisor.host, hypervisor.port))
yield from hypervisor.connect()
if parse_version(hypervisor.version) < parse_version('0.2.11'):
raise DynamipsError("Dynamips version must be >= 0.2.11, detected version is {}".format(hypervisor.version))
return hypervisor | [
"def",
"start_new_hypervisor",
"(",
"self",
",",
"working_dir",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_dynamips_path",
":",
"self",
".",
"find_dynamips",
"(",
")",
"if",
"not",
"working_dir",
":",
"working_dir",
"=",
"tempfile",
".",
"gettempdir"... | Creates a new Dynamips process and start it.
:param working_dir: working directory
:returns: the new hypervisor instance | [
"Creates",
"a",
"new",
"Dynamips",
"process",
"and",
"start",
"it",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/__init__.py#L270-L314 |
226,538 | GNS3/gns3-server | gns3server/compute/dynamips/__init__.py | Dynamips._set_ghost_ios | def _set_ghost_ios(self, vm):
"""
Manages Ghost IOS support.
:param vm: VM instance
"""
if not vm.mmap:
raise DynamipsError("mmap support is required to enable ghost IOS support")
if vm.platform == "c7200" and vm.npe == "npe-g2":
log.warning("Ghost IOS is not supported for c7200 with NPE-G2")
return
ghost_file = vm.formatted_ghost_file()
module_workdir = vm.project.module_working_directory(self.module_name.lower())
ghost_file_path = os.path.join(module_workdir, ghost_file)
if ghost_file_path not in self._ghost_files:
# create a new ghost IOS instance
ghost_id = str(uuid4())
ghost = Router("ghost-" + ghost_file, ghost_id, vm.project, vm.manager, platform=vm.platform, hypervisor=vm.hypervisor, ghost_flag=True)
try:
yield from ghost.create()
yield from ghost.set_image(vm.image)
yield from ghost.set_ghost_status(1)
yield from ghost.set_ghost_file(ghost_file_path)
yield from ghost.set_ram(vm.ram)
try:
yield from ghost.start()
yield from ghost.stop()
self._ghost_files.add(ghost_file_path)
except DynamipsError:
raise
finally:
yield from ghost.clean_delete()
except DynamipsError as e:
log.warn("Could not create ghost instance: {}".format(e))
if vm.ghost_file != ghost_file and os.path.isfile(ghost_file_path):
# set the ghost file to the router
yield from vm.set_ghost_status(2)
yield from vm.set_ghost_file(ghost_file_path) | python | def _set_ghost_ios(self, vm):
"""
Manages Ghost IOS support.
:param vm: VM instance
"""
if not vm.mmap:
raise DynamipsError("mmap support is required to enable ghost IOS support")
if vm.platform == "c7200" and vm.npe == "npe-g2":
log.warning("Ghost IOS is not supported for c7200 with NPE-G2")
return
ghost_file = vm.formatted_ghost_file()
module_workdir = vm.project.module_working_directory(self.module_name.lower())
ghost_file_path = os.path.join(module_workdir, ghost_file)
if ghost_file_path not in self._ghost_files:
# create a new ghost IOS instance
ghost_id = str(uuid4())
ghost = Router("ghost-" + ghost_file, ghost_id, vm.project, vm.manager, platform=vm.platform, hypervisor=vm.hypervisor, ghost_flag=True)
try:
yield from ghost.create()
yield from ghost.set_image(vm.image)
yield from ghost.set_ghost_status(1)
yield from ghost.set_ghost_file(ghost_file_path)
yield from ghost.set_ram(vm.ram)
try:
yield from ghost.start()
yield from ghost.stop()
self._ghost_files.add(ghost_file_path)
except DynamipsError:
raise
finally:
yield from ghost.clean_delete()
except DynamipsError as e:
log.warn("Could not create ghost instance: {}".format(e))
if vm.ghost_file != ghost_file and os.path.isfile(ghost_file_path):
# set the ghost file to the router
yield from vm.set_ghost_status(2)
yield from vm.set_ghost_file(ghost_file_path) | [
"def",
"_set_ghost_ios",
"(",
"self",
",",
"vm",
")",
":",
"if",
"not",
"vm",
".",
"mmap",
":",
"raise",
"DynamipsError",
"(",
"\"mmap support is required to enable ghost IOS support\"",
")",
"if",
"vm",
".",
"platform",
"==",
"\"c7200\"",
"and",
"vm",
".",
"n... | Manages Ghost IOS support.
:param vm: VM instance | [
"Manages",
"Ghost",
"IOS",
"support",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/__init__.py#L398-L440 |
226,539 | GNS3/gns3-server | gns3server/compute/dynamips/__init__.py | Dynamips.set_vm_configs | def set_vm_configs(self, vm, settings):
"""
Set VM configs from pushed content or existing config files.
:param vm: VM instance
:param settings: VM settings
"""
startup_config_content = settings.get("startup_config_content")
if startup_config_content:
self._create_config(vm, vm.startup_config_path, startup_config_content)
private_config_content = settings.get("private_config_content")
if private_config_content:
self._create_config(vm, vm.private_config_path, private_config_content) | python | def set_vm_configs(self, vm, settings):
"""
Set VM configs from pushed content or existing config files.
:param vm: VM instance
:param settings: VM settings
"""
startup_config_content = settings.get("startup_config_content")
if startup_config_content:
self._create_config(vm, vm.startup_config_path, startup_config_content)
private_config_content = settings.get("private_config_content")
if private_config_content:
self._create_config(vm, vm.private_config_path, private_config_content) | [
"def",
"set_vm_configs",
"(",
"self",
",",
"vm",
",",
"settings",
")",
":",
"startup_config_content",
"=",
"settings",
".",
"get",
"(",
"\"startup_config_content\"",
")",
"if",
"startup_config_content",
":",
"self",
".",
"_create_config",
"(",
"vm",
",",
"vm",
... | Set VM configs from pushed content or existing config files.
:param vm: VM instance
:param settings: VM settings | [
"Set",
"VM",
"configs",
"from",
"pushed",
"content",
"or",
"existing",
"config",
"files",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/__init__.py#L505-L518 |
226,540 | GNS3/gns3-server | gns3server/compute/dynamips/__init__.py | Dynamips.auto_idlepc | def auto_idlepc(self, vm):
"""
Try to find the best possible idle-pc value.
:param vm: VM instance
"""
yield from vm.set_idlepc("0x0")
was_auto_started = False
try:
status = yield from vm.get_status()
if status != "running":
yield from vm.start()
was_auto_started = True
yield from asyncio.sleep(20) # leave time to the router to boot
validated_idlepc = None
idlepcs = yield from vm.get_idle_pc_prop()
if not idlepcs:
raise DynamipsError("No Idle-PC values found")
for idlepc in idlepcs:
match = re.search(r"^0x[0-9a-f]{8}$", idlepc.split()[0])
if not match:
continue
yield from vm.set_idlepc(idlepc.split()[0])
log.debug("Auto Idle-PC: trying idle-PC value {}".format(vm.idlepc))
start_time = time.time()
initial_cpu_usage = yield from vm.get_cpu_usage()
log.debug("Auto Idle-PC: initial CPU usage is {}%".format(initial_cpu_usage))
yield from asyncio.sleep(3) # wait 3 seconds to probe the cpu again
elapsed_time = time.time() - start_time
cpu_usage = yield from vm.get_cpu_usage()
cpu_elapsed_usage = cpu_usage - initial_cpu_usage
cpu_usage = abs(cpu_elapsed_usage * 100.0 / elapsed_time)
if cpu_usage > 100:
cpu_usage = 100
log.debug("Auto Idle-PC: CPU usage is {}% after {:.2} seconds".format(cpu_usage, elapsed_time))
if cpu_usage < 70:
validated_idlepc = vm.idlepc
log.debug("Auto Idle-PC: idle-PC value {} has been validated".format(validated_idlepc))
break
if validated_idlepc is None:
raise DynamipsError("Sorry, no idle-pc value was suitable")
except DynamipsError:
raise
finally:
if was_auto_started:
yield from vm.stop()
return validated_idlepc | python | def auto_idlepc(self, vm):
"""
Try to find the best possible idle-pc value.
:param vm: VM instance
"""
yield from vm.set_idlepc("0x0")
was_auto_started = False
try:
status = yield from vm.get_status()
if status != "running":
yield from vm.start()
was_auto_started = True
yield from asyncio.sleep(20) # leave time to the router to boot
validated_idlepc = None
idlepcs = yield from vm.get_idle_pc_prop()
if not idlepcs:
raise DynamipsError("No Idle-PC values found")
for idlepc in idlepcs:
match = re.search(r"^0x[0-9a-f]{8}$", idlepc.split()[0])
if not match:
continue
yield from vm.set_idlepc(idlepc.split()[0])
log.debug("Auto Idle-PC: trying idle-PC value {}".format(vm.idlepc))
start_time = time.time()
initial_cpu_usage = yield from vm.get_cpu_usage()
log.debug("Auto Idle-PC: initial CPU usage is {}%".format(initial_cpu_usage))
yield from asyncio.sleep(3) # wait 3 seconds to probe the cpu again
elapsed_time = time.time() - start_time
cpu_usage = yield from vm.get_cpu_usage()
cpu_elapsed_usage = cpu_usage - initial_cpu_usage
cpu_usage = abs(cpu_elapsed_usage * 100.0 / elapsed_time)
if cpu_usage > 100:
cpu_usage = 100
log.debug("Auto Idle-PC: CPU usage is {}% after {:.2} seconds".format(cpu_usage, elapsed_time))
if cpu_usage < 70:
validated_idlepc = vm.idlepc
log.debug("Auto Idle-PC: idle-PC value {} has been validated".format(validated_idlepc))
break
if validated_idlepc is None:
raise DynamipsError("Sorry, no idle-pc value was suitable")
except DynamipsError:
raise
finally:
if was_auto_started:
yield from vm.stop()
return validated_idlepc | [
"def",
"auto_idlepc",
"(",
"self",
",",
"vm",
")",
":",
"yield",
"from",
"vm",
".",
"set_idlepc",
"(",
"\"0x0\"",
")",
"was_auto_started",
"=",
"False",
"try",
":",
"status",
"=",
"yield",
"from",
"vm",
".",
"get_status",
"(",
")",
"if",
"status",
"!="... | Try to find the best possible idle-pc value.
:param vm: VM instance | [
"Try",
"to",
"find",
"the",
"best",
"possible",
"idle",
"-",
"pc",
"value",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/__init__.py#L555-L605 |
226,541 | GNS3/gns3-server | gns3server/web/documentation.py | Documentation.write_documentation | def write_documentation(self, doc_type):
"""
Build all the doc page for handlers
:param doc_type: Type of doc to generate (controller, compute)
"""
for handler_name in sorted(self._documentation):
if "controller." in handler_name:
server_type = "controller"
elif "compute" in handler_name:
server_type = "compute"
else:
server_type = "root"
if doc_type != server_type:
continue
print("Build {}".format(handler_name))
for path in sorted(self._documentation[handler_name]):
api_version = self._documentation[handler_name][path]["api_version"]
if api_version is None:
continue
filename = self._file_path(path)
handler_doc = self._documentation[handler_name][path]
handler = handler_name.replace(server_type + ".", "")
self._create_handler_directory(handler, api_version, server_type)
with open("{}/api/v{}/{}/{}/{}.rst".format(self._directory, api_version, server_type, handler, filename), 'w+') as f:
f.write('{}\n------------------------------------------------------------------------------------------------------------------------------------------\n\n'.format(path))
f.write('.. contents::\n')
for method in handler_doc["methods"]:
f.write('\n{} {}\n'.format(method["method"], path.replace("{", '**{').replace("}", "}**")))
f.write('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n')
f.write('{}\n\n'.format(method["description"]))
if len(method["parameters"]) > 0:
f.write("Parameters\n**********\n")
for parameter in method["parameters"]:
desc = method["parameters"][parameter]
f.write("- **{}**: {}\n".format(parameter, desc))
f.write("\n")
f.write("Response status codes\n**********************\n")
for code in method["status_codes"]:
desc = method["status_codes"][code]
f.write("- **{}**: {}\n".format(code, desc))
f.write("\n")
if "properties" in method["input_schema"]:
f.write("Input\n*******\n")
self._write_definitions(f, method["input_schema"])
self._write_json_schema(f, method["input_schema"])
if "properties" in method["output_schema"]:
f.write("Output\n*******\n")
self._write_json_schema(f, method["output_schema"])
self._include_query_example(f, method, path, api_version, server_type) | python | def write_documentation(self, doc_type):
"""
Build all the doc page for handlers
:param doc_type: Type of doc to generate (controller, compute)
"""
for handler_name in sorted(self._documentation):
if "controller." in handler_name:
server_type = "controller"
elif "compute" in handler_name:
server_type = "compute"
else:
server_type = "root"
if doc_type != server_type:
continue
print("Build {}".format(handler_name))
for path in sorted(self._documentation[handler_name]):
api_version = self._documentation[handler_name][path]["api_version"]
if api_version is None:
continue
filename = self._file_path(path)
handler_doc = self._documentation[handler_name][path]
handler = handler_name.replace(server_type + ".", "")
self._create_handler_directory(handler, api_version, server_type)
with open("{}/api/v{}/{}/{}/{}.rst".format(self._directory, api_version, server_type, handler, filename), 'w+') as f:
f.write('{}\n------------------------------------------------------------------------------------------------------------------------------------------\n\n'.format(path))
f.write('.. contents::\n')
for method in handler_doc["methods"]:
f.write('\n{} {}\n'.format(method["method"], path.replace("{", '**{').replace("}", "}**")))
f.write('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n')
f.write('{}\n\n'.format(method["description"]))
if len(method["parameters"]) > 0:
f.write("Parameters\n**********\n")
for parameter in method["parameters"]:
desc = method["parameters"][parameter]
f.write("- **{}**: {}\n".format(parameter, desc))
f.write("\n")
f.write("Response status codes\n**********************\n")
for code in method["status_codes"]:
desc = method["status_codes"][code]
f.write("- **{}**: {}\n".format(code, desc))
f.write("\n")
if "properties" in method["input_schema"]:
f.write("Input\n*******\n")
self._write_definitions(f, method["input_schema"])
self._write_json_schema(f, method["input_schema"])
if "properties" in method["output_schema"]:
f.write("Output\n*******\n")
self._write_json_schema(f, method["output_schema"])
self._include_query_example(f, method, path, api_version, server_type) | [
"def",
"write_documentation",
"(",
"self",
",",
"doc_type",
")",
":",
"for",
"handler_name",
"in",
"sorted",
"(",
"self",
".",
"_documentation",
")",
":",
"if",
"\"controller.\"",
"in",
"handler_name",
":",
"server_type",
"=",
"\"controller\"",
"elif",
"\"comput... | Build all the doc page for handlers
:param doc_type: Type of doc to generate (controller, compute) | [
"Build",
"all",
"the",
"doc",
"page",
"for",
"handlers"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/web/documentation.py#L48-L108 |
226,542 | GNS3/gns3-server | gns3server/web/documentation.py | Documentation._create_handler_directory | def _create_handler_directory(self, handler_name, api_version, server_type):
"""Create a directory for the handler and add an index inside"""
directory = "{}/api/v{}/{}/{}".format(self._directory, api_version, server_type, handler_name)
os.makedirs(directory, exist_ok=True)
with open("{}/api/v{}/{}/{}.rst".format(self._directory, api_version, server_type, handler_name), "w+") as f:
f.write(handler_name.replace("api.", "").replace("_", " ", ).capitalize())
f.write("\n-----------------------------\n\n")
f.write(".. toctree::\n :glob:\n :maxdepth: 2\n\n {}/*\n".format(handler_name)) | python | def _create_handler_directory(self, handler_name, api_version, server_type):
"""Create a directory for the handler and add an index inside"""
directory = "{}/api/v{}/{}/{}".format(self._directory, api_version, server_type, handler_name)
os.makedirs(directory, exist_ok=True)
with open("{}/api/v{}/{}/{}.rst".format(self._directory, api_version, server_type, handler_name), "w+") as f:
f.write(handler_name.replace("api.", "").replace("_", " ", ).capitalize())
f.write("\n-----------------------------\n\n")
f.write(".. toctree::\n :glob:\n :maxdepth: 2\n\n {}/*\n".format(handler_name)) | [
"def",
"_create_handler_directory",
"(",
"self",
",",
"handler_name",
",",
"api_version",
",",
"server_type",
")",
":",
"directory",
"=",
"\"{}/api/v{}/{}/{}\"",
".",
"format",
"(",
"self",
".",
"_directory",
",",
"api_version",
",",
"server_type",
",",
"handler_n... | Create a directory for the handler and add an index inside | [
"Create",
"a",
"directory",
"for",
"the",
"handler",
"and",
"add",
"an",
"index",
"inside"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/web/documentation.py#L110-L119 |
226,543 | GNS3/gns3-server | gns3server/web/documentation.py | Documentation._include_query_example | def _include_query_example(self, f, method, path, api_version, server_type):
"""If a sample session is available we include it in documentation"""
m = method["method"].lower()
query_path = "{}_{}_{}.txt".format(server_type, m, self._file_path(path))
if os.path.isfile(os.path.join(self._directory, "api", "examples", query_path)):
f.write("Sample session\n***************\n")
f.write("\n\n.. literalinclude:: ../../../examples/{}\n\n".format(query_path)) | python | def _include_query_example(self, f, method, path, api_version, server_type):
"""If a sample session is available we include it in documentation"""
m = method["method"].lower()
query_path = "{}_{}_{}.txt".format(server_type, m, self._file_path(path))
if os.path.isfile(os.path.join(self._directory, "api", "examples", query_path)):
f.write("Sample session\n***************\n")
f.write("\n\n.. literalinclude:: ../../../examples/{}\n\n".format(query_path)) | [
"def",
"_include_query_example",
"(",
"self",
",",
"f",
",",
"method",
",",
"path",
",",
"api_version",
",",
"server_type",
")",
":",
"m",
"=",
"method",
"[",
"\"method\"",
"]",
".",
"lower",
"(",
")",
"query_path",
"=",
"\"{}_{}_{}.txt\"",
".",
"format",
... | If a sample session is available we include it in documentation | [
"If",
"a",
"sample",
"session",
"is",
"available",
"we",
"include",
"it",
"in",
"documentation"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/web/documentation.py#L121-L127 |
226,544 | GNS3/gns3-server | gns3server/web/documentation.py | Documentation._write_json_schema_object | def _write_json_schema_object(self, f, obj):
"""
obj is current object in JSON schema
schema is the whole schema including definitions
"""
for name in sorted(obj.get("properties", {})):
prop = obj["properties"][name]
mandatory = " "
if name in obj.get("required", []):
mandatory = "✔"
if "enum" in prop:
field_type = "enum"
prop['description'] = "Possible values: {}".format(', '.join(map(lambda a: a or "null", prop['enum'])))
else:
field_type = prop.get("type", "")
# Resolve oneOf relation to their human type.
if field_type == 'object' and 'oneOf' in prop:
field_type = ', '.join(map(lambda p: p['$ref'].split('/').pop(), prop['oneOf']))
f.write(" <tr><td>{}</td>\
<td>{}</td> \
<td>{}</td> \
<td>{}</td> \
</tr>\n".format(
name,
mandatory,
field_type,
prop.get("description", "")
)) | python | def _write_json_schema_object(self, f, obj):
"""
obj is current object in JSON schema
schema is the whole schema including definitions
"""
for name in sorted(obj.get("properties", {})):
prop = obj["properties"][name]
mandatory = " "
if name in obj.get("required", []):
mandatory = "✔"
if "enum" in prop:
field_type = "enum"
prop['description'] = "Possible values: {}".format(', '.join(map(lambda a: a or "null", prop['enum'])))
else:
field_type = prop.get("type", "")
# Resolve oneOf relation to their human type.
if field_type == 'object' and 'oneOf' in prop:
field_type = ', '.join(map(lambda p: p['$ref'].split('/').pop(), prop['oneOf']))
f.write(" <tr><td>{}</td>\
<td>{}</td> \
<td>{}</td> \
<td>{}</td> \
</tr>\n".format(
name,
mandatory,
field_type,
prop.get("description", "")
)) | [
"def",
"_write_json_schema_object",
"(",
"self",
",",
"f",
",",
"obj",
")",
":",
"for",
"name",
"in",
"sorted",
"(",
"obj",
".",
"get",
"(",
"\"properties\"",
",",
"{",
"}",
")",
")",
":",
"prop",
"=",
"obj",
"[",
"\"properties\"",
"]",
"[",
"name",
... | obj is current object in JSON schema
schema is the whole schema including definitions | [
"obj",
"is",
"current",
"object",
"in",
"JSON",
"schema",
"schema",
"is",
"the",
"whole",
"schema",
"including",
"definitions"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/web/documentation.py#L143-L173 |
226,545 | GNS3/gns3-server | gns3server/controller/compute.py | Compute._set_auth | def _set_auth(self, user, password):
"""
Set authentication parameters
"""
if user is None or len(user.strip()) == 0:
self._user = None
self._password = None
self._auth = None
else:
self._user = user.strip()
if password:
self._password = password.strip()
try:
self._auth = aiohttp.BasicAuth(self._user, self._password, "utf-8")
except ValueError as e:
log.error(str(e))
else:
self._password = None
self._auth = aiohttp.BasicAuth(self._user, "") | python | def _set_auth(self, user, password):
"""
Set authentication parameters
"""
if user is None or len(user.strip()) == 0:
self._user = None
self._password = None
self._auth = None
else:
self._user = user.strip()
if password:
self._password = password.strip()
try:
self._auth = aiohttp.BasicAuth(self._user, self._password, "utf-8")
except ValueError as e:
log.error(str(e))
else:
self._password = None
self._auth = aiohttp.BasicAuth(self._user, "") | [
"def",
"_set_auth",
"(",
"self",
",",
"user",
",",
"password",
")",
":",
"if",
"user",
"is",
"None",
"or",
"len",
"(",
"user",
".",
"strip",
"(",
")",
")",
"==",
"0",
":",
"self",
".",
"_user",
"=",
"None",
"self",
".",
"_password",
"=",
"None",
... | Set authentication parameters | [
"Set",
"authentication",
"parameters"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L120-L138 |
226,546 | GNS3/gns3-server | gns3server/controller/compute.py | Compute.interfaces | def interfaces(self):
"""
Get the list of network on compute
"""
if not self._interfaces_cache:
response = yield from self.get("/network/interfaces")
self._interfaces_cache = response.json
return self._interfaces_cache | python | def interfaces(self):
"""
Get the list of network on compute
"""
if not self._interfaces_cache:
response = yield from self.get("/network/interfaces")
self._interfaces_cache = response.json
return self._interfaces_cache | [
"def",
"interfaces",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_interfaces_cache",
":",
"response",
"=",
"yield",
"from",
"self",
".",
"get",
"(",
"\"/network/interfaces\"",
")",
"self",
".",
"_interfaces_cache",
"=",
"response",
".",
"json",
"return... | Get the list of network on compute | [
"Get",
"the",
"list",
"of",
"network",
"on",
"compute"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L141-L148 |
226,547 | GNS3/gns3-server | gns3server/controller/compute.py | Compute.stream_file | def stream_file(self, project, path):
"""
Read file of a project and stream it
:param project: A project object
:param path: The path of the file in the project
:returns: A file stream
"""
# Due to Python 3.4 limitation we can't use with and asyncio
# https://www.python.org/dev/peps/pep-0492/
# that why we wrap the answer
class StreamResponse:
def __init__(self, response):
self._response = response
def __enter__(self):
return self._response.content
def __exit__(self):
self._response.close()
url = self._getUrl("/projects/{}/stream/{}".format(project.id, path))
response = yield from self._session().request("GET", url, auth=self._auth, timeout=None)
if response.status == 404:
raise aiohttp.web.HTTPNotFound(text="{} not found on compute".format(path))
elif response.status == 403:
raise aiohttp.web.HTTPForbidden(text="forbidden to open {} on compute".format(path))
elif response.status != 200:
raise aiohttp.web.HTTPInternalServerError(text="Unexpected error {}: {}: while opening {} on compute".format(response.status,
response.reason,
path))
return StreamResponse(response) | python | def stream_file(self, project, path):
"""
Read file of a project and stream it
:param project: A project object
:param path: The path of the file in the project
:returns: A file stream
"""
# Due to Python 3.4 limitation we can't use with and asyncio
# https://www.python.org/dev/peps/pep-0492/
# that why we wrap the answer
class StreamResponse:
def __init__(self, response):
self._response = response
def __enter__(self):
return self._response.content
def __exit__(self):
self._response.close()
url = self._getUrl("/projects/{}/stream/{}".format(project.id, path))
response = yield from self._session().request("GET", url, auth=self._auth, timeout=None)
if response.status == 404:
raise aiohttp.web.HTTPNotFound(text="{} not found on compute".format(path))
elif response.status == 403:
raise aiohttp.web.HTTPForbidden(text="forbidden to open {} on compute".format(path))
elif response.status != 200:
raise aiohttp.web.HTTPInternalServerError(text="Unexpected error {}: {}: while opening {} on compute".format(response.status,
response.reason,
path))
return StreamResponse(response) | [
"def",
"stream_file",
"(",
"self",
",",
"project",
",",
"path",
")",
":",
"# Due to Python 3.4 limitation we can't use with and asyncio",
"# https://www.python.org/dev/peps/pep-0492/",
"# that why we wrap the answer",
"class",
"StreamResponse",
":",
"def",
"__init__",
"(",
"sel... | Read file of a project and stream it
:param project: A project object
:param path: The path of the file in the project
:returns: A file stream | [
"Read",
"file",
"of",
"a",
"project",
"and",
"stream",
"it"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L340-L373 |
226,548 | GNS3/gns3-server | gns3server/controller/compute.py | Compute.connect | def connect(self):
"""
Check if remote server is accessible
"""
if not self._connected and not self._closed:
try:
log.info("Connecting to compute '{}'".format(self._id))
response = yield from self._run_http_query("GET", "/capabilities")
except ComputeError as e:
# Try to reconnect after 2 seconds if server unavailable only if not during tests (otherwise we create a ressources usage bomb)
if not hasattr(sys, "_called_from_test") or not sys._called_from_test:
self._connection_failure += 1
# After 5 failure we close the project using the compute to avoid sync issues
if self._connection_failure == 5:
log.warning("Cannot connect to compute '{}': {}".format(self._id, e))
yield from self._controller.close_compute_projects(self)
asyncio.get_event_loop().call_later(2, lambda: asyncio.async(self._try_reconnect()))
return
except aiohttp.web.HTTPNotFound:
raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server or it's a 1.X server".format(self._id))
except aiohttp.web.HTTPUnauthorized:
raise aiohttp.web.HTTPConflict(text="Invalid auth for server {}".format(self._id))
except aiohttp.web.HTTPServiceUnavailable:
raise aiohttp.web.HTTPConflict(text="The server {} is unavailable".format(self._id))
except ValueError:
raise aiohttp.web.HTTPConflict(text="Invalid server url for server {}".format(self._id))
if "version" not in response.json:
self._http_session.close()
raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server".format(self._id))
self._capabilities = response.json
if parse_version(__version__)[:2] != parse_version(response.json["version"])[:2]:
self._http_session.close()
raise aiohttp.web.HTTPConflict(text="The server {} versions are not compatible {} != {}".format(self._id, __version__, response.json["version"]))
self._notifications = asyncio.gather(self._connect_notification())
self._connected = True
self._connection_failure = 0
self._controller.notification.emit("compute.updated", self.__json__()) | python | def connect(self):
"""
Check if remote server is accessible
"""
if not self._connected and not self._closed:
try:
log.info("Connecting to compute '{}'".format(self._id))
response = yield from self._run_http_query("GET", "/capabilities")
except ComputeError as e:
# Try to reconnect after 2 seconds if server unavailable only if not during tests (otherwise we create a ressources usage bomb)
if not hasattr(sys, "_called_from_test") or not sys._called_from_test:
self._connection_failure += 1
# After 5 failure we close the project using the compute to avoid sync issues
if self._connection_failure == 5:
log.warning("Cannot connect to compute '{}': {}".format(self._id, e))
yield from self._controller.close_compute_projects(self)
asyncio.get_event_loop().call_later(2, lambda: asyncio.async(self._try_reconnect()))
return
except aiohttp.web.HTTPNotFound:
raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server or it's a 1.X server".format(self._id))
except aiohttp.web.HTTPUnauthorized:
raise aiohttp.web.HTTPConflict(text="Invalid auth for server {}".format(self._id))
except aiohttp.web.HTTPServiceUnavailable:
raise aiohttp.web.HTTPConflict(text="The server {} is unavailable".format(self._id))
except ValueError:
raise aiohttp.web.HTTPConflict(text="Invalid server url for server {}".format(self._id))
if "version" not in response.json:
self._http_session.close()
raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server".format(self._id))
self._capabilities = response.json
if parse_version(__version__)[:2] != parse_version(response.json["version"])[:2]:
self._http_session.close()
raise aiohttp.web.HTTPConflict(text="The server {} versions are not compatible {} != {}".format(self._id, __version__, response.json["version"]))
self._notifications = asyncio.gather(self._connect_notification())
self._connected = True
self._connection_failure = 0
self._controller.notification.emit("compute.updated", self.__json__()) | [
"def",
"connect",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_connected",
"and",
"not",
"self",
".",
"_closed",
":",
"try",
":",
"log",
".",
"info",
"(",
"\"Connecting to compute '{}'\"",
".",
"format",
"(",
"self",
".",
"_id",
")",
")",
"respon... | Check if remote server is accessible | [
"Check",
"if",
"remote",
"server",
"is",
"accessible"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L401-L440 |
226,549 | GNS3/gns3-server | gns3server/controller/compute.py | Compute._connect_notification | def _connect_notification(self):
"""
Connect to the notification stream
"""
try:
self._ws = yield from self._session().ws_connect(self._getUrl("/notifications/ws"), auth=self._auth)
except (aiohttp.WSServerHandshakeError, aiohttp.ClientResponseError):
self._ws = None
while self._ws is not None:
try:
response = yield from self._ws.receive()
except aiohttp.WSServerHandshakeError:
self._ws = None
break
if response.tp == aiohttp.WSMsgType.closed or response.tp == aiohttp.WSMsgType.error or response.data is None:
self._connected = False
break
msg = json.loads(response.data)
action = msg.pop("action")
event = msg.pop("event")
if action == "ping":
self._cpu_usage_percent = event["cpu_usage_percent"]
self._memory_usage_percent = event["memory_usage_percent"]
self._controller.notification.emit("compute.updated", self.__json__())
else:
yield from self._controller.notification.dispatch(action, event, compute_id=self.id)
if self._ws:
yield from self._ws.close()
# Try to reconnect after 1 seconds if server unavailable only if not during tests (otherwise we create a ressources usage bomb)
if not hasattr(sys, "_called_from_test") or not sys._called_from_test:
asyncio.get_event_loop().call_later(1, lambda: asyncio.async(self.connect()))
self._ws = None
self._cpu_usage_percent = None
self._memory_usage_percent = None
self._controller.notification.emit("compute.updated", self.__json__()) | python | def _connect_notification(self):
"""
Connect to the notification stream
"""
try:
self._ws = yield from self._session().ws_connect(self._getUrl("/notifications/ws"), auth=self._auth)
except (aiohttp.WSServerHandshakeError, aiohttp.ClientResponseError):
self._ws = None
while self._ws is not None:
try:
response = yield from self._ws.receive()
except aiohttp.WSServerHandshakeError:
self._ws = None
break
if response.tp == aiohttp.WSMsgType.closed or response.tp == aiohttp.WSMsgType.error or response.data is None:
self._connected = False
break
msg = json.loads(response.data)
action = msg.pop("action")
event = msg.pop("event")
if action == "ping":
self._cpu_usage_percent = event["cpu_usage_percent"]
self._memory_usage_percent = event["memory_usage_percent"]
self._controller.notification.emit("compute.updated", self.__json__())
else:
yield from self._controller.notification.dispatch(action, event, compute_id=self.id)
if self._ws:
yield from self._ws.close()
# Try to reconnect after 1 seconds if server unavailable only if not during tests (otherwise we create a ressources usage bomb)
if not hasattr(sys, "_called_from_test") or not sys._called_from_test:
asyncio.get_event_loop().call_later(1, lambda: asyncio.async(self.connect()))
self._ws = None
self._cpu_usage_percent = None
self._memory_usage_percent = None
self._controller.notification.emit("compute.updated", self.__json__()) | [
"def",
"_connect_notification",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_ws",
"=",
"yield",
"from",
"self",
".",
"_session",
"(",
")",
".",
"ws_connect",
"(",
"self",
".",
"_getUrl",
"(",
"\"/notifications/ws\"",
")",
",",
"auth",
"=",
"self",
... | Connect to the notification stream | [
"Connect",
"to",
"the",
"notification",
"stream"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L443-L479 |
226,550 | GNS3/gns3-server | gns3server/controller/compute.py | Compute.forward | def forward(self, method, type, path, data=None):
"""
Forward a call to the emulator on compute
"""
try:
action = "/{}/{}".format(type, path)
res = yield from self.http_query(method, action, data=data, timeout=None)
except aiohttp.ServerDisconnectedError:
log.error("Connection lost to %s during %s %s", self._id, method, action)
raise aiohttp.web.HTTPGatewayTimeout()
return res.json | python | def forward(self, method, type, path, data=None):
"""
Forward a call to the emulator on compute
"""
try:
action = "/{}/{}".format(type, path)
res = yield from self.http_query(method, action, data=data, timeout=None)
except aiohttp.ServerDisconnectedError:
log.error("Connection lost to %s during %s %s", self._id, method, action)
raise aiohttp.web.HTTPGatewayTimeout()
return res.json | [
"def",
"forward",
"(",
"self",
",",
"method",
",",
"type",
",",
"path",
",",
"data",
"=",
"None",
")",
":",
"try",
":",
"action",
"=",
"\"/{}/{}\"",
".",
"format",
"(",
"type",
",",
"path",
")",
"res",
"=",
"yield",
"from",
"self",
".",
"http_query... | Forward a call to the emulator on compute | [
"Forward",
"a",
"call",
"to",
"the",
"emulator",
"on",
"compute"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L604-L614 |
226,551 | GNS3/gns3-server | gns3server/controller/compute.py | Compute.images | def images(self, type):
"""
Return the list of images available for this type on controller
and on the compute node.
"""
images = []
res = yield from self.http_query("GET", "/{}/images".format(type), timeout=None)
images = res.json
try:
if type in ["qemu", "dynamips", "iou"]:
for local_image in list_images(type):
if local_image['filename'] not in [i['filename'] for i in images]:
images.append(local_image)
images = sorted(images, key=itemgetter('filename'))
else:
images = sorted(images, key=itemgetter('image'))
except OSError as e:
raise ComputeError("Can't list images: {}".format(str(e)))
return images | python | def images(self, type):
"""
Return the list of images available for this type on controller
and on the compute node.
"""
images = []
res = yield from self.http_query("GET", "/{}/images".format(type), timeout=None)
images = res.json
try:
if type in ["qemu", "dynamips", "iou"]:
for local_image in list_images(type):
if local_image['filename'] not in [i['filename'] for i in images]:
images.append(local_image)
images = sorted(images, key=itemgetter('filename'))
else:
images = sorted(images, key=itemgetter('image'))
except OSError as e:
raise ComputeError("Can't list images: {}".format(str(e)))
return images | [
"def",
"images",
"(",
"self",
",",
"type",
")",
":",
"images",
"=",
"[",
"]",
"res",
"=",
"yield",
"from",
"self",
".",
"http_query",
"(",
"\"GET\"",
",",
"\"/{}/images\"",
".",
"format",
"(",
"type",
")",
",",
"timeout",
"=",
"None",
")",
"images",
... | Return the list of images available for this type on controller
and on the compute node. | [
"Return",
"the",
"list",
"of",
"images",
"available",
"for",
"this",
"type",
"on",
"controller",
"and",
"on",
"the",
"compute",
"node",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L617-L637 |
226,552 | GNS3/gns3-server | gns3server/controller/compute.py | Compute.list_files | def list_files(self, project):
"""
List files in the project on computes
"""
path = "/projects/{}/files".format(project.id)
res = yield from self.http_query("GET", path, timeout=120)
return res.json | python | def list_files(self, project):
"""
List files in the project on computes
"""
path = "/projects/{}/files".format(project.id)
res = yield from self.http_query("GET", path, timeout=120)
return res.json | [
"def",
"list_files",
"(",
"self",
",",
"project",
")",
":",
"path",
"=",
"\"/projects/{}/files\"",
".",
"format",
"(",
"project",
".",
"id",
")",
"res",
"=",
"yield",
"from",
"self",
".",
"http_query",
"(",
"\"GET\"",
",",
"path",
",",
"timeout",
"=",
... | List files in the project on computes | [
"List",
"files",
"in",
"the",
"project",
"on",
"computes"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L640-L646 |
226,553 | GNS3/gns3-server | gns3server/controller/compute.py | Compute.get_ip_on_same_subnet | def get_ip_on_same_subnet(self, other_compute):
"""
Try to found the best ip for communication from one compute
to another
:returns: Tuple (ip_for_this_compute, ip_for_other_compute)
"""
if other_compute == self:
return (self.host_ip, self.host_ip)
# Perhaps the user has correct network gateway, we trust him
if (self.host_ip not in ('0.0.0.0', '127.0.0.1') and other_compute.host_ip not in ('0.0.0.0', '127.0.0.1')):
return (self.host_ip, other_compute.host_ip)
this_compute_interfaces = yield from self.interfaces()
other_compute_interfaces = yield from other_compute.interfaces()
# Sort interface to put the compute host in first position
# we guess that if user specified this host it could have a reason (VMware Nat / Host only interface)
this_compute_interfaces = sorted(this_compute_interfaces, key=lambda i: i["ip_address"] != self.host_ip)
other_compute_interfaces = sorted(other_compute_interfaces, key=lambda i: i["ip_address"] != other_compute.host_ip)
for this_interface in this_compute_interfaces:
# Skip if no ip or no netmask (vbox when stopped set a null netmask)
if len(this_interface["ip_address"]) == 0 or this_interface["netmask"] is None:
continue
# Ignore 169.254 network because it's for Windows special purpose
if this_interface["ip_address"].startswith("169.254."):
continue
this_network = ipaddress.ip_network("{}/{}".format(this_interface["ip_address"], this_interface["netmask"]), strict=False)
for other_interface in other_compute_interfaces:
if len(other_interface["ip_address"]) == 0 or other_interface["netmask"] is None:
continue
# Avoid stuff like 127.0.0.1
if other_interface["ip_address"] == this_interface["ip_address"]:
continue
other_network = ipaddress.ip_network("{}/{}".format(other_interface["ip_address"], other_interface["netmask"]), strict=False)
if this_network.overlaps(other_network):
return (this_interface["ip_address"], other_interface["ip_address"])
raise ValueError("No common subnet for compute {} and {}".format(self.name, other_compute.name)) | python | def get_ip_on_same_subnet(self, other_compute):
"""
Try to found the best ip for communication from one compute
to another
:returns: Tuple (ip_for_this_compute, ip_for_other_compute)
"""
if other_compute == self:
return (self.host_ip, self.host_ip)
# Perhaps the user has correct network gateway, we trust him
if (self.host_ip not in ('0.0.0.0', '127.0.0.1') and other_compute.host_ip not in ('0.0.0.0', '127.0.0.1')):
return (self.host_ip, other_compute.host_ip)
this_compute_interfaces = yield from self.interfaces()
other_compute_interfaces = yield from other_compute.interfaces()
# Sort interface to put the compute host in first position
# we guess that if user specified this host it could have a reason (VMware Nat / Host only interface)
this_compute_interfaces = sorted(this_compute_interfaces, key=lambda i: i["ip_address"] != self.host_ip)
other_compute_interfaces = sorted(other_compute_interfaces, key=lambda i: i["ip_address"] != other_compute.host_ip)
for this_interface in this_compute_interfaces:
# Skip if no ip or no netmask (vbox when stopped set a null netmask)
if len(this_interface["ip_address"]) == 0 or this_interface["netmask"] is None:
continue
# Ignore 169.254 network because it's for Windows special purpose
if this_interface["ip_address"].startswith("169.254."):
continue
this_network = ipaddress.ip_network("{}/{}".format(this_interface["ip_address"], this_interface["netmask"]), strict=False)
for other_interface in other_compute_interfaces:
if len(other_interface["ip_address"]) == 0 or other_interface["netmask"] is None:
continue
# Avoid stuff like 127.0.0.1
if other_interface["ip_address"] == this_interface["ip_address"]:
continue
other_network = ipaddress.ip_network("{}/{}".format(other_interface["ip_address"], other_interface["netmask"]), strict=False)
if this_network.overlaps(other_network):
return (this_interface["ip_address"], other_interface["ip_address"])
raise ValueError("No common subnet for compute {} and {}".format(self.name, other_compute.name)) | [
"def",
"get_ip_on_same_subnet",
"(",
"self",
",",
"other_compute",
")",
":",
"if",
"other_compute",
"==",
"self",
":",
"return",
"(",
"self",
".",
"host_ip",
",",
"self",
".",
"host_ip",
")",
"# Perhaps the user has correct network gateway, we trust him",
"if",
"(",... | Try to found the best ip for communication from one compute
to another
:returns: Tuple (ip_for_this_compute, ip_for_other_compute) | [
"Try",
"to",
"found",
"the",
"best",
"ip",
"for",
"communication",
"from",
"one",
"compute",
"to",
"another"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L649-L693 |
226,554 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/frame_relay_switch.py | FrameRelaySwitch.add_nio | def add_nio(self, nio, port_number):
"""
Adds a NIO as new port on Frame Relay switch.
:param nio: NIO instance to add
:param port_number: port to allocate for the NIO
"""
if port_number in self._nios:
raise DynamipsError("Port {} isn't free".format(port_number))
log.info('Frame Relay switch "{name}" [{id}]: NIO {nio} bound to port {port}'.format(name=self._name,
id=self._id,
nio=nio,
port=port_number))
self._nios[port_number] = nio
yield from self.set_mappings(self._mappings) | python | def add_nio(self, nio, port_number):
"""
Adds a NIO as new port on Frame Relay switch.
:param nio: NIO instance to add
:param port_number: port to allocate for the NIO
"""
if port_number in self._nios:
raise DynamipsError("Port {} isn't free".format(port_number))
log.info('Frame Relay switch "{name}" [{id}]: NIO {nio} bound to port {port}'.format(name=self._name,
id=self._id,
nio=nio,
port=port_number))
self._nios[port_number] = nio
yield from self.set_mappings(self._mappings) | [
"def",
"add_nio",
"(",
"self",
",",
"nio",
",",
"port_number",
")",
":",
"if",
"port_number",
"in",
"self",
".",
"_nios",
":",
"raise",
"DynamipsError",
"(",
"\"Port {} isn't free\"",
".",
"format",
"(",
"port_number",
")",
")",
"log",
".",
"info",
"(",
... | Adds a NIO as new port on Frame Relay switch.
:param nio: NIO instance to add
:param port_number: port to allocate for the NIO | [
"Adds",
"a",
"NIO",
"as",
"new",
"port",
"on",
"Frame",
"Relay",
"switch",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/frame_relay_switch.py#L160-L177 |
226,555 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/frame_relay_switch.py | FrameRelaySwitch.remove_nio | def remove_nio(self, port_number):
"""
Removes the specified NIO as member of this Frame Relay switch.
:param port_number: allocated port number
:returns: the NIO that was bound to the allocated port
"""
if port_number not in self._nios:
raise DynamipsError("Port {} is not allocated".format(port_number))
# remove VCs mapped with the port
for source, destination in self._active_mappings.copy().items():
source_port, source_dlci = source
destination_port, destination_dlci = destination
if port_number == source_port:
log.info('Frame Relay switch "{name}" [{id}]: unmapping VC between port {source_port} DLCI {source_dlci} and port {destination_port} DLCI {destination_dlci}'.format(name=self._name,
id=self._id,
source_port=source_port,
source_dlci=source_dlci,
destination_port=destination_port,
destination_dlci=destination_dlci))
yield from self.unmap_vc(source_port, source_dlci, destination_port, destination_dlci)
yield from self.unmap_vc(destination_port, destination_dlci, source_port, source_dlci)
nio = self._nios[port_number]
if isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
log.info('Frame Relay switch "{name}" [{id}]: NIO {nio} removed from port {port}'.format(name=self._name,
id=self._id,
nio=nio,
port=port_number))
del self._nios[port_number]
return nio | python | def remove_nio(self, port_number):
"""
Removes the specified NIO as member of this Frame Relay switch.
:param port_number: allocated port number
:returns: the NIO that was bound to the allocated port
"""
if port_number not in self._nios:
raise DynamipsError("Port {} is not allocated".format(port_number))
# remove VCs mapped with the port
for source, destination in self._active_mappings.copy().items():
source_port, source_dlci = source
destination_port, destination_dlci = destination
if port_number == source_port:
log.info('Frame Relay switch "{name}" [{id}]: unmapping VC between port {source_port} DLCI {source_dlci} and port {destination_port} DLCI {destination_dlci}'.format(name=self._name,
id=self._id,
source_port=source_port,
source_dlci=source_dlci,
destination_port=destination_port,
destination_dlci=destination_dlci))
yield from self.unmap_vc(source_port, source_dlci, destination_port, destination_dlci)
yield from self.unmap_vc(destination_port, destination_dlci, source_port, source_dlci)
nio = self._nios[port_number]
if isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
log.info('Frame Relay switch "{name}" [{id}]: NIO {nio} removed from port {port}'.format(name=self._name,
id=self._id,
nio=nio,
port=port_number))
del self._nios[port_number]
return nio | [
"def",
"remove_nio",
"(",
"self",
",",
"port_number",
")",
":",
"if",
"port_number",
"not",
"in",
"self",
".",
"_nios",
":",
"raise",
"DynamipsError",
"(",
"\"Port {} is not allocated\"",
".",
"format",
"(",
"port_number",
")",
")",
"# remove VCs mapped with the p... | Removes the specified NIO as member of this Frame Relay switch.
:param port_number: allocated port number
:returns: the NIO that was bound to the allocated port | [
"Removes",
"the",
"specified",
"NIO",
"as",
"member",
"of",
"this",
"Frame",
"Relay",
"switch",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/frame_relay_switch.py#L180-L216 |
226,556 | GNS3/gns3-server | gns3server/main.py | main | def main():
"""
Entry point for GNS3 server
"""
if not sys.platform.startswith("win"):
if "--daemon" in sys.argv:
daemonize()
from gns3server.run import run
run() | python | def main():
"""
Entry point for GNS3 server
"""
if not sys.platform.startswith("win"):
if "--daemon" in sys.argv:
daemonize()
from gns3server.run import run
run() | [
"def",
"main",
"(",
")",
":",
"if",
"not",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"if",
"\"--daemon\"",
"in",
"sys",
".",
"argv",
":",
"daemonize",
"(",
")",
"from",
"gns3server",
".",
"run",
"import",
"run",
"run",
"(",... | Entry point for GNS3 server | [
"Entry",
"point",
"for",
"GNS3",
"server"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/main.py#L74-L83 |
226,557 | GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM._get_free_display_port | def _get_free_display_port(self):
"""
Search a free display port
"""
display = 100
if not os.path.exists("/tmp/.X11-unix/"):
return display
while True:
if not os.path.exists("/tmp/.X11-unix/X{}".format(display)):
return display
display += 1 | python | def _get_free_display_port(self):
"""
Search a free display port
"""
display = 100
if not os.path.exists("/tmp/.X11-unix/"):
return display
while True:
if not os.path.exists("/tmp/.X11-unix/X{}".format(display)):
return display
display += 1 | [
"def",
"_get_free_display_port",
"(",
"self",
")",
":",
"display",
"=",
"100",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"\"/tmp/.X11-unix/\"",
")",
":",
"return",
"display",
"while",
"True",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
... | Search a free display port | [
"Search",
"a",
"free",
"display",
"port"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L120-L130 |
226,558 | GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM.create | def create(self):
"""Creates the Docker container."""
try:
image_infos = yield from self._get_image_information()
except DockerHttp404Error:
log.info("Image %s is missing pulling it from docker hub", self._image)
yield from self.pull_image(self._image)
image_infos = yield from self._get_image_information()
if image_infos is None:
raise DockerError("Can't get image informations, please try again.")
params = {
"Hostname": self._name,
"Name": self._name,
"Image": self._image,
"NetworkDisabled": True,
"Tty": True,
"OpenStdin": True,
"StdinOnce": False,
"HostConfig": {
"CapAdd": ["ALL"],
"Privileged": True,
"Binds": self._mount_binds(image_infos)
},
"Volumes": {},
"Env": ["container=docker"], # Systemd compliant: https://github.com/GNS3/gns3-server/issues/573
"Cmd": [],
"Entrypoint": image_infos.get("Config", {"Entrypoint": []})["Entrypoint"]
}
if params["Entrypoint"] is None:
params["Entrypoint"] = []
if self._start_command:
params["Cmd"] = shlex.split(self._start_command)
if len(params["Cmd"]) == 0:
params["Cmd"] = image_infos.get("Config", {"Cmd": []})["Cmd"]
if params["Cmd"] is None:
params["Cmd"] = []
if len(params["Cmd"]) == 0 and len(params["Entrypoint"]) == 0:
params["Cmd"] = ["/bin/sh"]
params["Entrypoint"].insert(0, "/gns3/init.sh") # FIXME /gns3/init.sh is not found?
# Give the information to the container on how many interface should be inside
params["Env"].append("GNS3_MAX_ETHERNET=eth{}".format(self.adapters - 1))
# Give the information to the container the list of volume path mounted
params["Env"].append("GNS3_VOLUMES={}".format(":".join(self._volumes)))
if self._environment:
for e in self._environment.strip().split("\n"):
e = e.strip()
if not e.startswith("GNS3_"):
params["Env"].append(e)
if self._console_type == "vnc":
yield from self._start_vnc()
params["Env"].append("QT_GRAPHICSSYSTEM=native") # To fix a Qt issue: https://github.com/GNS3/gns3-server/issues/556
params["Env"].append("DISPLAY=:{}".format(self._display))
params["HostConfig"]["Binds"].append("/tmp/.X11-unix/:/tmp/.X11-unix/")
result = yield from self.manager.query("POST", "containers/create", data=params)
self._cid = result['Id']
log.info("Docker container '{name}' [{id}] created".format(
name=self._name, id=self._id))
return True | python | def create(self):
"""Creates the Docker container."""
try:
image_infos = yield from self._get_image_information()
except DockerHttp404Error:
log.info("Image %s is missing pulling it from docker hub", self._image)
yield from self.pull_image(self._image)
image_infos = yield from self._get_image_information()
if image_infos is None:
raise DockerError("Can't get image informations, please try again.")
params = {
"Hostname": self._name,
"Name": self._name,
"Image": self._image,
"NetworkDisabled": True,
"Tty": True,
"OpenStdin": True,
"StdinOnce": False,
"HostConfig": {
"CapAdd": ["ALL"],
"Privileged": True,
"Binds": self._mount_binds(image_infos)
},
"Volumes": {},
"Env": ["container=docker"], # Systemd compliant: https://github.com/GNS3/gns3-server/issues/573
"Cmd": [],
"Entrypoint": image_infos.get("Config", {"Entrypoint": []})["Entrypoint"]
}
if params["Entrypoint"] is None:
params["Entrypoint"] = []
if self._start_command:
params["Cmd"] = shlex.split(self._start_command)
if len(params["Cmd"]) == 0:
params["Cmd"] = image_infos.get("Config", {"Cmd": []})["Cmd"]
if params["Cmd"] is None:
params["Cmd"] = []
if len(params["Cmd"]) == 0 and len(params["Entrypoint"]) == 0:
params["Cmd"] = ["/bin/sh"]
params["Entrypoint"].insert(0, "/gns3/init.sh") # FIXME /gns3/init.sh is not found?
# Give the information to the container on how many interface should be inside
params["Env"].append("GNS3_MAX_ETHERNET=eth{}".format(self.adapters - 1))
# Give the information to the container the list of volume path mounted
params["Env"].append("GNS3_VOLUMES={}".format(":".join(self._volumes)))
if self._environment:
for e in self._environment.strip().split("\n"):
e = e.strip()
if not e.startswith("GNS3_"):
params["Env"].append(e)
if self._console_type == "vnc":
yield from self._start_vnc()
params["Env"].append("QT_GRAPHICSSYSTEM=native") # To fix a Qt issue: https://github.com/GNS3/gns3-server/issues/556
params["Env"].append("DISPLAY=:{}".format(self._display))
params["HostConfig"]["Binds"].append("/tmp/.X11-unix/:/tmp/.X11-unix/")
result = yield from self.manager.query("POST", "containers/create", data=params)
self._cid = result['Id']
log.info("Docker container '{name}' [{id}] created".format(
name=self._name, id=self._id))
return True | [
"def",
"create",
"(",
"self",
")",
":",
"try",
":",
"image_infos",
"=",
"yield",
"from",
"self",
".",
"_get_image_information",
"(",
")",
"except",
"DockerHttp404Error",
":",
"log",
".",
"info",
"(",
"\"Image %s is missing pulling it from docker hub\"",
",",
"self... | Creates the Docker container. | [
"Creates",
"the",
"Docker",
"container",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L268-L332 |
226,559 | GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM.update | def update(self):
"""
Destroy an recreate the container with the new settings
"""
# We need to save the console and state and restore it
console = self.console
aux = self.aux
state = yield from self._get_container_state()
yield from self.reset()
yield from self.create()
self.console = console
self.aux = aux
if state == "running":
yield from self.start() | python | def update(self):
"""
Destroy an recreate the container with the new settings
"""
# We need to save the console and state and restore it
console = self.console
aux = self.aux
state = yield from self._get_container_state()
yield from self.reset()
yield from self.create()
self.console = console
self.aux = aux
if state == "running":
yield from self.start() | [
"def",
"update",
"(",
"self",
")",
":",
"# We need to save the console and state and restore it",
"console",
"=",
"self",
".",
"console",
"aux",
"=",
"self",
".",
"aux",
"state",
"=",
"yield",
"from",
"self",
".",
"_get_container_state",
"(",
")",
"yield",
"from... | Destroy an recreate the container with the new settings | [
"Destroy",
"an",
"recreate",
"the",
"container",
"with",
"the",
"new",
"settings"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L335-L349 |
226,560 | GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM.start | def start(self):
"""Starts this Docker container."""
try:
state = yield from self._get_container_state()
except DockerHttp404Error:
raise DockerError("Docker container '{name}' with ID {cid} does not exist or is not ready yet. Please try again in a few seconds.".format(name=self.name,
cid=self._cid))
if state == "paused":
yield from self.unpause()
elif state == "running":
return
else:
yield from self._clean_servers()
yield from self.manager.query("POST", "containers/{}/start".format(self._cid))
self._namespace = yield from self._get_namespace()
yield from self._start_ubridge()
for adapter_number in range(0, self.adapters):
nio = self._ethernet_adapters[adapter_number].get_nio(0)
with (yield from self.manager.ubridge_lock):
try:
yield from self._add_ubridge_connection(nio, adapter_number)
except UbridgeNamespaceError:
log.error("Container %s failed to start", self.name)
yield from self.stop()
# The container can crash soon after the start, this means we can not move the interface to the container namespace
logdata = yield from self._get_log()
for line in logdata.split('\n'):
log.error(line)
raise DockerError(logdata)
if self.console_type == "telnet":
yield from self._start_console()
elif self.console_type == "http" or self.console_type == "https":
yield from self._start_http()
if self.allocate_aux:
yield from self._start_aux()
self.status = "started"
log.info("Docker container '{name}' [{image}] started listen for {console_type} on {console}".format(name=self._name,
image=self._image,
console=self.console,
console_type=self.console_type)) | python | def start(self):
"""Starts this Docker container."""
try:
state = yield from self._get_container_state()
except DockerHttp404Error:
raise DockerError("Docker container '{name}' with ID {cid} does not exist or is not ready yet. Please try again in a few seconds.".format(name=self.name,
cid=self._cid))
if state == "paused":
yield from self.unpause()
elif state == "running":
return
else:
yield from self._clean_servers()
yield from self.manager.query("POST", "containers/{}/start".format(self._cid))
self._namespace = yield from self._get_namespace()
yield from self._start_ubridge()
for adapter_number in range(0, self.adapters):
nio = self._ethernet_adapters[adapter_number].get_nio(0)
with (yield from self.manager.ubridge_lock):
try:
yield from self._add_ubridge_connection(nio, adapter_number)
except UbridgeNamespaceError:
log.error("Container %s failed to start", self.name)
yield from self.stop()
# The container can crash soon after the start, this means we can not move the interface to the container namespace
logdata = yield from self._get_log()
for line in logdata.split('\n'):
log.error(line)
raise DockerError(logdata)
if self.console_type == "telnet":
yield from self._start_console()
elif self.console_type == "http" or self.console_type == "https":
yield from self._start_http()
if self.allocate_aux:
yield from self._start_aux()
self.status = "started"
log.info("Docker container '{name}' [{image}] started listen for {console_type} on {console}".format(name=self._name,
image=self._image,
console=self.console,
console_type=self.console_type)) | [
"def",
"start",
"(",
"self",
")",
":",
"try",
":",
"state",
"=",
"yield",
"from",
"self",
".",
"_get_container_state",
"(",
")",
"except",
"DockerHttp404Error",
":",
"raise",
"DockerError",
"(",
"\"Docker container '{name}' with ID {cid} does not exist or is not ready y... | Starts this Docker container. | [
"Starts",
"this",
"Docker",
"container",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L352-L399 |
226,561 | GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM._start_aux | def _start_aux(self):
"""
Start an auxilary console
"""
# We can not use the API because docker doesn't expose a websocket api for exec
# https://github.com/GNS3/gns3-gui/issues/1039
process = yield from asyncio.subprocess.create_subprocess_exec(
"docker", "exec", "-i", self._cid, "/gns3/bin/busybox", "script", "-qfc", "while true; do TERM=vt100 /gns3/bin/busybox sh; done", "/dev/null",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
stdin=asyncio.subprocess.PIPE)
server = AsyncioTelnetServer(reader=process.stdout, writer=process.stdin, binary=True, echo=True)
self._telnet_servers.append((yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.aux)))
log.debug("Docker container '%s' started listen for auxilary telnet on %d", self.name, self.aux) | python | def _start_aux(self):
"""
Start an auxilary console
"""
# We can not use the API because docker doesn't expose a websocket api for exec
# https://github.com/GNS3/gns3-gui/issues/1039
process = yield from asyncio.subprocess.create_subprocess_exec(
"docker", "exec", "-i", self._cid, "/gns3/bin/busybox", "script", "-qfc", "while true; do TERM=vt100 /gns3/bin/busybox sh; done", "/dev/null",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
stdin=asyncio.subprocess.PIPE)
server = AsyncioTelnetServer(reader=process.stdout, writer=process.stdin, binary=True, echo=True)
self._telnet_servers.append((yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.aux)))
log.debug("Docker container '%s' started listen for auxilary telnet on %d", self.name, self.aux) | [
"def",
"_start_aux",
"(",
"self",
")",
":",
"# We can not use the API because docker doesn't expose a websocket api for exec",
"# https://github.com/GNS3/gns3-gui/issues/1039",
"process",
"=",
"yield",
"from",
"asyncio",
".",
"subprocess",
".",
"create_subprocess_exec",
"(",
"\"d... | Start an auxilary console | [
"Start",
"an",
"auxilary",
"console"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L402-L416 |
226,562 | GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM._fix_permissions | def _fix_permissions(self):
"""
Because docker run as root we need to fix permission and ownership to allow user to interact
with it from their filesystem and do operation like file delete
"""
state = yield from self._get_container_state()
if state == "stopped" or state == "exited":
# We need to restart it to fix permissions
yield from self.manager.query("POST", "containers/{}/start".format(self._cid))
for volume in self._volumes:
log.debug("Docker container '{name}' [{image}] fix ownership on {path}".format(
name=self._name, image=self._image, path=volume))
process = yield from asyncio.subprocess.create_subprocess_exec(
"docker",
"exec",
self._cid,
"/gns3/bin/busybox",
"sh",
"-c",
"("
"/gns3/bin/busybox find \"{path}\" -depth -print0"
" | /gns3/bin/busybox xargs -0 /gns3/bin/busybox stat -c '%a:%u:%g:%n' > \"{path}/.gns3_perms\""
")"
" && /gns3/bin/busybox chmod -R u+rX \"{path}\""
" && /gns3/bin/busybox chown {uid}:{gid} -R \"{path}\""
.format(uid=os.getuid(), gid=os.getgid(), path=volume),
)
yield from process.wait() | python | def _fix_permissions(self):
"""
Because docker run as root we need to fix permission and ownership to allow user to interact
with it from their filesystem and do operation like file delete
"""
state = yield from self._get_container_state()
if state == "stopped" or state == "exited":
# We need to restart it to fix permissions
yield from self.manager.query("POST", "containers/{}/start".format(self._cid))
for volume in self._volumes:
log.debug("Docker container '{name}' [{image}] fix ownership on {path}".format(
name=self._name, image=self._image, path=volume))
process = yield from asyncio.subprocess.create_subprocess_exec(
"docker",
"exec",
self._cid,
"/gns3/bin/busybox",
"sh",
"-c",
"("
"/gns3/bin/busybox find \"{path}\" -depth -print0"
" | /gns3/bin/busybox xargs -0 /gns3/bin/busybox stat -c '%a:%u:%g:%n' > \"{path}/.gns3_perms\""
")"
" && /gns3/bin/busybox chmod -R u+rX \"{path}\""
" && /gns3/bin/busybox chown {uid}:{gid} -R \"{path}\""
.format(uid=os.getuid(), gid=os.getgid(), path=volume),
)
yield from process.wait() | [
"def",
"_fix_permissions",
"(",
"self",
")",
":",
"state",
"=",
"yield",
"from",
"self",
".",
"_get_container_state",
"(",
")",
"if",
"state",
"==",
"\"stopped\"",
"or",
"state",
"==",
"\"exited\"",
":",
"# We need to restart it to fix permissions",
"yield",
"from... | Because docker run as root we need to fix permission and ownership to allow user to interact
with it from their filesystem and do operation like file delete | [
"Because",
"docker",
"run",
"as",
"root",
"we",
"need",
"to",
"fix",
"permission",
"and",
"ownership",
"to",
"allow",
"user",
"to",
"interact",
"with",
"it",
"from",
"their",
"filesystem",
"and",
"do",
"operation",
"like",
"file",
"delete"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L419-L448 |
226,563 | GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM._start_vnc | def _start_vnc(self):
"""
Start a VNC server for this container
"""
self._display = self._get_free_display_port()
if shutil.which("Xvfb") is None or shutil.which("x11vnc") is None:
raise DockerError("Please install Xvfb and x11vnc before using the VNC support")
self._xvfb_process = yield from asyncio.create_subprocess_exec("Xvfb", "-nolisten", "tcp", ":{}".format(self._display), "-screen", "0", self._console_resolution + "x16")
# We pass a port for TCPV6 due to a crash in X11VNC if not here: https://github.com/GNS3/gns3-server/issues/569
self._x11vnc_process = yield from asyncio.create_subprocess_exec("x11vnc", "-forever", "-nopw", "-shared", "-geometry", self._console_resolution, "-display", "WAIT:{}".format(self._display), "-rfbport", str(self.console), "-rfbportv6", str(self.console), "-noncache", "-listen", self._manager.port_manager.console_host)
x11_socket = os.path.join("/tmp/.X11-unix/", "X{}".format(self._display))
yield from wait_for_file_creation(x11_socket) | python | def _start_vnc(self):
"""
Start a VNC server for this container
"""
self._display = self._get_free_display_port()
if shutil.which("Xvfb") is None or shutil.which("x11vnc") is None:
raise DockerError("Please install Xvfb and x11vnc before using the VNC support")
self._xvfb_process = yield from asyncio.create_subprocess_exec("Xvfb", "-nolisten", "tcp", ":{}".format(self._display), "-screen", "0", self._console_resolution + "x16")
# We pass a port for TCPV6 due to a crash in X11VNC if not here: https://github.com/GNS3/gns3-server/issues/569
self._x11vnc_process = yield from asyncio.create_subprocess_exec("x11vnc", "-forever", "-nopw", "-shared", "-geometry", self._console_resolution, "-display", "WAIT:{}".format(self._display), "-rfbport", str(self.console), "-rfbportv6", str(self.console), "-noncache", "-listen", self._manager.port_manager.console_host)
x11_socket = os.path.join("/tmp/.X11-unix/", "X{}".format(self._display))
yield from wait_for_file_creation(x11_socket) | [
"def",
"_start_vnc",
"(",
"self",
")",
":",
"self",
".",
"_display",
"=",
"self",
".",
"_get_free_display_port",
"(",
")",
"if",
"shutil",
".",
"which",
"(",
"\"Xvfb\"",
")",
"is",
"None",
"or",
"shutil",
".",
"which",
"(",
"\"x11vnc\"",
")",
"is",
"No... | Start a VNC server for this container | [
"Start",
"a",
"VNC",
"server",
"for",
"this",
"container"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L451-L464 |
226,564 | GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM._start_http | def _start_http(self):
"""
Start an HTTP tunnel to container localhost. It's not perfect
but the only way we have to inject network packet is using nc.
"""
log.debug("Forward HTTP for %s to %d", self.name, self._console_http_port)
command = ["docker", "exec", "-i", self._cid, "/gns3/bin/busybox", "nc", "127.0.0.1", str(self._console_http_port)]
# We replace host and port in the server answer otherwise some link could be broken
server = AsyncioRawCommandServer(command, replaces=[
(
'://127.0.0.1'.encode(), # {{HOST}} mean client host
'://{{HOST}}'.encode(),
),
(
':{}'.format(self._console_http_port).encode(),
':{}'.format(self.console).encode(),
)
])
self._telnet_servers.append((yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console))) | python | def _start_http(self):
"""
Start an HTTP tunnel to container localhost. It's not perfect
but the only way we have to inject network packet is using nc.
"""
log.debug("Forward HTTP for %s to %d", self.name, self._console_http_port)
command = ["docker", "exec", "-i", self._cid, "/gns3/bin/busybox", "nc", "127.0.0.1", str(self._console_http_port)]
# We replace host and port in the server answer otherwise some link could be broken
server = AsyncioRawCommandServer(command, replaces=[
(
'://127.0.0.1'.encode(), # {{HOST}} mean client host
'://{{HOST}}'.encode(),
),
(
':{}'.format(self._console_http_port).encode(),
':{}'.format(self.console).encode(),
)
])
self._telnet_servers.append((yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console))) | [
"def",
"_start_http",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"Forward HTTP for %s to %d\"",
",",
"self",
".",
"name",
",",
"self",
".",
"_console_http_port",
")",
"command",
"=",
"[",
"\"docker\"",
",",
"\"exec\"",
",",
"\"-i\"",
",",
"self",
"... | Start an HTTP tunnel to container localhost. It's not perfect
but the only way we have to inject network packet is using nc. | [
"Start",
"an",
"HTTP",
"tunnel",
"to",
"container",
"localhost",
".",
"It",
"s",
"not",
"perfect",
"but",
"the",
"only",
"way",
"we",
"have",
"to",
"inject",
"network",
"packet",
"is",
"using",
"nc",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L467-L485 |
226,565 | GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM._start_console | def _start_console(self):
"""
Start streaming the console via telnet
"""
class InputStream:
def __init__(self):
self._data = b""
def write(self, data):
self._data += data
@asyncio.coroutine
def drain(self):
if not self.ws.closed:
self.ws.send_bytes(self._data)
self._data = b""
output_stream = asyncio.StreamReader()
input_stream = InputStream()
telnet = AsyncioTelnetServer(reader=output_stream, writer=input_stream, echo=True)
self._telnet_servers.append((yield from asyncio.start_server(telnet.run, self._manager.port_manager.console_host, self.console)))
self._console_websocket = yield from self.manager.websocket_query("containers/{}/attach/ws?stream=1&stdin=1&stdout=1&stderr=1".format(self._cid))
input_stream.ws = self._console_websocket
output_stream.feed_data(self.name.encode() + b" console is now available... Press RETURN to get started.\r\n")
asyncio.async(self._read_console_output(self._console_websocket, output_stream)) | python | def _start_console(self):
"""
Start streaming the console via telnet
"""
class InputStream:
def __init__(self):
self._data = b""
def write(self, data):
self._data += data
@asyncio.coroutine
def drain(self):
if not self.ws.closed:
self.ws.send_bytes(self._data)
self._data = b""
output_stream = asyncio.StreamReader()
input_stream = InputStream()
telnet = AsyncioTelnetServer(reader=output_stream, writer=input_stream, echo=True)
self._telnet_servers.append((yield from asyncio.start_server(telnet.run, self._manager.port_manager.console_host, self.console)))
self._console_websocket = yield from self.manager.websocket_query("containers/{}/attach/ws?stream=1&stdin=1&stdout=1&stderr=1".format(self._cid))
input_stream.ws = self._console_websocket
output_stream.feed_data(self.name.encode() + b" console is now available... Press RETURN to get started.\r\n")
asyncio.async(self._read_console_output(self._console_websocket, output_stream)) | [
"def",
"_start_console",
"(",
"self",
")",
":",
"class",
"InputStream",
":",
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"_data",
"=",
"b\"\"",
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_data",
"+=",
"data",
"@",
... | Start streaming the console via telnet | [
"Start",
"streaming",
"the",
"console",
"via",
"telnet"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L488-L518 |
226,566 | GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM._read_console_output | def _read_console_output(self, ws, out):
"""
Read Websocket and forward it to the telnet
:param ws: Websocket connection
:param out: Output stream
"""
while True:
msg = yield from ws.receive()
if msg.tp == aiohttp.WSMsgType.text:
out.feed_data(msg.data.encode())
elif msg.tp == aiohttp.WSMsgType.BINARY:
out.feed_data(msg.data)
elif msg.tp == aiohttp.WSMsgType.ERROR:
log.critical("Docker WebSocket Error: {}".format(msg.data))
else:
out.feed_eof()
ws.close()
break
yield from self.stop() | python | def _read_console_output(self, ws, out):
"""
Read Websocket and forward it to the telnet
:param ws: Websocket connection
:param out: Output stream
"""
while True:
msg = yield from ws.receive()
if msg.tp == aiohttp.WSMsgType.text:
out.feed_data(msg.data.encode())
elif msg.tp == aiohttp.WSMsgType.BINARY:
out.feed_data(msg.data)
elif msg.tp == aiohttp.WSMsgType.ERROR:
log.critical("Docker WebSocket Error: {}".format(msg.data))
else:
out.feed_eof()
ws.close()
break
yield from self.stop() | [
"def",
"_read_console_output",
"(",
"self",
",",
"ws",
",",
"out",
")",
":",
"while",
"True",
":",
"msg",
"=",
"yield",
"from",
"ws",
".",
"receive",
"(",
")",
"if",
"msg",
".",
"tp",
"==",
"aiohttp",
".",
"WSMsgType",
".",
"text",
":",
"out",
".",... | Read Websocket and forward it to the telnet
:param ws: Websocket connection
:param out: Output stream | [
"Read",
"Websocket",
"and",
"forward",
"it",
"to",
"the",
"telnet"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L521-L541 |
226,567 | GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM.is_running | def is_running(self):
"""Checks if the container is running.
:returns: True or False
:rtype: bool
"""
state = yield from self._get_container_state()
if state == "running":
return True
if self.status == "started": # The container crashed we need to clean
yield from self.stop()
return False | python | def is_running(self):
"""Checks if the container is running.
:returns: True or False
:rtype: bool
"""
state = yield from self._get_container_state()
if state == "running":
return True
if self.status == "started": # The container crashed we need to clean
yield from self.stop()
return False | [
"def",
"is_running",
"(",
"self",
")",
":",
"state",
"=",
"yield",
"from",
"self",
".",
"_get_container_state",
"(",
")",
"if",
"state",
"==",
"\"running\"",
":",
"return",
"True",
"if",
"self",
".",
"status",
"==",
"\"started\"",
":",
"# The container crash... | Checks if the container is running.
:returns: True or False
:rtype: bool | [
"Checks",
"if",
"the",
"container",
"is",
"running",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L544-L555 |
226,568 | GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM.restart | def restart(self):
"""Restart this Docker container."""
yield from self.manager.query("POST", "containers/{}/restart".format(self._cid))
log.info("Docker container '{name}' [{image}] restarted".format(
name=self._name, image=self._image)) | python | def restart(self):
"""Restart this Docker container."""
yield from self.manager.query("POST", "containers/{}/restart".format(self._cid))
log.info("Docker container '{name}' [{image}] restarted".format(
name=self._name, image=self._image)) | [
"def",
"restart",
"(",
"self",
")",
":",
"yield",
"from",
"self",
".",
"manager",
".",
"query",
"(",
"\"POST\"",
",",
"\"containers/{}/restart\"",
".",
"format",
"(",
"self",
".",
"_cid",
")",
")",
"log",
".",
"info",
"(",
"\"Docker container '{name}' [{imag... | Restart this Docker container. | [
"Restart",
"this",
"Docker",
"container",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L558-L562 |
226,569 | GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM._clean_servers | def _clean_servers(self):
"""
Clean the list of running console servers
"""
if len(self._telnet_servers) > 0:
for telnet_server in self._telnet_servers:
telnet_server.close()
yield from telnet_server.wait_closed()
self._telnet_servers = [] | python | def _clean_servers(self):
"""
Clean the list of running console servers
"""
if len(self._telnet_servers) > 0:
for telnet_server in self._telnet_servers:
telnet_server.close()
yield from telnet_server.wait_closed()
self._telnet_servers = [] | [
"def",
"_clean_servers",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_telnet_servers",
")",
">",
"0",
":",
"for",
"telnet_server",
"in",
"self",
".",
"_telnet_servers",
":",
"telnet_server",
".",
"close",
"(",
")",
"yield",
"from",
"telnet_serve... | Clean the list of running console servers | [
"Clean",
"the",
"list",
"of",
"running",
"console",
"servers"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L565-L573 |
226,570 | GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM.stop | def stop(self):
"""Stops this Docker container."""
try:
yield from self._clean_servers()
yield from self._stop_ubridge()
try:
state = yield from self._get_container_state()
except DockerHttp404Error:
self.status = "stopped"
return
if state == "paused":
yield from self.unpause()
yield from self._fix_permissions()
state = yield from self._get_container_state()
if state != "stopped" or state != "exited":
# t=5 number of seconds to wait before killing the container
try:
yield from self.manager.query("POST", "containers/{}/stop".format(self._cid), params={"t": 5})
log.info("Docker container '{name}' [{image}] stopped".format(
name=self._name, image=self._image))
except DockerHttp304Error:
# Container is already stopped
pass
# Ignore runtime error because when closing the server
except RuntimeError as e:
log.debug("Docker runtime error when closing: {}".format(str(e)))
return
self.status = "stopped" | python | def stop(self):
"""Stops this Docker container."""
try:
yield from self._clean_servers()
yield from self._stop_ubridge()
try:
state = yield from self._get_container_state()
except DockerHttp404Error:
self.status = "stopped"
return
if state == "paused":
yield from self.unpause()
yield from self._fix_permissions()
state = yield from self._get_container_state()
if state != "stopped" or state != "exited":
# t=5 number of seconds to wait before killing the container
try:
yield from self.manager.query("POST", "containers/{}/stop".format(self._cid), params={"t": 5})
log.info("Docker container '{name}' [{image}] stopped".format(
name=self._name, image=self._image))
except DockerHttp304Error:
# Container is already stopped
pass
# Ignore runtime error because when closing the server
except RuntimeError as e:
log.debug("Docker runtime error when closing: {}".format(str(e)))
return
self.status = "stopped" | [
"def",
"stop",
"(",
"self",
")",
":",
"try",
":",
"yield",
"from",
"self",
".",
"_clean_servers",
"(",
")",
"yield",
"from",
"self",
".",
"_stop_ubridge",
"(",
")",
"try",
":",
"state",
"=",
"yield",
"from",
"self",
".",
"_get_container_state",
"(",
")... | Stops this Docker container. | [
"Stops",
"this",
"Docker",
"container",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L576-L607 |
226,571 | GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM.pause | def pause(self):
"""Pauses this Docker container."""
yield from self.manager.query("POST", "containers/{}/pause".format(self._cid))
self.status = "suspended"
log.info("Docker container '{name}' [{image}] paused".format(name=self._name, image=self._image)) | python | def pause(self):
"""Pauses this Docker container."""
yield from self.manager.query("POST", "containers/{}/pause".format(self._cid))
self.status = "suspended"
log.info("Docker container '{name}' [{image}] paused".format(name=self._name, image=self._image)) | [
"def",
"pause",
"(",
"self",
")",
":",
"yield",
"from",
"self",
".",
"manager",
".",
"query",
"(",
"\"POST\"",
",",
"\"containers/{}/pause\"",
".",
"format",
"(",
"self",
".",
"_cid",
")",
")",
"self",
".",
"status",
"=",
"\"suspended\"",
"log",
".",
"... | Pauses this Docker container. | [
"Pauses",
"this",
"Docker",
"container",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L610-L614 |
226,572 | GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM._get_log | def _get_log(self):
"""
Return the log from the container
:returns: string
"""
result = yield from self.manager.query("GET", "containers/{}/logs".format(self._cid), params={"stderr": 1, "stdout": 1})
return result | python | def _get_log(self):
"""
Return the log from the container
:returns: string
"""
result = yield from self.manager.query("GET", "containers/{}/logs".format(self._cid), params={"stderr": 1, "stdout": 1})
return result | [
"def",
"_get_log",
"(",
"self",
")",
":",
"result",
"=",
"yield",
"from",
"self",
".",
"manager",
".",
"query",
"(",
"\"GET\"",
",",
"\"containers/{}/logs\"",
".",
"format",
"(",
"self",
".",
"_cid",
")",
",",
"params",
"=",
"{",
"\"stderr\"",
":",
"1"... | Return the log from the container
:returns: string | [
"Return",
"the",
"log",
"from",
"the",
"container"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L916-L924 |
226,573 | GNS3/gns3-server | gns3server/compute/iou/utils/application_id.py | get_next_application_id | def get_next_application_id(nodes):
"""
Calculates free application_id from given nodes
:param nodes:
:raises IOUError when exceeds number
:return: integer first free id
"""
used = set([n.application_id for n in nodes])
pool = set(range(1, 512))
try:
return (pool - used).pop()
except KeyError:
raise IOUError("Cannot create a new IOU VM (limit of 512 VMs on one host reached)") | python | def get_next_application_id(nodes):
"""
Calculates free application_id from given nodes
:param nodes:
:raises IOUError when exceeds number
:return: integer first free id
"""
used = set([n.application_id for n in nodes])
pool = set(range(1, 512))
try:
return (pool - used).pop()
except KeyError:
raise IOUError("Cannot create a new IOU VM (limit of 512 VMs on one host reached)") | [
"def",
"get_next_application_id",
"(",
"nodes",
")",
":",
"used",
"=",
"set",
"(",
"[",
"n",
".",
"application_id",
"for",
"n",
"in",
"nodes",
"]",
")",
"pool",
"=",
"set",
"(",
"range",
"(",
"1",
",",
"512",
")",
")",
"try",
":",
"return",
"(",
... | Calculates free application_id from given nodes
:param nodes:
:raises IOUError when exceeds number
:return: integer first free id | [
"Calculates",
"free",
"application_id",
"from",
"given",
"nodes"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/utils/application_id.py#L24-L37 |
226,574 | GNS3/gns3-server | gns3server/config.py | Config.clear | def clear(self):
"""Restart with a clean config"""
self._config = configparser.RawConfigParser()
# Override config from command line even if we modify the config file and live reload it.
self._override_config = {}
self.read_config() | python | def clear(self):
"""Restart with a clean config"""
self._config = configparser.RawConfigParser()
# Override config from command line even if we modify the config file and live reload it.
self._override_config = {}
self.read_config() | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"_config",
"=",
"configparser",
".",
"RawConfigParser",
"(",
")",
"# Override config from command line even if we modify the config file and live reload it.",
"self",
".",
"_override_config",
"=",
"{",
"}",
"self",
"."... | Restart with a clean config | [
"Restart",
"with",
"a",
"clean",
"config"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/config.py#L137-L143 |
226,575 | GNS3/gns3-server | gns3server/config.py | Config.read_config | def read_config(self):
"""
Read the configuration files.
"""
try:
parsed_files = self._config.read(self._files, encoding="utf-8")
except configparser.Error as e:
log.error("Can't parse configuration file: %s", str(e))
return
if not parsed_files:
log.warning("No configuration file could be found or read")
else:
for file in parsed_files:
log.info("Load configuration file {}".format(file))
self._watched_files[file] = os.stat(file).st_mtime | python | def read_config(self):
"""
Read the configuration files.
"""
try:
parsed_files = self._config.read(self._files, encoding="utf-8")
except configparser.Error as e:
log.error("Can't parse configuration file: %s", str(e))
return
if not parsed_files:
log.warning("No configuration file could be found or read")
else:
for file in parsed_files:
log.info("Load configuration file {}".format(file))
self._watched_files[file] = os.stat(file).st_mtime | [
"def",
"read_config",
"(",
"self",
")",
":",
"try",
":",
"parsed_files",
"=",
"self",
".",
"_config",
".",
"read",
"(",
"self",
".",
"_files",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"except",
"configparser",
".",
"Error",
"as",
"e",
":",
"log",
".",
... | Read the configuration files. | [
"Read",
"the",
"configuration",
"files",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/config.py#L169-L184 |
226,576 | GNS3/gns3-server | gns3server/config.py | Config.get_section_config | def get_section_config(self, section):
"""
Get a specific configuration section.
Returns the default section if none can be found.
:returns: configparser section
"""
if section not in self._config:
return self._config["DEFAULT"]
return self._config[section] | python | def get_section_config(self, section):
"""
Get a specific configuration section.
Returns the default section if none can be found.
:returns: configparser section
"""
if section not in self._config:
return self._config["DEFAULT"]
return self._config[section] | [
"def",
"get_section_config",
"(",
"self",
",",
"section",
")",
":",
"if",
"section",
"not",
"in",
"self",
".",
"_config",
":",
"return",
"self",
".",
"_config",
"[",
"\"DEFAULT\"",
"]",
"return",
"self",
".",
"_config",
"[",
"section",
"]"
] | Get a specific configuration section.
Returns the default section if none can be found.
:returns: configparser section | [
"Get",
"a",
"specific",
"configuration",
"section",
".",
"Returns",
"the",
"default",
"section",
"if",
"none",
"can",
"be",
"found",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/config.py#L195-L205 |
226,577 | GNS3/gns3-server | gns3server/config.py | Config.set_section_config | def set_section_config(self, section, content):
"""
Set a specific configuration section. It's not
dumped on the disk.
:param section: Section name
:param content: A dictionary with section content
"""
if not self._config.has_section(section):
self._config.add_section(section)
for key in content:
if isinstance(content[key], bool):
content[key] = str(content[key]).lower()
self._config.set(section, key, content[key])
self._override_config[section] = content | python | def set_section_config(self, section, content):
"""
Set a specific configuration section. It's not
dumped on the disk.
:param section: Section name
:param content: A dictionary with section content
"""
if not self._config.has_section(section):
self._config.add_section(section)
for key in content:
if isinstance(content[key], bool):
content[key] = str(content[key]).lower()
self._config.set(section, key, content[key])
self._override_config[section] = content | [
"def",
"set_section_config",
"(",
"self",
",",
"section",
",",
"content",
")",
":",
"if",
"not",
"self",
".",
"_config",
".",
"has_section",
"(",
"section",
")",
":",
"self",
".",
"_config",
".",
"add_section",
"(",
"section",
")",
"for",
"key",
"in",
... | Set a specific configuration section. It's not
dumped on the disk.
:param section: Section name
:param content: A dictionary with section content | [
"Set",
"a",
"specific",
"configuration",
"section",
".",
"It",
"s",
"not",
"dumped",
"on",
"the",
"disk",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/config.py#L207-L222 |
226,578 | GNS3/gns3-server | gns3server/config.py | Config.set | def set(self, section, key, value):
"""
Set a config value.
It's not dumped on the disk.
If the section doesn't exists the section is created
"""
conf = self.get_section_config(section)
if isinstance(value, bool):
conf[key] = str(value)
else:
conf[key] = value
self.set_section_config(section, conf) | python | def set(self, section, key, value):
"""
Set a config value.
It's not dumped on the disk.
If the section doesn't exists the section is created
"""
conf = self.get_section_config(section)
if isinstance(value, bool):
conf[key] = str(value)
else:
conf[key] = value
self.set_section_config(section, conf) | [
"def",
"set",
"(",
"self",
",",
"section",
",",
"key",
",",
"value",
")",
":",
"conf",
"=",
"self",
".",
"get_section_config",
"(",
"section",
")",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"conf",
"[",
"key",
"]",
"=",
"str",
"(",
... | Set a config value.
It's not dumped on the disk.
If the section doesn't exists the section is created | [
"Set",
"a",
"config",
"value",
".",
"It",
"s",
"not",
"dumped",
"on",
"the",
"disk",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/config.py#L224-L237 |
226,579 | GNS3/gns3-server | gns3server/config.py | Config.instance | def instance(*args, **kwargs):
"""
Singleton to return only one instance of Config.
:returns: instance of Config
"""
if not hasattr(Config, "_instance") or Config._instance is None:
Config._instance = Config(*args, **kwargs)
return Config._instance | python | def instance(*args, **kwargs):
"""
Singleton to return only one instance of Config.
:returns: instance of Config
"""
if not hasattr(Config, "_instance") or Config._instance is None:
Config._instance = Config(*args, **kwargs)
return Config._instance | [
"def",
"instance",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"hasattr",
"(",
"Config",
",",
"\"_instance\"",
")",
"or",
"Config",
".",
"_instance",
"is",
"None",
":",
"Config",
".",
"_instance",
"=",
"Config",
"(",
"*",
"args"... | Singleton to return only one instance of Config.
:returns: instance of Config | [
"Singleton",
"to",
"return",
"only",
"one",
"instance",
"of",
"Config",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/config.py#L240-L249 |
226,580 | GNS3/gns3-server | gns3server/utils/asyncio/__init__.py | wait_run_in_executor | def wait_run_in_executor(func, *args, **kwargs):
"""
Run blocking code in a different thread and wait
for the result.
:param func: Run this function in a different thread
:param args: Parameters of the function
:param kwargs: Keyword parameters of the function
:returns: Return the result of the function
"""
loop = asyncio.get_event_loop()
future = loop.run_in_executor(None, functools.partial(func, *args, **kwargs))
yield from asyncio.wait([future])
return future.result() | python | def wait_run_in_executor(func, *args, **kwargs):
"""
Run blocking code in a different thread and wait
for the result.
:param func: Run this function in a different thread
:param args: Parameters of the function
:param kwargs: Keyword parameters of the function
:returns: Return the result of the function
"""
loop = asyncio.get_event_loop()
future = loop.run_in_executor(None, functools.partial(func, *args, **kwargs))
yield from asyncio.wait([future])
return future.result() | [
"def",
"wait_run_in_executor",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"future",
"=",
"loop",
".",
"run_in_executor",
"(",
"None",
",",
"functools",
".",
"partial",
"(",
... | Run blocking code in a different thread and wait
for the result.
:param func: Run this function in a different thread
:param args: Parameters of the function
:param kwargs: Keyword parameters of the function
:returns: Return the result of the function | [
"Run",
"blocking",
"code",
"in",
"a",
"different",
"thread",
"and",
"wait",
"for",
"the",
"result",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/__init__.py#L26-L40 |
226,581 | GNS3/gns3-server | gns3server/utils/asyncio/__init__.py | subprocess_check_output | def subprocess_check_output(*args, cwd=None, env=None, stderr=False):
"""
Run a command and capture output
:param *args: List of command arguments
:param cwd: Current working directory
:param env: Command environment
:param stderr: Read on stderr
:returns: Command output
"""
if stderr:
proc = yield from asyncio.create_subprocess_exec(*args, stderr=asyncio.subprocess.PIPE, cwd=cwd, env=env)
output = yield from proc.stderr.read()
else:
proc = yield from asyncio.create_subprocess_exec(*args, stdout=asyncio.subprocess.PIPE, cwd=cwd, env=env)
output = yield from proc.stdout.read()
if output is None:
return ""
# If we received garbage we ignore invalid characters
# it should happens only when user try to use another binary
# and the code of VPCS, dynamips... Will detect it's not the correct binary
return output.decode("utf-8", errors="ignore") | python | def subprocess_check_output(*args, cwd=None, env=None, stderr=False):
"""
Run a command and capture output
:param *args: List of command arguments
:param cwd: Current working directory
:param env: Command environment
:param stderr: Read on stderr
:returns: Command output
"""
if stderr:
proc = yield from asyncio.create_subprocess_exec(*args, stderr=asyncio.subprocess.PIPE, cwd=cwd, env=env)
output = yield from proc.stderr.read()
else:
proc = yield from asyncio.create_subprocess_exec(*args, stdout=asyncio.subprocess.PIPE, cwd=cwd, env=env)
output = yield from proc.stdout.read()
if output is None:
return ""
# If we received garbage we ignore invalid characters
# it should happens only when user try to use another binary
# and the code of VPCS, dynamips... Will detect it's not the correct binary
return output.decode("utf-8", errors="ignore") | [
"def",
"subprocess_check_output",
"(",
"*",
"args",
",",
"cwd",
"=",
"None",
",",
"env",
"=",
"None",
",",
"stderr",
"=",
"False",
")",
":",
"if",
"stderr",
":",
"proc",
"=",
"yield",
"from",
"asyncio",
".",
"create_subprocess_exec",
"(",
"*",
"args",
... | Run a command and capture output
:param *args: List of command arguments
:param cwd: Current working directory
:param env: Command environment
:param stderr: Read on stderr
:returns: Command output | [
"Run",
"a",
"command",
"and",
"capture",
"output"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/__init__.py#L44-L66 |
226,582 | GNS3/gns3-server | gns3server/utils/asyncio/__init__.py | wait_for_process_termination | def wait_for_process_termination(process, timeout=10):
"""
Wait for a process terminate, and raise asyncio.TimeoutError in case of
timeout.
In theory this can be implemented by just:
yield from asyncio.wait_for(self._iou_process.wait(), timeout=100)
But it's broken before Python 3.4:
http://bugs.python.org/issue23140
:param process: An asyncio subprocess
:param timeout: Timeout in seconds
"""
if sys.version_info >= (3, 5):
try:
yield from asyncio.wait_for(process.wait(), timeout=timeout)
except ProcessLookupError:
return
else:
while timeout > 0:
if process.returncode is not None:
return
yield from asyncio.sleep(0.1)
timeout -= 0.1
raise asyncio.TimeoutError() | python | def wait_for_process_termination(process, timeout=10):
"""
Wait for a process terminate, and raise asyncio.TimeoutError in case of
timeout.
In theory this can be implemented by just:
yield from asyncio.wait_for(self._iou_process.wait(), timeout=100)
But it's broken before Python 3.4:
http://bugs.python.org/issue23140
:param process: An asyncio subprocess
:param timeout: Timeout in seconds
"""
if sys.version_info >= (3, 5):
try:
yield from asyncio.wait_for(process.wait(), timeout=timeout)
except ProcessLookupError:
return
else:
while timeout > 0:
if process.returncode is not None:
return
yield from asyncio.sleep(0.1)
timeout -= 0.1
raise asyncio.TimeoutError() | [
"def",
"wait_for_process_termination",
"(",
"process",
",",
"timeout",
"=",
"10",
")",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"5",
")",
":",
"try",
":",
"yield",
"from",
"asyncio",
".",
"wait_for",
"(",
"process",
".",
"wait",
"(",... | Wait for a process terminate, and raise asyncio.TimeoutError in case of
timeout.
In theory this can be implemented by just:
yield from asyncio.wait_for(self._iou_process.wait(), timeout=100)
But it's broken before Python 3.4:
http://bugs.python.org/issue23140
:param process: An asyncio subprocess
:param timeout: Timeout in seconds | [
"Wait",
"for",
"a",
"process",
"terminate",
"and",
"raise",
"asyncio",
".",
"TimeoutError",
"in",
"case",
"of",
"timeout",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/__init__.py#L69-L95 |
226,583 | GNS3/gns3-server | gns3server/utils/asyncio/__init__.py | locked_coroutine | def locked_coroutine(f):
"""
Method decorator that replace asyncio.coroutine that warranty
that this specific method of this class instance will not we
executed twice at the same time
"""
@asyncio.coroutine
def new_function(*args, **kwargs):
# In the instance of the class we will store
# a lock has an attribute.
lock_var_name = "__" + f.__name__ + "_lock"
if not hasattr(args[0], lock_var_name):
setattr(args[0], lock_var_name, asyncio.Lock())
with (yield from getattr(args[0], lock_var_name)):
return (yield from f(*args, **kwargs))
return new_function | python | def locked_coroutine(f):
"""
Method decorator that replace asyncio.coroutine that warranty
that this specific method of this class instance will not we
executed twice at the same time
"""
@asyncio.coroutine
def new_function(*args, **kwargs):
# In the instance of the class we will store
# a lock has an attribute.
lock_var_name = "__" + f.__name__ + "_lock"
if not hasattr(args[0], lock_var_name):
setattr(args[0], lock_var_name, asyncio.Lock())
with (yield from getattr(args[0], lock_var_name)):
return (yield from f(*args, **kwargs))
return new_function | [
"def",
"locked_coroutine",
"(",
"f",
")",
":",
"@",
"asyncio",
".",
"coroutine",
"def",
"new_function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# In the instance of the class we will store",
"# a lock has an attribute.",
"lock_var_name",
"=",
"\"__\"",... | Method decorator that replace asyncio.coroutine that warranty
that this specific method of this class instance will not we
executed twice at the same time | [
"Method",
"decorator",
"that",
"replace",
"asyncio",
".",
"coroutine",
"that",
"warranty",
"that",
"this",
"specific",
"method",
"of",
"this",
"class",
"instance",
"will",
"not",
"we",
"executed",
"twice",
"at",
"the",
"same",
"time"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/__init__.py#L142-L160 |
226,584 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/bridge.py | Bridge.set_name | def set_name(self, new_name):
"""
Renames this bridge.
:param new_name: New name for this bridge
"""
yield from self._hypervisor.send('nio_bridge rename "{name}" "{new_name}"'.format(name=self._name,
new_name=new_name))
self._name = new_name | python | def set_name(self, new_name):
"""
Renames this bridge.
:param new_name: New name for this bridge
"""
yield from self._hypervisor.send('nio_bridge rename "{name}" "{new_name}"'.format(name=self._name,
new_name=new_name))
self._name = new_name | [
"def",
"set_name",
"(",
"self",
",",
"new_name",
")",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'nio_bridge rename \"{name}\" \"{new_name}\"'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"new_name",
"=",
"new_name",
... | Renames this bridge.
:param new_name: New name for this bridge | [
"Renames",
"this",
"bridge",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/bridge.py#L55-L65 |
226,585 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/bridge.py | Bridge.delete | def delete(self):
"""
Deletes this bridge.
"""
if self._hypervisor and self in self._hypervisor.devices:
self._hypervisor.devices.remove(self)
if self._hypervisor and not self._hypervisor.devices:
yield from self._hypervisor.send('nio_bridge delete "{}"'.format(self._name)) | python | def delete(self):
"""
Deletes this bridge.
"""
if self._hypervisor and self in self._hypervisor.devices:
self._hypervisor.devices.remove(self)
if self._hypervisor and not self._hypervisor.devices:
yield from self._hypervisor.send('nio_bridge delete "{}"'.format(self._name)) | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"_hypervisor",
"and",
"self",
"in",
"self",
".",
"_hypervisor",
".",
"devices",
":",
"self",
".",
"_hypervisor",
".",
"devices",
".",
"remove",
"(",
"self",
")",
"if",
"self",
".",
"_hypervisor... | Deletes this bridge. | [
"Deletes",
"this",
"bridge",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/bridge.py#L78-L86 |
226,586 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/bridge.py | Bridge.add_nio | def add_nio(self, nio):
"""
Adds a NIO as new port on this bridge.
:param nio: NIO instance to add
"""
yield from self._hypervisor.send('nio_bridge add_nio "{name}" {nio}'.format(name=self._name, nio=nio))
self._nios.append(nio) | python | def add_nio(self, nio):
"""
Adds a NIO as new port on this bridge.
:param nio: NIO instance to add
"""
yield from self._hypervisor.send('nio_bridge add_nio "{name}" {nio}'.format(name=self._name, nio=nio))
self._nios.append(nio) | [
"def",
"add_nio",
"(",
"self",
",",
"nio",
")",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'nio_bridge add_nio \"{name}\" {nio}'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"nio",
"=",
"nio",
")",
")",
"self",
... | Adds a NIO as new port on this bridge.
:param nio: NIO instance to add | [
"Adds",
"a",
"NIO",
"as",
"new",
"port",
"on",
"this",
"bridge",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/bridge.py#L89-L97 |
226,587 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/bridge.py | Bridge.remove_nio | def remove_nio(self, nio):
"""
Removes the specified NIO as member of this bridge.
:param nio: NIO instance to remove
"""
if self._hypervisor:
yield from self._hypervisor.send('nio_bridge remove_nio "{name}" {nio}'.format(name=self._name, nio=nio))
self._nios.remove(nio) | python | def remove_nio(self, nio):
"""
Removes the specified NIO as member of this bridge.
:param nio: NIO instance to remove
"""
if self._hypervisor:
yield from self._hypervisor.send('nio_bridge remove_nio "{name}" {nio}'.format(name=self._name, nio=nio))
self._nios.remove(nio) | [
"def",
"remove_nio",
"(",
"self",
",",
"nio",
")",
":",
"if",
"self",
".",
"_hypervisor",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'nio_bridge remove_nio \"{name}\" {nio}'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
... | Removes the specified NIO as member of this bridge.
:param nio: NIO instance to remove | [
"Removes",
"the",
"specified",
"NIO",
"as",
"member",
"of",
"this",
"bridge",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/bridge.py#L100-L108 |
226,588 | GNS3/gns3-server | gns3server/controller/import_project.py | _move_node_file | def _move_node_file(path, old_id, new_id):
"""
Move the files from a node when changing his id
:param path: Path of the project
:param old_id: ID before change
:param new_id: New node UUID
"""
root = os.path.join(path, "project-files")
if os.path.exists(root):
for dirname in os.listdir(root):
module_dir = os.path.join(root, dirname)
if os.path.isdir(module_dir):
node_dir = os.path.join(module_dir, old_id)
if os.path.exists(node_dir):
shutil.move(node_dir, os.path.join(module_dir, new_id)) | python | def _move_node_file(path, old_id, new_id):
"""
Move the files from a node when changing his id
:param path: Path of the project
:param old_id: ID before change
:param new_id: New node UUID
"""
root = os.path.join(path, "project-files")
if os.path.exists(root):
for dirname in os.listdir(root):
module_dir = os.path.join(root, dirname)
if os.path.isdir(module_dir):
node_dir = os.path.join(module_dir, old_id)
if os.path.exists(node_dir):
shutil.move(node_dir, os.path.join(module_dir, new_id)) | [
"def",
"_move_node_file",
"(",
"path",
",",
"old_id",
",",
"new_id",
")",
":",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"project-files\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"root",
")",
":",
"for",
"dirname",
... | Move the files from a node when changing his id
:param path: Path of the project
:param old_id: ID before change
:param new_id: New node UUID | [
"Move",
"the",
"files",
"from",
"a",
"node",
"when",
"changing",
"his",
"id"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/import_project.py#L157-L172 |
226,589 | GNS3/gns3-server | gns3server/controller/import_project.py | _move_files_to_compute | def _move_files_to_compute(compute, project_id, directory, files_path):
"""
Move the files to a remote compute
"""
location = os.path.join(directory, files_path)
if os.path.exists(location):
for (dirpath, dirnames, filenames) in os.walk(location):
for filename in filenames:
path = os.path.join(dirpath, filename)
dst = os.path.relpath(path, directory)
yield from _upload_file(compute, project_id, path, dst)
shutil.rmtree(os.path.join(directory, files_path)) | python | def _move_files_to_compute(compute, project_id, directory, files_path):
"""
Move the files to a remote compute
"""
location = os.path.join(directory, files_path)
if os.path.exists(location):
for (dirpath, dirnames, filenames) in os.walk(location):
for filename in filenames:
path = os.path.join(dirpath, filename)
dst = os.path.relpath(path, directory)
yield from _upload_file(compute, project_id, path, dst)
shutil.rmtree(os.path.join(directory, files_path)) | [
"def",
"_move_files_to_compute",
"(",
"compute",
",",
"project_id",
",",
"directory",
",",
"files_path",
")",
":",
"location",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"files_path",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"lo... | Move the files to a remote compute | [
"Move",
"the",
"files",
"to",
"a",
"remote",
"compute"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/import_project.py#L176-L187 |
226,590 | GNS3/gns3-server | gns3server/controller/import_project.py | _upload_file | def _upload_file(compute, project_id, file_path, path):
"""
Upload a file to a remote project
:param file_path: File path on the controller file system
:param path: File path on the remote system relative to project directory
"""
path = "/projects/{}/files/{}".format(project_id, path.replace("\\", "/"))
with open(file_path, "rb") as f:
yield from compute.http_query("POST", path, f, timeout=None) | python | def _upload_file(compute, project_id, file_path, path):
"""
Upload a file to a remote project
:param file_path: File path on the controller file system
:param path: File path on the remote system relative to project directory
"""
path = "/projects/{}/files/{}".format(project_id, path.replace("\\", "/"))
with open(file_path, "rb") as f:
yield from compute.http_query("POST", path, f, timeout=None) | [
"def",
"_upload_file",
"(",
"compute",
",",
"project_id",
",",
"file_path",
",",
"path",
")",
":",
"path",
"=",
"\"/projects/{}/files/{}\"",
".",
"format",
"(",
"project_id",
",",
"path",
".",
"replace",
"(",
"\"\\\\\"",
",",
"\"/\"",
")",
")",
"with",
"op... | Upload a file to a remote project
:param file_path: File path on the controller file system
:param path: File path on the remote system relative to project directory | [
"Upload",
"a",
"file",
"to",
"a",
"remote",
"project"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/import_project.py#L191-L200 |
226,591 | GNS3/gns3-server | gns3server/controller/import_project.py | _import_images | def _import_images(controller, path):
"""
Copy images to the images directory or delete them if they
already exists.
"""
image_dir = controller.images_path()
root = os.path.join(path, "images")
for (dirpath, dirnames, filenames) in os.walk(root):
for filename in filenames:
path = os.path.join(dirpath, filename)
dst = os.path.join(image_dir, os.path.relpath(path, root))
os.makedirs(os.path.dirname(dst), exist_ok=True)
shutil.move(path, dst) | python | def _import_images(controller, path):
"""
Copy images to the images directory or delete them if they
already exists.
"""
image_dir = controller.images_path()
root = os.path.join(path, "images")
for (dirpath, dirnames, filenames) in os.walk(root):
for filename in filenames:
path = os.path.join(dirpath, filename)
dst = os.path.join(image_dir, os.path.relpath(path, root))
os.makedirs(os.path.dirname(dst), exist_ok=True)
shutil.move(path, dst) | [
"def",
"_import_images",
"(",
"controller",
",",
"path",
")",
":",
"image_dir",
"=",
"controller",
".",
"images_path",
"(",
")",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"images\"",
")",
"for",
"(",
"dirpath",
",",
"dirnames",
"... | Copy images to the images directory or delete them if they
already exists. | [
"Copy",
"images",
"to",
"the",
"images",
"directory",
"or",
"delete",
"them",
"if",
"they",
"already",
"exists",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/import_project.py#L203-L216 |
226,592 | GNS3/gns3-server | gns3server/utils/windows_loopback.py | parse_add_loopback | def parse_add_loopback():
"""
Validate params when adding a loopback adapter
"""
class Add(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
try:
ipaddress.IPv4Interface("{}/{}".format(values[1], values[2]))
except ipaddress.AddressValueError as e:
raise argparse.ArgumentTypeError("Invalid IP address: {}".format(e))
except ipaddress.NetmaskValueError as e:
raise argparse.ArgumentTypeError("Invalid subnet mask: {}".format(e))
setattr(args, self.dest, values)
return Add | python | def parse_add_loopback():
"""
Validate params when adding a loopback adapter
"""
class Add(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
try:
ipaddress.IPv4Interface("{}/{}".format(values[1], values[2]))
except ipaddress.AddressValueError as e:
raise argparse.ArgumentTypeError("Invalid IP address: {}".format(e))
except ipaddress.NetmaskValueError as e:
raise argparse.ArgumentTypeError("Invalid subnet mask: {}".format(e))
setattr(args, self.dest, values)
return Add | [
"def",
"parse_add_loopback",
"(",
")",
":",
"class",
"Add",
"(",
"argparse",
".",
"Action",
")",
":",
"def",
"__call__",
"(",
"self",
",",
"parser",
",",
"args",
",",
"values",
",",
"option_string",
"=",
"None",
")",
":",
"try",
":",
"ipaddress",
".",
... | Validate params when adding a loopback adapter | [
"Validate",
"params",
"when",
"adding",
"a",
"loopback",
"adapter"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/windows_loopback.py#L31-L46 |
226,593 | GNS3/gns3-server | gns3server/utils/windows_loopback.py | main | def main():
"""
Entry point for the Windows loopback tool.
"""
parser = argparse.ArgumentParser(description='%(prog)s add/remove Windows loopback adapters')
parser.add_argument('-a', "--add", nargs=3, action=parse_add_loopback(), help="add a Windows loopback adapter")
parser.add_argument("-r", "--remove", action="store", help="remove a Windows loopback adapter")
try:
args = parser.parse_args()
except argparse.ArgumentTypeError as e:
raise SystemExit(e)
# devcon is required to install/remove Windows loopback adapters
devcon_path = shutil.which("devcon")
if not devcon_path:
raise SystemExit("Could not find devcon.exe")
from win32com.shell import shell
if not shell.IsUserAnAdmin():
raise SystemExit("You must run this script as an administrator")
try:
if args.add:
add_loopback(devcon_path, args.add[0], args.add[1], args.add[2])
if args.remove:
remove_loopback(devcon_path, args.remove)
except SystemExit as e:
print(e)
os.system("pause") | python | def main():
"""
Entry point for the Windows loopback tool.
"""
parser = argparse.ArgumentParser(description='%(prog)s add/remove Windows loopback adapters')
parser.add_argument('-a', "--add", nargs=3, action=parse_add_loopback(), help="add a Windows loopback adapter")
parser.add_argument("-r", "--remove", action="store", help="remove a Windows loopback adapter")
try:
args = parser.parse_args()
except argparse.ArgumentTypeError as e:
raise SystemExit(e)
# devcon is required to install/remove Windows loopback adapters
devcon_path = shutil.which("devcon")
if not devcon_path:
raise SystemExit("Could not find devcon.exe")
from win32com.shell import shell
if not shell.IsUserAnAdmin():
raise SystemExit("You must run this script as an administrator")
try:
if args.add:
add_loopback(devcon_path, args.add[0], args.add[1], args.add[2])
if args.remove:
remove_loopback(devcon_path, args.remove)
except SystemExit as e:
print(e)
os.system("pause") | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'%(prog)s add/remove Windows loopback adapters'",
")",
"parser",
".",
"add_argument",
"(",
"'-a'",
",",
"\"--add\"",
",",
"nargs",
"=",
"3",
",",
"action",
... | Entry point for the Windows loopback tool. | [
"Entry",
"point",
"for",
"the",
"Windows",
"loopback",
"tool",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/windows_loopback.py#L105-L134 |
226,594 | GNS3/gns3-server | gns3server/utils/picture.py | _svg_convert_size | def _svg_convert_size(size):
"""
Convert svg size to the px version
:param size: String with the size
"""
# https://www.w3.org/TR/SVG/coords.html#Units
conversion_table = {
"pt": 1.25,
"pc": 15,
"mm": 3.543307,
"cm": 35.43307,
"in": 90,
"px": 1
}
if len(size) > 3:
if size[-2:] in conversion_table:
return round(float(size[:-2]) * conversion_table[size[-2:]])
return round(float(size)) | python | def _svg_convert_size(size):
"""
Convert svg size to the px version
:param size: String with the size
"""
# https://www.w3.org/TR/SVG/coords.html#Units
conversion_table = {
"pt": 1.25,
"pc": 15,
"mm": 3.543307,
"cm": 35.43307,
"in": 90,
"px": 1
}
if len(size) > 3:
if size[-2:] in conversion_table:
return round(float(size[:-2]) * conversion_table[size[-2:]])
return round(float(size)) | [
"def",
"_svg_convert_size",
"(",
"size",
")",
":",
"# https://www.w3.org/TR/SVG/coords.html#Units",
"conversion_table",
"=",
"{",
"\"pt\"",
":",
"1.25",
",",
"\"pc\"",
":",
"15",
",",
"\"mm\"",
":",
"3.543307",
",",
"\"cm\"",
":",
"35.43307",
",",
"\"in\"",
":",... | Convert svg size to the px version
:param size: String with the size | [
"Convert",
"svg",
"size",
"to",
"the",
"px",
"version"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/picture.py#L114-L134 |
226,595 | GNS3/gns3-server | gns3server/utils/images.py | list_images | def list_images(type):
"""
Scan directories for available image for a type
:param type: emulator type (dynamips, qemu, iou)
"""
files = set()
images = []
server_config = Config.instance().get_section_config("Server")
general_images_directory = os.path.expanduser(server_config.get("images_path", "~/GNS3/images"))
# Subfolder of the general_images_directory specific to this VM type
default_directory = default_images_directory(type)
for directory in images_directories(type):
# We limit recursion to path outside the default images directory
# the reason is in the default directory manage file organization and
# it should be flatten to keep things simple
recurse = True
if os.path.commonprefix([directory, general_images_directory]) == general_images_directory:
recurse = False
directory = os.path.normpath(directory)
for root, _, filenames in _os_walk(directory, recurse=recurse):
for filename in filenames:
path = os.path.join(root, filename)
if filename not in files:
if filename.endswith(".md5sum") or filename.startswith("."):
continue
elif ((filename.endswith(".image") or filename.endswith(".bin")) and type == "dynamips") \
or ((filename.endswith(".bin") or filename.startswith("i86bi")) and type == "iou") \
or (not filename.endswith(".bin") and not filename.endswith(".image") and type == "qemu"):
files.add(filename)
# It the image is located in the standard directory the path is relative
if os.path.commonprefix([root, default_directory]) != default_directory:
path = os.path.join(root, filename)
else:
path = os.path.relpath(os.path.join(root, filename), default_directory)
try:
if type in ["dynamips", "iou"]:
with open(os.path.join(root, filename), "rb") as f:
# read the first 7 bytes of the file.
elf_header_start = f.read(7)
# valid IOS images must start with the ELF magic number, be 32-bit, big endian and have an ELF version of 1
if not elf_header_start == b'\x7fELF\x01\x02\x01' and not elf_header_start == b'\x7fELF\x01\x01\x01':
continue
images.append({
"filename": filename,
"path": force_unix_path(path),
"md5sum": md5sum(os.path.join(root, filename)),
"filesize": os.stat(os.path.join(root, filename)).st_size})
except OSError as e:
log.warn("Can't add image {}: {}".format(path, str(e)))
return images | python | def list_images(type):
"""
Scan directories for available image for a type
:param type: emulator type (dynamips, qemu, iou)
"""
files = set()
images = []
server_config = Config.instance().get_section_config("Server")
general_images_directory = os.path.expanduser(server_config.get("images_path", "~/GNS3/images"))
# Subfolder of the general_images_directory specific to this VM type
default_directory = default_images_directory(type)
for directory in images_directories(type):
# We limit recursion to path outside the default images directory
# the reason is in the default directory manage file organization and
# it should be flatten to keep things simple
recurse = True
if os.path.commonprefix([directory, general_images_directory]) == general_images_directory:
recurse = False
directory = os.path.normpath(directory)
for root, _, filenames in _os_walk(directory, recurse=recurse):
for filename in filenames:
path = os.path.join(root, filename)
if filename not in files:
if filename.endswith(".md5sum") or filename.startswith("."):
continue
elif ((filename.endswith(".image") or filename.endswith(".bin")) and type == "dynamips") \
or ((filename.endswith(".bin") or filename.startswith("i86bi")) and type == "iou") \
or (not filename.endswith(".bin") and not filename.endswith(".image") and type == "qemu"):
files.add(filename)
# It the image is located in the standard directory the path is relative
if os.path.commonprefix([root, default_directory]) != default_directory:
path = os.path.join(root, filename)
else:
path = os.path.relpath(os.path.join(root, filename), default_directory)
try:
if type in ["dynamips", "iou"]:
with open(os.path.join(root, filename), "rb") as f:
# read the first 7 bytes of the file.
elf_header_start = f.read(7)
# valid IOS images must start with the ELF magic number, be 32-bit, big endian and have an ELF version of 1
if not elf_header_start == b'\x7fELF\x01\x02\x01' and not elf_header_start == b'\x7fELF\x01\x01\x01':
continue
images.append({
"filename": filename,
"path": force_unix_path(path),
"md5sum": md5sum(os.path.join(root, filename)),
"filesize": os.stat(os.path.join(root, filename)).st_size})
except OSError as e:
log.warn("Can't add image {}: {}".format(path, str(e)))
return images | [
"def",
"list_images",
"(",
"type",
")",
":",
"files",
"=",
"set",
"(",
")",
"images",
"=",
"[",
"]",
"server_config",
"=",
"Config",
".",
"instance",
"(",
")",
".",
"get_section_config",
"(",
"\"Server\"",
")",
"general_images_directory",
"=",
"os",
".",
... | Scan directories for available image for a type
:param type: emulator type (dynamips, qemu, iou) | [
"Scan",
"directories",
"for",
"available",
"image",
"for",
"a",
"type"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/images.py#L29-L87 |
226,596 | GNS3/gns3-server | gns3server/utils/images.py | _os_walk | def _os_walk(directory, recurse=True, **kwargs):
"""
Work like os.walk but if recurse is False just list current directory
"""
if recurse:
for root, dirs, files in os.walk(directory, **kwargs):
yield root, dirs, files
else:
files = []
for filename in os.listdir(directory):
if os.path.isfile(os.path.join(directory, filename)):
files.append(filename)
yield directory, [], files | python | def _os_walk(directory, recurse=True, **kwargs):
"""
Work like os.walk but if recurse is False just list current directory
"""
if recurse:
for root, dirs, files in os.walk(directory, **kwargs):
yield root, dirs, files
else:
files = []
for filename in os.listdir(directory):
if os.path.isfile(os.path.join(directory, filename)):
files.append(filename)
yield directory, [], files | [
"def",
"_os_walk",
"(",
"directory",
",",
"recurse",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"recurse",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"directory",
",",
"*",
"*",
"kwargs",
")",
":",
"yi... | Work like os.walk but if recurse is False just list current directory | [
"Work",
"like",
"os",
".",
"walk",
"but",
"if",
"recurse",
"is",
"False",
"just",
"list",
"current",
"directory"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/images.py#L90-L102 |
226,597 | GNS3/gns3-server | gns3server/utils/images.py | images_directories | def images_directories(type):
"""
Return all directory where we will look for images
by priority
:param type: Type of emulator
"""
server_config = Config.instance().get_section_config("Server")
paths = []
img_dir = os.path.expanduser(server_config.get("images_path", "~/GNS3/images"))
type_img_directory = default_images_directory(type)
try:
os.makedirs(type_img_directory, exist_ok=True)
paths.append(type_img_directory)
except (OSError, PermissionError):
pass
for directory in server_config.get("additional_images_path", "").split(";"):
paths.append(directory)
# Compatibility with old topologies we look in parent directory
paths.append(img_dir)
# Return only the existings paths
return [force_unix_path(p) for p in paths if os.path.exists(p)] | python | def images_directories(type):
"""
Return all directory where we will look for images
by priority
:param type: Type of emulator
"""
server_config = Config.instance().get_section_config("Server")
paths = []
img_dir = os.path.expanduser(server_config.get("images_path", "~/GNS3/images"))
type_img_directory = default_images_directory(type)
try:
os.makedirs(type_img_directory, exist_ok=True)
paths.append(type_img_directory)
except (OSError, PermissionError):
pass
for directory in server_config.get("additional_images_path", "").split(";"):
paths.append(directory)
# Compatibility with old topologies we look in parent directory
paths.append(img_dir)
# Return only the existings paths
return [force_unix_path(p) for p in paths if os.path.exists(p)] | [
"def",
"images_directories",
"(",
"type",
")",
":",
"server_config",
"=",
"Config",
".",
"instance",
"(",
")",
".",
"get_section_config",
"(",
"\"Server\"",
")",
"paths",
"=",
"[",
"]",
"img_dir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"server_con... | Return all directory where we will look for images
by priority
:param type: Type of emulator | [
"Return",
"all",
"directory",
"where",
"we",
"will",
"look",
"for",
"images",
"by",
"priority"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/images.py#L121-L143 |
226,598 | GNS3/gns3-server | gns3server/utils/images.py | md5sum | def md5sum(path):
"""
Return the md5sum of an image and cache it on disk
:param path: Path to the image
:returns: Digest of the image
"""
if path is None or len(path) == 0 or not os.path.exists(path):
return None
try:
with open(path + '.md5sum') as f:
md5 = f.read()
if len(md5) == 32:
return md5
# Unicode error is when user rename an image to .md5sum ....
except (OSError, UnicodeDecodeError):
pass
try:
m = hashlib.md5()
with open(path, 'rb') as f:
while True:
buf = f.read(128)
if not buf:
break
m.update(buf)
digest = m.hexdigest()
except OSError as e:
log.error("Can't create digest of %s: %s", path, str(e))
return None
try:
with open('{}.md5sum'.format(path), 'w+') as f:
f.write(digest)
except OSError as e:
log.error("Can't write digest of %s: %s", path, str(e))
return digest | python | def md5sum(path):
"""
Return the md5sum of an image and cache it on disk
:param path: Path to the image
:returns: Digest of the image
"""
if path is None or len(path) == 0 or not os.path.exists(path):
return None
try:
with open(path + '.md5sum') as f:
md5 = f.read()
if len(md5) == 32:
return md5
# Unicode error is when user rename an image to .md5sum ....
except (OSError, UnicodeDecodeError):
pass
try:
m = hashlib.md5()
with open(path, 'rb') as f:
while True:
buf = f.read(128)
if not buf:
break
m.update(buf)
digest = m.hexdigest()
except OSError as e:
log.error("Can't create digest of %s: %s", path, str(e))
return None
try:
with open('{}.md5sum'.format(path), 'w+') as f:
f.write(digest)
except OSError as e:
log.error("Can't write digest of %s: %s", path, str(e))
return digest | [
"def",
"md5sum",
"(",
"path",
")",
":",
"if",
"path",
"is",
"None",
"or",
"len",
"(",
"path",
")",
"==",
"0",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"None",
"try",
":",
"with",
"open",
"(",
"path",
"+",
... | Return the md5sum of an image and cache it on disk
:param path: Path to the image
:returns: Digest of the image | [
"Return",
"the",
"md5sum",
"of",
"an",
"image",
"and",
"cache",
"it",
"on",
"disk"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/images.py#L146-L185 |
226,599 | GNS3/gns3-server | gns3server/utils/images.py | remove_checksum | def remove_checksum(path):
"""
Remove the checksum of an image from cache if exists
"""
path = '{}.md5sum'.format(path)
if os.path.exists(path):
os.remove(path) | python | def remove_checksum(path):
"""
Remove the checksum of an image from cache if exists
"""
path = '{}.md5sum'.format(path)
if os.path.exists(path):
os.remove(path) | [
"def",
"remove_checksum",
"(",
"path",
")",
":",
"path",
"=",
"'{}.md5sum'",
".",
"format",
"(",
"path",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"remove",
"(",
"path",
")"
] | Remove the checksum of an image from cache if exists | [
"Remove",
"the",
"checksum",
"of",
"an",
"image",
"from",
"cache",
"if",
"exists"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/images.py#L188-L195 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.