repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
GNS3/gns3-server
gns3server/compute/vpcs/vpcs_vm.py
VPCSVM._vpcs_path
def _vpcs_path(self): """ Returns the VPCS executable path. :returns: path to VPCS """ search_path = self._manager.config.get_section_config("VPCS").get("vpcs_path", "vpcs") path = shutil.which(search_path) # shutil.which return None if the path doesn't exists if not path: return search_path return path
python
def _vpcs_path(self): """ Returns the VPCS executable path. :returns: path to VPCS """ search_path = self._manager.config.get_section_config("VPCS").get("vpcs_path", "vpcs") path = shutil.which(search_path) # shutil.which return None if the path doesn't exists if not path: return search_path return path
[ "def", "_vpcs_path", "(", "self", ")", ":", "search_path", "=", "self", ".", "_manager", ".", "config", ".", "get_section_config", "(", "\"VPCS\"", ")", ".", "get", "(", "\"vpcs_path\"", ",", "\"vpcs\"", ")", "path", "=", "shutil", ".", "which", "(", "se...
Returns the VPCS executable path. :returns: path to VPCS
[ "Returns", "the", "VPCS", "executable", "path", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L137-L149
train
221,200
GNS3/gns3-server
gns3server/compute/vpcs/vpcs_vm.py
VPCSVM.name
def name(self, new_name): """ Sets the name of this VPCS VM. :param new_name: name """ if self.script_file: content = self.startup_script content = content.replace(self._name, new_name) escaped_name = new_name.replace('\\', '') content = re.sub(r"^set pcname .+$", "set pcname " + escaped_name, content, flags=re.MULTILINE) self.startup_script = content super(VPCSVM, VPCSVM).name.__set__(self, new_name)
python
def name(self, new_name): """ Sets the name of this VPCS VM. :param new_name: name """ if self.script_file: content = self.startup_script content = content.replace(self._name, new_name) escaped_name = new_name.replace('\\', '') content = re.sub(r"^set pcname .+$", "set pcname " + escaped_name, content, flags=re.MULTILINE) self.startup_script = content super(VPCSVM, VPCSVM).name.__set__(self, new_name)
[ "def", "name", "(", "self", ",", "new_name", ")", ":", "if", "self", ".", "script_file", ":", "content", "=", "self", ".", "startup_script", "content", "=", "content", ".", "replace", "(", "self", ".", "_name", ",", "new_name", ")", "escaped_name", "=", ...
Sets the name of this VPCS VM. :param new_name: name
[ "Sets", "the", "name", "of", "this", "VPCS", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L152-L166
train
221,201
GNS3/gns3-server
gns3server/compute/vpcs/vpcs_vm.py
VPCSVM.startup_script
def startup_script(self): """ Returns the content of the current startup script """ script_file = self.script_file if script_file is None: return None try: with open(script_file, "rb") as f: return f.read().decode("utf-8", errors="replace") except OSError as e: raise VPCSError('Cannot read the startup script file "{}": {}'.format(script_file, e))
python
def startup_script(self): """ Returns the content of the current startup script """ script_file = self.script_file if script_file is None: return None try: with open(script_file, "rb") as f: return f.read().decode("utf-8", errors="replace") except OSError as e: raise VPCSError('Cannot read the startup script file "{}": {}'.format(script_file, e))
[ "def", "startup_script", "(", "self", ")", ":", "script_file", "=", "self", ".", "script_file", "if", "script_file", "is", "None", ":", "return", "None", "try", ":", "with", "open", "(", "script_file", ",", "\"rb\"", ")", "as", "f", ":", "return", "f", ...
Returns the content of the current startup script
[ "Returns", "the", "content", "of", "the", "current", "startup", "script" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L169-L182
train
221,202
GNS3/gns3-server
gns3server/compute/vpcs/vpcs_vm.py
VPCSVM.startup_script
def startup_script(self, startup_script): """ Updates the startup script. :param startup_script: content of the startup script """ try: startup_script_path = os.path.join(self.working_dir, 'startup.vpc') with open(startup_script_path, "w+", encoding='utf-8') as f: if startup_script is None: f.write('') else: startup_script = startup_script.replace("%h", self._name) f.write(startup_script) except OSError as e: raise VPCSError('Cannot write the startup script file "{}": {}'.format(startup_script_path, e))
python
def startup_script(self, startup_script): """ Updates the startup script. :param startup_script: content of the startup script """ try: startup_script_path = os.path.join(self.working_dir, 'startup.vpc') with open(startup_script_path, "w+", encoding='utf-8') as f: if startup_script is None: f.write('') else: startup_script = startup_script.replace("%h", self._name) f.write(startup_script) except OSError as e: raise VPCSError('Cannot write the startup script file "{}": {}'.format(startup_script_path, e))
[ "def", "startup_script", "(", "self", ",", "startup_script", ")", ":", "try", ":", "startup_script_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "working_dir", ",", "'startup.vpc'", ")", "with", "open", "(", "startup_script_path", ",", "\"w+\...
Updates the startup script. :param startup_script: content of the startup script
[ "Updates", "the", "startup", "script", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L185-L201
train
221,203
GNS3/gns3-server
gns3server/compute/vpcs/vpcs_vm.py
VPCSVM._check_vpcs_version
def _check_vpcs_version(self): """ Checks if the VPCS executable version is >= 0.8b or == 0.6.1. """ try: output = yield from subprocess_check_output(self._vpcs_path(), "-v", cwd=self.working_dir) match = re.search("Welcome to Virtual PC Simulator, version ([0-9a-z\.]+)", output) if match: version = match.group(1) self._vpcs_version = parse_version(version) if self._vpcs_version < parse_version("0.6.1"): raise VPCSError("VPCS executable version must be >= 0.6.1 but not a 0.8") else: raise VPCSError("Could not determine the VPCS version for {}".format(self._vpcs_path())) except (OSError, subprocess.SubprocessError) as e: raise VPCSError("Error while looking for the VPCS version: {}".format(e))
python
def _check_vpcs_version(self): """ Checks if the VPCS executable version is >= 0.8b or == 0.6.1. """ try: output = yield from subprocess_check_output(self._vpcs_path(), "-v", cwd=self.working_dir) match = re.search("Welcome to Virtual PC Simulator, version ([0-9a-z\.]+)", output) if match: version = match.group(1) self._vpcs_version = parse_version(version) if self._vpcs_version < parse_version("0.6.1"): raise VPCSError("VPCS executable version must be >= 0.6.1 but not a 0.8") else: raise VPCSError("Could not determine the VPCS version for {}".format(self._vpcs_path())) except (OSError, subprocess.SubprocessError) as e: raise VPCSError("Error while looking for the VPCS version: {}".format(e))
[ "def", "_check_vpcs_version", "(", "self", ")", ":", "try", ":", "output", "=", "yield", "from", "subprocess_check_output", "(", "self", ".", "_vpcs_path", "(", ")", ",", "\"-v\"", ",", "cwd", "=", "self", ".", "working_dir", ")", "match", "=", "re", "."...
Checks if the VPCS executable version is >= 0.8b or == 0.6.1.
[ "Checks", "if", "the", "VPCS", "executable", "version", "is", ">", "=", "0", ".", "8b", "or", "==", "0", ".", "6", ".", "1", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L204-L219
train
221,204
GNS3/gns3-server
gns3server/compute/vpcs/vpcs_vm.py
VPCSVM.start
def start(self): """ Starts the VPCS process. """ yield from self._check_requirements() if not self.is_running(): nio = self._ethernet_adapter.get_nio(0) command = self._build_command() try: log.info("Starting VPCS: {}".format(command)) self._vpcs_stdout_file = os.path.join(self.working_dir, "vpcs.log") log.info("Logging to {}".format(self._vpcs_stdout_file)) flags = 0 if sys.platform.startswith("win32"): flags = subprocess.CREATE_NEW_PROCESS_GROUP with open(self._vpcs_stdout_file, "w", encoding="utf-8") as fd: self.command_line = ' '.join(command) self._process = yield from asyncio.create_subprocess_exec(*command, stdout=fd, stderr=subprocess.STDOUT, cwd=self.working_dir, creationflags=flags) monitor_process(self._process, self._termination_callback) yield from self._start_ubridge() if nio: yield from self.add_ubridge_udp_connection("VPCS-{}".format(self._id), self._local_udp_tunnel[1], nio) yield from self.start_wrap_console() log.info("VPCS instance {} started PID={}".format(self.name, self._process.pid)) self._started = True self.status = "started" except (OSError, subprocess.SubprocessError) as e: vpcs_stdout = self.read_vpcs_stdout() log.error("Could not start VPCS {}: {}\n{}".format(self._vpcs_path(), e, vpcs_stdout)) raise VPCSError("Could not start VPCS {}: {}\n{}".format(self._vpcs_path(), e, vpcs_stdout))
python
def start(self): """ Starts the VPCS process. """ yield from self._check_requirements() if not self.is_running(): nio = self._ethernet_adapter.get_nio(0) command = self._build_command() try: log.info("Starting VPCS: {}".format(command)) self._vpcs_stdout_file = os.path.join(self.working_dir, "vpcs.log") log.info("Logging to {}".format(self._vpcs_stdout_file)) flags = 0 if sys.platform.startswith("win32"): flags = subprocess.CREATE_NEW_PROCESS_GROUP with open(self._vpcs_stdout_file, "w", encoding="utf-8") as fd: self.command_line = ' '.join(command) self._process = yield from asyncio.create_subprocess_exec(*command, stdout=fd, stderr=subprocess.STDOUT, cwd=self.working_dir, creationflags=flags) monitor_process(self._process, self._termination_callback) yield from self._start_ubridge() if nio: yield from self.add_ubridge_udp_connection("VPCS-{}".format(self._id), self._local_udp_tunnel[1], nio) yield from self.start_wrap_console() log.info("VPCS instance {} started PID={}".format(self.name, self._process.pid)) self._started = True self.status = "started" except (OSError, subprocess.SubprocessError) as e: vpcs_stdout = self.read_vpcs_stdout() log.error("Could not start VPCS {}: {}\n{}".format(self._vpcs_path(), e, vpcs_stdout)) raise VPCSError("Could not start VPCS {}: {}\n{}".format(self._vpcs_path(), e, vpcs_stdout))
[ "def", "start", "(", "self", ")", ":", "yield", "from", "self", ".", "_check_requirements", "(", ")", "if", "not", "self", ".", "is_running", "(", ")", ":", "nio", "=", "self", ".", "_ethernet_adapter", ".", "get_nio", "(", "0", ")", "command", "=", ...
Starts the VPCS process.
[ "Starts", "the", "VPCS", "process", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L222-L259
train
221,205
GNS3/gns3-server
gns3server/compute/vpcs/vpcs_vm.py
VPCSVM.stop
def stop(self): """ Stops the VPCS process. """ yield from self._stop_ubridge() if self.is_running(): self._terminate_process() if self._process.returncode is None: try: yield from wait_for_process_termination(self._process, timeout=3) except asyncio.TimeoutError: if self._process.returncode is None: try: self._process.kill() except OSError as e: log.error("Cannot stop the VPCS process: {}".format(e)) if self._process.returncode is None: log.warn('VPCS VM "{}" with PID={} is still running'.format(self._name, self._process.pid)) self._process = None self._started = False yield from super().stop()
python
def stop(self): """ Stops the VPCS process. """ yield from self._stop_ubridge() if self.is_running(): self._terminate_process() if self._process.returncode is None: try: yield from wait_for_process_termination(self._process, timeout=3) except asyncio.TimeoutError: if self._process.returncode is None: try: self._process.kill() except OSError as e: log.error("Cannot stop the VPCS process: {}".format(e)) if self._process.returncode is None: log.warn('VPCS VM "{}" with PID={} is still running'.format(self._name, self._process.pid)) self._process = None self._started = False yield from super().stop()
[ "def", "stop", "(", "self", ")", ":", "yield", "from", "self", ".", "_stop_ubridge", "(", ")", "if", "self", ".", "is_running", "(", ")", ":", "self", ".", "_terminate_process", "(", ")", "if", "self", ".", "_process", ".", "returncode", "is", "None", ...
Stops the VPCS process.
[ "Stops", "the", "VPCS", "process", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L276-L298
train
221,206
GNS3/gns3-server
gns3server/compute/vpcs/vpcs_vm.py
VPCSVM._terminate_process
def _terminate_process(self): """ Terminate the process if running """ log.info("Stopping VPCS instance {} PID={}".format(self.name, self._process.pid)) if sys.platform.startswith("win32"): self._process.send_signal(signal.CTRL_BREAK_EVENT) else: try: self._process.terminate() # Sometime the process may already be dead when we garbage collect except ProcessLookupError: pass
python
def _terminate_process(self): """ Terminate the process if running """ log.info("Stopping VPCS instance {} PID={}".format(self.name, self._process.pid)) if sys.platform.startswith("win32"): self._process.send_signal(signal.CTRL_BREAK_EVENT) else: try: self._process.terminate() # Sometime the process may already be dead when we garbage collect except ProcessLookupError: pass
[ "def", "_terminate_process", "(", "self", ")", ":", "log", ".", "info", "(", "\"Stopping VPCS instance {} PID={}\"", ".", "format", "(", "self", ".", "name", ",", "self", ".", "_process", ".", "pid", ")", ")", "if", "sys", ".", "platform", ".", "startswith...
Terminate the process if running
[ "Terminate", "the", "process", "if", "running" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L309-L322
train
221,207
GNS3/gns3-server
gns3server/compute/vpcs/vpcs_vm.py
VPCSVM.read_vpcs_stdout
def read_vpcs_stdout(self): """ Reads the standard output of the VPCS process. Only use when the process has been stopped or has crashed. """ output = "" if self._vpcs_stdout_file: try: with open(self._vpcs_stdout_file, "rb") as file: output = file.read().decode("utf-8", errors="replace") except OSError as e: log.warn("Could not read {}: {}".format(self._vpcs_stdout_file, e)) return output
python
def read_vpcs_stdout(self): """ Reads the standard output of the VPCS process. Only use when the process has been stopped or has crashed. """ output = "" if self._vpcs_stdout_file: try: with open(self._vpcs_stdout_file, "rb") as file: output = file.read().decode("utf-8", errors="replace") except OSError as e: log.warn("Could not read {}: {}".format(self._vpcs_stdout_file, e)) return output
[ "def", "read_vpcs_stdout", "(", "self", ")", ":", "output", "=", "\"\"", "if", "self", ".", "_vpcs_stdout_file", ":", "try", ":", "with", "open", "(", "self", ".", "_vpcs_stdout_file", ",", "\"rb\"", ")", "as", "file", ":", "output", "=", "file", ".", ...
Reads the standard output of the VPCS process. Only use when the process has been stopped or has crashed.
[ "Reads", "the", "standard", "output", "of", "the", "VPCS", "process", ".", "Only", "use", "when", "the", "process", "has", "been", "stopped", "or", "has", "crashed", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L324-L337
train
221,208
GNS3/gns3-server
gns3server/compute/vpcs/vpcs_vm.py
VPCSVM.script_file
def script_file(self): """ Returns the startup script file for this VPCS VM. :returns: path to startup script file """ # use the default VPCS file if it exists path = os.path.join(self.working_dir, 'startup.vpc') if os.path.exists(path): return path else: return None
python
def script_file(self): """ Returns the startup script file for this VPCS VM. :returns: path to startup script file """ # use the default VPCS file if it exists path = os.path.join(self.working_dir, 'startup.vpc') if os.path.exists(path): return path else: return None
[ "def", "script_file", "(", "self", ")", ":", "# use the default VPCS file if it exists", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "working_dir", ",", "'startup.vpc'", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":",...
Returns the startup script file for this VPCS VM. :returns: path to startup script file
[ "Returns", "the", "startup", "script", "file", "for", "this", "VPCS", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L539-L551
train
221,209
GNS3/gns3-server
gns3server/utils/interfaces.py
get_windows_interfaces
def get_windows_interfaces(): """ Get Windows interfaces. :returns: list of windows interfaces """ import win32com.client import pywintypes interfaces = [] try: locator = win32com.client.Dispatch("WbemScripting.SWbemLocator") service = locator.ConnectServer(".", "root\cimv2") network_configs = service.InstancesOf("Win32_NetworkAdapterConfiguration") # more info on Win32_NetworkAdapter: http://msdn.microsoft.com/en-us/library/aa394216%28v=vs.85%29.aspx for adapter in service.InstancesOf("Win32_NetworkAdapter"): if adapter.NetConnectionStatus == 2 or adapter.NetConnectionStatus == 7: # adapter is connected or media disconnected ip_address = "" netmask = "" for network_config in network_configs: if network_config.InterfaceIndex == adapter.InterfaceIndex: if network_config.IPAddress: # get the first IPv4 address only ip_address = network_config.IPAddress[0] netmask = network_config.IPSubnet[0] break npf_interface = "\\Device\\NPF_{guid}".format(guid=adapter.GUID) interfaces.append({"id": npf_interface, "name": adapter.NetConnectionID, "ip_address": ip_address, "mac_address": adapter.MACAddress, "netcard": adapter.name, "netmask": netmask, "type": "ethernet"}) except (AttributeError, pywintypes.com_error): log.warn("Could not use the COM service to retrieve interface info, trying using the registry...") return _get_windows_interfaces_from_registry() return interfaces
python
def get_windows_interfaces(): """ Get Windows interfaces. :returns: list of windows interfaces """ import win32com.client import pywintypes interfaces = [] try: locator = win32com.client.Dispatch("WbemScripting.SWbemLocator") service = locator.ConnectServer(".", "root\cimv2") network_configs = service.InstancesOf("Win32_NetworkAdapterConfiguration") # more info on Win32_NetworkAdapter: http://msdn.microsoft.com/en-us/library/aa394216%28v=vs.85%29.aspx for adapter in service.InstancesOf("Win32_NetworkAdapter"): if adapter.NetConnectionStatus == 2 or adapter.NetConnectionStatus == 7: # adapter is connected or media disconnected ip_address = "" netmask = "" for network_config in network_configs: if network_config.InterfaceIndex == adapter.InterfaceIndex: if network_config.IPAddress: # get the first IPv4 address only ip_address = network_config.IPAddress[0] netmask = network_config.IPSubnet[0] break npf_interface = "\\Device\\NPF_{guid}".format(guid=adapter.GUID) interfaces.append({"id": npf_interface, "name": adapter.NetConnectionID, "ip_address": ip_address, "mac_address": adapter.MACAddress, "netcard": adapter.name, "netmask": netmask, "type": "ethernet"}) except (AttributeError, pywintypes.com_error): log.warn("Could not use the COM service to retrieve interface info, trying using the registry...") return _get_windows_interfaces_from_registry() return interfaces
[ "def", "get_windows_interfaces", "(", ")", ":", "import", "win32com", ".", "client", "import", "pywintypes", "interfaces", "=", "[", "]", "try", ":", "locator", "=", "win32com", ".", "client", ".", "Dispatch", "(", "\"WbemScripting.SWbemLocator\"", ")", "service...
Get Windows interfaces. :returns: list of windows interfaces
[ "Get", "Windows", "interfaces", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/interfaces.py#L79-L119
train
221,210
GNS3/gns3-server
gns3server/utils/interfaces.py
has_netmask
def has_netmask(interface_name): """ Checks if an interface has a netmask. :param interface: interface name :returns: boolean """ for interface in interfaces(): if interface["name"] == interface_name: if interface["netmask"] and len(interface["netmask"]) > 0: return True return False return False
python
def has_netmask(interface_name): """ Checks if an interface has a netmask. :param interface: interface name :returns: boolean """ for interface in interfaces(): if interface["name"] == interface_name: if interface["netmask"] and len(interface["netmask"]) > 0: return True return False return False
[ "def", "has_netmask", "(", "interface_name", ")", ":", "for", "interface", "in", "interfaces", "(", ")", ":", "if", "interface", "[", "\"name\"", "]", "==", "interface_name", ":", "if", "interface", "[", "\"netmask\"", "]", "and", "len", "(", "interface", ...
Checks if an interface has a netmask. :param interface: interface name :returns: boolean
[ "Checks", "if", "an", "interface", "has", "a", "netmask", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/interfaces.py#L122-L135
train
221,211
GNS3/gns3-server
gns3server/utils/interfaces.py
is_interface_up
def is_interface_up(interface): """ Checks if an interface is up. :param interface: interface name :returns: boolean """ if sys.platform.startswith("linux"): if interface not in psutil.net_if_addrs(): return False import fcntl SIOCGIFFLAGS = 0x8913 try: with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: result = fcntl.ioctl(s.fileno(), SIOCGIFFLAGS, interface + '\0' * 256) flags, = struct.unpack('H', result[16:18]) if flags & 1: # check if the up bit is set return True return False except OSError as e: raise aiohttp.web.HTTPInternalServerError(text="Exception when checking if {} is up: {}".format(interface, e)) else: # TODO: Windows & OSX support return True
python
def is_interface_up(interface): """ Checks if an interface is up. :param interface: interface name :returns: boolean """ if sys.platform.startswith("linux"): if interface not in psutil.net_if_addrs(): return False import fcntl SIOCGIFFLAGS = 0x8913 try: with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: result = fcntl.ioctl(s.fileno(), SIOCGIFFLAGS, interface + '\0' * 256) flags, = struct.unpack('H', result[16:18]) if flags & 1: # check if the up bit is set return True return False except OSError as e: raise aiohttp.web.HTTPInternalServerError(text="Exception when checking if {} is up: {}".format(interface, e)) else: # TODO: Windows & OSX support return True
[ "def", "is_interface_up", "(", "interface", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "\"linux\"", ")", ":", "if", "interface", "not", "in", "psutil", ".", "net_if_addrs", "(", ")", ":", "return", "False", "import", "fcntl", "SIOCGIFF...
Checks if an interface is up. :param interface: interface name :returns: boolean
[ "Checks", "if", "an", "interface", "is", "up", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/interfaces.py#L138-L165
train
221,212
GNS3/gns3-server
gns3server/utils/interfaces.py
interfaces
def interfaces(): """ Gets the network interfaces on this server. :returns: list of network interfaces """ results = [] if not sys.platform.startswith("win"): net_if_addrs = psutil.net_if_addrs() for interface in sorted(net_if_addrs.keys()): ip_address = "" mac_address = "" netmask = "" interface_type = "ethernet" for addr in net_if_addrs[interface]: # get the first available IPv4 address only if addr.family == socket.AF_INET: ip_address = addr.address netmask = addr.netmask if addr.family == psutil.AF_LINK: mac_address = addr.address if interface.startswith("tap"): # found no way to reliably detect a TAP interface interface_type = "tap" results.append({"id": interface, "name": interface, "ip_address": ip_address, "netmask": netmask, "mac_address": mac_address, "type": interface_type}) else: try: service_installed = True if not _check_windows_service("npf") and not _check_windows_service("npcap"): service_installed = False else: results = get_windows_interfaces() except ImportError: message = "pywin32 module is not installed, please install it on the server to get the available interface names" raise aiohttp.web.HTTPInternalServerError(text=message) except Exception as e: log.error("uncaught exception {type}".format(type=type(e)), exc_info=1) raise aiohttp.web.HTTPInternalServerError(text="uncaught exception: {}".format(e)) if service_installed is False: raise aiohttp.web.HTTPInternalServerError(text="The Winpcap or Npcap is not installed or running") # This interface have special behavior for result in results: result["special"] = False for special_interface in ("lo", "vmnet", "vboxnet", "docker", "lxcbr", "virbr", "ovs-system", "veth", "fw", "p2p", "bridge", "vmware", "virtualbox", "gns3"): if result["name"].lower().startswith(special_interface): result["special"] = True for special_interface in ("-nic"): if result["name"].lower().endswith(special_interface): result["special"] = True return results
python
def interfaces(): """ Gets the network interfaces on this server. :returns: list of network interfaces """ results = [] if not sys.platform.startswith("win"): net_if_addrs = psutil.net_if_addrs() for interface in sorted(net_if_addrs.keys()): ip_address = "" mac_address = "" netmask = "" interface_type = "ethernet" for addr in net_if_addrs[interface]: # get the first available IPv4 address only if addr.family == socket.AF_INET: ip_address = addr.address netmask = addr.netmask if addr.family == psutil.AF_LINK: mac_address = addr.address if interface.startswith("tap"): # found no way to reliably detect a TAP interface interface_type = "tap" results.append({"id": interface, "name": interface, "ip_address": ip_address, "netmask": netmask, "mac_address": mac_address, "type": interface_type}) else: try: service_installed = True if not _check_windows_service("npf") and not _check_windows_service("npcap"): service_installed = False else: results = get_windows_interfaces() except ImportError: message = "pywin32 module is not installed, please install it on the server to get the available interface names" raise aiohttp.web.HTTPInternalServerError(text=message) except Exception as e: log.error("uncaught exception {type}".format(type=type(e)), exc_info=1) raise aiohttp.web.HTTPInternalServerError(text="uncaught exception: {}".format(e)) if service_installed is False: raise aiohttp.web.HTTPInternalServerError(text="The Winpcap or Npcap is not installed or running") # This interface have special behavior for result in results: result["special"] = False for special_interface in ("lo", "vmnet", "vboxnet", "docker", "lxcbr", "virbr", "ovs-system", "veth", "fw", "p2p", "bridge", "vmware", "virtualbox", "gns3"): if result["name"].lower().startswith(special_interface): result["special"] = True for special_interface in ("-nic"): if result["name"].lower().endswith(special_interface): result["special"] = True return results
[ "def", "interfaces", "(", ")", ":", "results", "=", "[", "]", "if", "not", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", ":", "net_if_addrs", "=", "psutil", ".", "net_if_addrs", "(", ")", "for", "interface", "in", "sorted", "(", "net_...
Gets the network interfaces on this server. :returns: list of network interfaces
[ "Gets", "the", "network", "interfaces", "on", "this", "server", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/interfaces.py#L192-L251
train
221,213
GNS3/gns3-server
gns3server/controller/gns3vm/vmware_gns3_vm.py
VMwareGNS3VM._set_vcpus_ram
def _set_vcpus_ram(self, vcpus, ram): """ Set the number of vCPU cores and amount of RAM for the GNS3 VM. :param vcpus: number of vCPU cores :param ram: amount of RAM """ # memory must be a multiple of 4 (VMware requirement) if ram % 4 != 0: raise GNS3VMError("Allocated memory {} for the GNS3 VM must be a multiple of 4".format(ram)) available_vcpus = psutil.cpu_count(logical=False) if vcpus > available_vcpus: raise GNS3VMError("You have allocated too many vCPUs for the GNS3 VM! (max available is {} vCPUs)".format(available_vcpus)) try: pairs = VMware.parse_vmware_file(self._vmx_path) pairs["numvcpus"] = str(vcpus) pairs["memsize"] = str(ram) VMware.write_vmx_file(self._vmx_path, pairs) log.info("GNS3 VM vCPU count set to {} and RAM amount set to {}".format(vcpus, ram)) except OSError as e: raise GNS3VMError('Could not read/write VMware VMX file "{}": {}'.format(self._vmx_path, e))
python
def _set_vcpus_ram(self, vcpus, ram): """ Set the number of vCPU cores and amount of RAM for the GNS3 VM. :param vcpus: number of vCPU cores :param ram: amount of RAM """ # memory must be a multiple of 4 (VMware requirement) if ram % 4 != 0: raise GNS3VMError("Allocated memory {} for the GNS3 VM must be a multiple of 4".format(ram)) available_vcpus = psutil.cpu_count(logical=False) if vcpus > available_vcpus: raise GNS3VMError("You have allocated too many vCPUs for the GNS3 VM! (max available is {} vCPUs)".format(available_vcpus)) try: pairs = VMware.parse_vmware_file(self._vmx_path) pairs["numvcpus"] = str(vcpus) pairs["memsize"] = str(ram) VMware.write_vmx_file(self._vmx_path, pairs) log.info("GNS3 VM vCPU count set to {} and RAM amount set to {}".format(vcpus, ram)) except OSError as e: raise GNS3VMError('Could not read/write VMware VMX file "{}": {}'.format(self._vmx_path, e))
[ "def", "_set_vcpus_ram", "(", "self", ",", "vcpus", ",", "ram", ")", ":", "# memory must be a multiple of 4 (VMware requirement)", "if", "ram", "%", "4", "!=", "0", ":", "raise", "GNS3VMError", "(", "\"Allocated memory {} for the GNS3 VM must be a multiple of 4\"", ".", ...
Set the number of vCPU cores and amount of RAM for the GNS3 VM. :param vcpus: number of vCPU cores :param ram: amount of RAM
[ "Set", "the", "number", "of", "vCPU", "cores", "and", "amount", "of", "RAM", "for", "the", "GNS3", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/vmware_gns3_vm.py#L63-L86
train
221,214
GNS3/gns3-server
gns3server/controller/gns3vm/vmware_gns3_vm.py
VMwareGNS3VM.list
def list(self): """ List all VMware VMs """ try: return (yield from self._vmware_manager.list_vms()) except VMwareError as e: raise GNS3VMError("Could not list VMware VMs: {}".format(str(e)))
python
def list(self): """ List all VMware VMs """ try: return (yield from self._vmware_manager.list_vms()) except VMwareError as e: raise GNS3VMError("Could not list VMware VMs: {}".format(str(e)))
[ "def", "list", "(", "self", ")", ":", "try", ":", "return", "(", "yield", "from", "self", ".", "_vmware_manager", ".", "list_vms", "(", ")", ")", "except", "VMwareError", "as", "e", ":", "raise", "GNS3VMError", "(", "\"Could not list VMware VMs: {}\"", ".", ...
List all VMware VMs
[ "List", "all", "VMware", "VMs" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/vmware_gns3_vm.py#L113-L120
train
221,215
GNS3/gns3-server
gns3server/compute/vmware/vmware_vm.py
VMwareVM._read_vmx_file
def _read_vmx_file(self): """ Reads from the VMware VMX file corresponding to this VM. """ try: self._vmx_pairs = self.manager.parse_vmware_file(self._vmx_path) except OSError as e: raise VMwareError('Could not read VMware VMX file "{}": {}'.format(self._vmx_path, e))
python
def _read_vmx_file(self): """ Reads from the VMware VMX file corresponding to this VM. """ try: self._vmx_pairs = self.manager.parse_vmware_file(self._vmx_path) except OSError as e: raise VMwareError('Could not read VMware VMX file "{}": {}'.format(self._vmx_path, e))
[ "def", "_read_vmx_file", "(", "self", ")", ":", "try", ":", "self", ".", "_vmx_pairs", "=", "self", ".", "manager", ".", "parse_vmware_file", "(", "self", ".", "_vmx_path", ")", "except", "OSError", "as", "e", ":", "raise", "VMwareError", "(", "'Could not ...
Reads from the VMware VMX file corresponding to this VM.
[ "Reads", "from", "the", "VMware", "VMX", "file", "corresponding", "to", "this", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L107-L115
train
221,216
GNS3/gns3-server
gns3server/compute/vmware/vmware_vm.py
VMwareVM._write_vmx_file
def _write_vmx_file(self): """ Writes pairs to the VMware VMX file corresponding to this VM. """ try: self.manager.write_vmx_file(self._vmx_path, self._vmx_pairs) except OSError as e: raise VMwareError('Could not write VMware VMX file "{}": {}'.format(self._vmx_path, e))
python
def _write_vmx_file(self): """ Writes pairs to the VMware VMX file corresponding to this VM. """ try: self.manager.write_vmx_file(self._vmx_path, self._vmx_pairs) except OSError as e: raise VMwareError('Could not write VMware VMX file "{}": {}'.format(self._vmx_path, e))
[ "def", "_write_vmx_file", "(", "self", ")", ":", "try", ":", "self", ".", "manager", ".", "write_vmx_file", "(", "self", ".", "_vmx_path", ",", "self", ".", "_vmx_pairs", ")", "except", "OSError", "as", "e", ":", "raise", "VMwareError", "(", "'Could not wr...
Writes pairs to the VMware VMX file corresponding to this VM.
[ "Writes", "pairs", "to", "the", "VMware", "VMX", "file", "corresponding", "to", "this", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L117-L125
train
221,217
GNS3/gns3-server
gns3server/compute/vmware/vmware_vm.py
VMwareVM.create
def create(self): """ Creates this VM and handle linked clones. """ if not self.linked_clone: yield from self._check_duplicate_linked_clone() yield from self.manager.check_vmrun_version() if self.linked_clone and not os.path.exists(os.path.join(self.working_dir, os.path.basename(self._vmx_path))): if self.manager.host_type == "player": raise VMwareError("Linked clones are not supported by VMware Player") # create the base snapshot for linked clones base_snapshot_name = "GNS3 Linked Base for clones" vmsd_path = os.path.splitext(self._vmx_path)[0] + ".vmsd" if not os.path.exists(vmsd_path): raise VMwareError("{} doesn't not exist".format(vmsd_path)) try: vmsd_pairs = self.manager.parse_vmware_file(vmsd_path) except OSError as e: raise VMwareError('Could not read VMware VMSD file "{}": {}'.format(vmsd_path, e)) gns3_snapshot_exists = False for value in vmsd_pairs.values(): if value == base_snapshot_name: gns3_snapshot_exists = True break if not gns3_snapshot_exists: log.info("Creating snapshot '{}'".format(base_snapshot_name)) yield from self._control_vm("snapshot", base_snapshot_name) # create the linked clone based on the base snapshot new_vmx_path = os.path.join(self.working_dir, self.name + ".vmx") yield from self._control_vm("clone", new_vmx_path, "linked", "-snapshot={}".format(base_snapshot_name), "-cloneName={}".format(self.name)) try: vmsd_pairs = self.manager.parse_vmware_file(vmsd_path) except OSError as e: raise VMwareError('Could not read VMware VMSD file "{}": {}'.format(vmsd_path, e)) snapshot_name = None for name, value in vmsd_pairs.items(): if value == base_snapshot_name: snapshot_name = name.split(".", 1)[0] break if snapshot_name is None: raise VMwareError("Could not find the linked base snapshot in {}".format(vmsd_path)) num_clones_entry = "{}.numClones".format(snapshot_name) if num_clones_entry in vmsd_pairs: try: nb_of_clones = int(vmsd_pairs[num_clones_entry]) except ValueError: raise VMwareError("Value of {} in {} is not a number".format(num_clones_entry, vmsd_path)) vmsd_pairs[num_clones_entry] = str(nb_of_clones - 1) for clone_nb in range(0, nb_of_clones): clone_entry = "{}.clone{}".format(snapshot_name, clone_nb) if clone_entry in vmsd_pairs: del vmsd_pairs[clone_entry] try: self.manager.write_vmware_file(vmsd_path, vmsd_pairs) except OSError as e: raise VMwareError('Could not write VMware VMSD file "{}": {}'.format(vmsd_path, e)) # update the VMX file path self._vmx_path = new_vmx_path
python
def create(self): """ Creates this VM and handle linked clones. """ if not self.linked_clone: yield from self._check_duplicate_linked_clone() yield from self.manager.check_vmrun_version() if self.linked_clone and not os.path.exists(os.path.join(self.working_dir, os.path.basename(self._vmx_path))): if self.manager.host_type == "player": raise VMwareError("Linked clones are not supported by VMware Player") # create the base snapshot for linked clones base_snapshot_name = "GNS3 Linked Base for clones" vmsd_path = os.path.splitext(self._vmx_path)[0] + ".vmsd" if not os.path.exists(vmsd_path): raise VMwareError("{} doesn't not exist".format(vmsd_path)) try: vmsd_pairs = self.manager.parse_vmware_file(vmsd_path) except OSError as e: raise VMwareError('Could not read VMware VMSD file "{}": {}'.format(vmsd_path, e)) gns3_snapshot_exists = False for value in vmsd_pairs.values(): if value == base_snapshot_name: gns3_snapshot_exists = True break if not gns3_snapshot_exists: log.info("Creating snapshot '{}'".format(base_snapshot_name)) yield from self._control_vm("snapshot", base_snapshot_name) # create the linked clone based on the base snapshot new_vmx_path = os.path.join(self.working_dir, self.name + ".vmx") yield from self._control_vm("clone", new_vmx_path, "linked", "-snapshot={}".format(base_snapshot_name), "-cloneName={}".format(self.name)) try: vmsd_pairs = self.manager.parse_vmware_file(vmsd_path) except OSError as e: raise VMwareError('Could not read VMware VMSD file "{}": {}'.format(vmsd_path, e)) snapshot_name = None for name, value in vmsd_pairs.items(): if value == base_snapshot_name: snapshot_name = name.split(".", 1)[0] break if snapshot_name is None: raise VMwareError("Could not find the linked base snapshot in {}".format(vmsd_path)) num_clones_entry = "{}.numClones".format(snapshot_name) if num_clones_entry in vmsd_pairs: try: nb_of_clones = int(vmsd_pairs[num_clones_entry]) except ValueError: raise VMwareError("Value of {} in {} is not a number".format(num_clones_entry, vmsd_path)) vmsd_pairs[num_clones_entry] = str(nb_of_clones - 1) for clone_nb in range(0, nb_of_clones): clone_entry = "{}.clone{}".format(snapshot_name, clone_nb) if clone_entry in vmsd_pairs: del vmsd_pairs[clone_entry] try: self.manager.write_vmware_file(vmsd_path, vmsd_pairs) except OSError as e: raise VMwareError('Could not write VMware VMSD file "{}": {}'.format(vmsd_path, e)) # update the VMX file path self._vmx_path = new_vmx_path
[ "def", "create", "(", "self", ")", ":", "if", "not", "self", ".", "linked_clone", ":", "yield", "from", "self", ".", "_check_duplicate_linked_clone", "(", ")", "yield", "from", "self", ".", "manager", ".", "check_vmrun_version", "(", ")", "if", "self", "."...
Creates this VM and handle linked clones.
[ "Creates", "this", "VM", "and", "handle", "linked", "clones", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L163-L233
train
221,218
GNS3/gns3-server
gns3server/compute/vmware/vmware_vm.py
VMwareVM._set_network_options
def _set_network_options(self): """ Set up VMware networking. """ # first some sanity checks for adapter_number in range(0, self._adapters): # we want the vmnet interface to be connected when starting the VM connected = "ethernet{}.startConnected".format(adapter_number) if self._get_vmx_setting(connected): del self._vmx_pairs[connected] # then configure VMware network adapters self.manager.refresh_vmnet_list() for adapter_number in range(0, self._adapters): # add/update the interface if self._adapter_type == "default": # force default to e1000 because some guest OS don't detect the adapter (i.e. Windows 2012 server) # when 'virtualdev' is not set in the VMX file. adapter_type = "e1000" else: adapter_type = self._adapter_type ethernet_adapter = {"ethernet{}.present".format(adapter_number): "TRUE", "ethernet{}.addresstype".format(adapter_number): "generated", "ethernet{}.generatedaddressoffset".format(adapter_number): "0", "ethernet{}.virtualdev".format(adapter_number): adapter_type} self._vmx_pairs.update(ethernet_adapter) connection_type = "ethernet{}.connectiontype".format(adapter_number) if not self._use_any_adapter and connection_type in self._vmx_pairs and self._vmx_pairs[connection_type] in ("nat", "bridged", "hostonly"): continue self._vmx_pairs["ethernet{}.connectiontype".format(adapter_number)] = "custom" # make sure we have a vmnet per adapter if we use uBridge allocate_vmnet = False # first check if a vmnet is already assigned to the adapter vnet = "ethernet{}.vnet".format(adapter_number) if vnet in self._vmx_pairs: vmnet = os.path.basename(self._vmx_pairs[vnet]) if self.manager.is_managed_vmnet(vmnet) or vmnet in ("vmnet0", "vmnet1", "vmnet8"): # vmnet already managed, try to allocate a new one allocate_vmnet = True else: # otherwise allocate a new one allocate_vmnet = True if allocate_vmnet: try: vmnet = self.manager.allocate_vmnet() except BaseException: # clear everything up in case of error (e.g. no enough vmnets) self._vmnets.clear() raise # mark the vmnet managed by us if vmnet not in self._vmnets: self._vmnets.append(vmnet) self._vmx_pairs["ethernet{}.vnet".format(adapter_number)] = vmnet # disable remaining network adapters for adapter_number in range(self._adapters, self._maximum_adapters): if self._get_vmx_setting("ethernet{}.present".format(adapter_number), "TRUE"): log.debug("disabling remaining adapter {}".format(adapter_number)) self._vmx_pairs["ethernet{}.startconnected".format(adapter_number)] = "FALSE"
python
def _set_network_options(self): """ Set up VMware networking. """ # first some sanity checks for adapter_number in range(0, self._adapters): # we want the vmnet interface to be connected when starting the VM connected = "ethernet{}.startConnected".format(adapter_number) if self._get_vmx_setting(connected): del self._vmx_pairs[connected] # then configure VMware network adapters self.manager.refresh_vmnet_list() for adapter_number in range(0, self._adapters): # add/update the interface if self._adapter_type == "default": # force default to e1000 because some guest OS don't detect the adapter (i.e. Windows 2012 server) # when 'virtualdev' is not set in the VMX file. adapter_type = "e1000" else: adapter_type = self._adapter_type ethernet_adapter = {"ethernet{}.present".format(adapter_number): "TRUE", "ethernet{}.addresstype".format(adapter_number): "generated", "ethernet{}.generatedaddressoffset".format(adapter_number): "0", "ethernet{}.virtualdev".format(adapter_number): adapter_type} self._vmx_pairs.update(ethernet_adapter) connection_type = "ethernet{}.connectiontype".format(adapter_number) if not self._use_any_adapter and connection_type in self._vmx_pairs and self._vmx_pairs[connection_type] in ("nat", "bridged", "hostonly"): continue self._vmx_pairs["ethernet{}.connectiontype".format(adapter_number)] = "custom" # make sure we have a vmnet per adapter if we use uBridge allocate_vmnet = False # first check if a vmnet is already assigned to the adapter vnet = "ethernet{}.vnet".format(adapter_number) if vnet in self._vmx_pairs: vmnet = os.path.basename(self._vmx_pairs[vnet]) if self.manager.is_managed_vmnet(vmnet) or vmnet in ("vmnet0", "vmnet1", "vmnet8"): # vmnet already managed, try to allocate a new one allocate_vmnet = True else: # otherwise allocate a new one allocate_vmnet = True if allocate_vmnet: try: vmnet = self.manager.allocate_vmnet() except BaseException: # clear everything up in case of error (e.g. no enough vmnets) self._vmnets.clear() raise # mark the vmnet managed by us if vmnet not in self._vmnets: self._vmnets.append(vmnet) self._vmx_pairs["ethernet{}.vnet".format(adapter_number)] = vmnet # disable remaining network adapters for adapter_number in range(self._adapters, self._maximum_adapters): if self._get_vmx_setting("ethernet{}.present".format(adapter_number), "TRUE"): log.debug("disabling remaining adapter {}".format(adapter_number)) self._vmx_pairs["ethernet{}.startconnected".format(adapter_number)] = "FALSE"
[ "def", "_set_network_options", "(", "self", ")", ":", "# first some sanity checks", "for", "adapter_number", "in", "range", "(", "0", ",", "self", ".", "_adapters", ")", ":", "# we want the vmnet interface to be connected when starting the VM", "connected", "=", "\"ethern...
Set up VMware networking.
[ "Set", "up", "VMware", "networking", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L245-L311
train
221,219
GNS3/gns3-server
gns3server/compute/vmware/vmware_vm.py
VMwareVM._get_vnet
def _get_vnet(self, adapter_number): """ Return the vnet will use in ubridge """ vnet = "ethernet{}.vnet".format(adapter_number) if vnet not in self._vmx_pairs: raise VMwareError("vnet {} not in VMX file".format(vnet)) return vnet
python
def _get_vnet(self, adapter_number): """ Return the vnet will use in ubridge """ vnet = "ethernet{}.vnet".format(adapter_number) if vnet not in self._vmx_pairs: raise VMwareError("vnet {} not in VMX file".format(vnet)) return vnet
[ "def", "_get_vnet", "(", "self", ",", "adapter_number", ")", ":", "vnet", "=", "\"ethernet{}.vnet\"", ".", "format", "(", "adapter_number", ")", "if", "vnet", "not", "in", "self", ".", "_vmx_pairs", ":", "raise", "VMwareError", "(", "\"vnet {} not in VMX file\""...
Return the vnet will use in ubridge
[ "Return", "the", "vnet", "will", "use", "in", "ubridge" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L313-L320
train
221,220
GNS3/gns3-server
gns3server/compute/vmware/vmware_vm.py
VMwareVM._update_ubridge_connection
def _update_ubridge_connection(self, adapter_number, nio): """ Update a connection in uBridge. :param nio: NIO instance :param adapter_number: adapter number """ try: bridge_name = self._get_vnet(adapter_number) except VMwareError: return # vnet not yet available yield from self._ubridge_apply_filters(bridge_name, nio.filters)
python
def _update_ubridge_connection(self, adapter_number, nio): """ Update a connection in uBridge. :param nio: NIO instance :param adapter_number: adapter number """ try: bridge_name = self._get_vnet(adapter_number) except VMwareError: return # vnet not yet available yield from self._ubridge_apply_filters(bridge_name, nio.filters)
[ "def", "_update_ubridge_connection", "(", "self", ",", "adapter_number", ",", "nio", ")", ":", "try", ":", "bridge_name", "=", "self", ".", "_get_vnet", "(", "adapter_number", ")", "except", "VMwareError", ":", "return", "# vnet not yet available", "yield", "from"...
Update a connection in uBridge. :param nio: NIO instance :param adapter_number: adapter number
[ "Update", "a", "connection", "in", "uBridge", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L355-L366
train
221,221
GNS3/gns3-server
gns3server/compute/vmware/vmware_vm.py
VMwareVM.start
def start(self): """ Starts this VMware VM. """ if self.status == "started": return if (yield from self.is_running()): raise VMwareError("The VM is already running in VMware") ubridge_path = self.ubridge_path if not ubridge_path or not os.path.isfile(ubridge_path): raise VMwareError("ubridge is necessary to start a VMware VM") yield from self._start_ubridge() self._read_vmx_file() # check if there is enough RAM to run if "memsize" in self._vmx_pairs: self.check_available_ram(int(self._vmx_pairs["memsize"])) self._set_network_options() self._set_serial_console() self._write_vmx_file() if self._headless: yield from self._control_vm("start", "nogui") else: yield from self._control_vm("start") try: if self._ubridge_hypervisor: for adapter_number in range(0, self._adapters): nio = self._ethernet_adapters[adapter_number].get_nio(0) if nio: yield from self._add_ubridge_connection(nio, adapter_number) yield from self._start_console() except VMwareError: yield from self.stop() raise if self._get_vmx_setting("vhv.enable", "TRUE"): self._hw_virtualization = True self._started = True self.status = "started" log.info("VMware VM '{name}' [{id}] started".format(name=self.name, id=self.id))
python
def start(self): """ Starts this VMware VM. """ if self.status == "started": return if (yield from self.is_running()): raise VMwareError("The VM is already running in VMware") ubridge_path = self.ubridge_path if not ubridge_path or not os.path.isfile(ubridge_path): raise VMwareError("ubridge is necessary to start a VMware VM") yield from self._start_ubridge() self._read_vmx_file() # check if there is enough RAM to run if "memsize" in self._vmx_pairs: self.check_available_ram(int(self._vmx_pairs["memsize"])) self._set_network_options() self._set_serial_console() self._write_vmx_file() if self._headless: yield from self._control_vm("start", "nogui") else: yield from self._control_vm("start") try: if self._ubridge_hypervisor: for adapter_number in range(0, self._adapters): nio = self._ethernet_adapters[adapter_number].get_nio(0) if nio: yield from self._add_ubridge_connection(nio, adapter_number) yield from self._start_console() except VMwareError: yield from self.stop() raise if self._get_vmx_setting("vhv.enable", "TRUE"): self._hw_virtualization = True self._started = True self.status = "started" log.info("VMware VM '{name}' [{id}] started".format(name=self.name, id=self.id))
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "status", "==", "\"started\"", ":", "return", "if", "(", "yield", "from", "self", ".", "is_running", "(", ")", ")", ":", "raise", "VMwareError", "(", "\"The VM is already running in VMware\"", ")", ...
Starts this VMware VM.
[ "Starts", "this", "VMware", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L426-L472
train
221,222
GNS3/gns3-server
gns3server/compute/vmware/vmware_vm.py
VMwareVM.stop
def stop(self): """ Stops this VMware VM. """ self._hw_virtualization = False yield from self._stop_remote_console() yield from self._stop_ubridge() try: if (yield from self.is_running()): if self.acpi_shutdown: # use ACPI to shutdown the VM yield from self._control_vm("stop", "soft") else: yield from self._control_vm("stop") finally: self._started = False self.status = "stopped" self._read_vmx_file() self._vmnets.clear() # remove the adapters managed by GNS3 for adapter_number in range(0, self._adapters): vnet = "ethernet{}.vnet".format(adapter_number) if self._get_vmx_setting(vnet) or self._get_vmx_setting("ethernet{}.connectiontype".format(adapter_number)) is None: if vnet in self._vmx_pairs: vmnet = os.path.basename(self._vmx_pairs[vnet]) if not self.manager.is_managed_vmnet(vmnet): continue log.debug("removing adapter {}".format(adapter_number)) self._vmx_pairs[vnet] = "vmnet1" self._vmx_pairs["ethernet{}.connectiontype".format(adapter_number)] = "custom" # re-enable any remaining network adapters for adapter_number in range(self._adapters, self._maximum_adapters): if self._get_vmx_setting("ethernet{}.present".format(adapter_number), "TRUE"): log.debug("enabling remaining adapter {}".format(adapter_number)) self._vmx_pairs["ethernet{}.startconnected".format(adapter_number)] = "TRUE" self._write_vmx_file() yield from super().stop() log.info("VMware VM '{name}' [{id}] stopped".format(name=self.name, id=self.id))
python
def stop(self): """ Stops this VMware VM. """ self._hw_virtualization = False yield from self._stop_remote_console() yield from self._stop_ubridge() try: if (yield from self.is_running()): if self.acpi_shutdown: # use ACPI to shutdown the VM yield from self._control_vm("stop", "soft") else: yield from self._control_vm("stop") finally: self._started = False self.status = "stopped" self._read_vmx_file() self._vmnets.clear() # remove the adapters managed by GNS3 for adapter_number in range(0, self._adapters): vnet = "ethernet{}.vnet".format(adapter_number) if self._get_vmx_setting(vnet) or self._get_vmx_setting("ethernet{}.connectiontype".format(adapter_number)) is None: if vnet in self._vmx_pairs: vmnet = os.path.basename(self._vmx_pairs[vnet]) if not self.manager.is_managed_vmnet(vmnet): continue log.debug("removing adapter {}".format(adapter_number)) self._vmx_pairs[vnet] = "vmnet1" self._vmx_pairs["ethernet{}.connectiontype".format(adapter_number)] = "custom" # re-enable any remaining network adapters for adapter_number in range(self._adapters, self._maximum_adapters): if self._get_vmx_setting("ethernet{}.present".format(adapter_number), "TRUE"): log.debug("enabling remaining adapter {}".format(adapter_number)) self._vmx_pairs["ethernet{}.startconnected".format(adapter_number)] = "TRUE" self._write_vmx_file() yield from super().stop() log.info("VMware VM '{name}' [{id}] stopped".format(name=self.name, id=self.id))
[ "def", "stop", "(", "self", ")", ":", "self", ".", "_hw_virtualization", "=", "False", "yield", "from", "self", ".", "_stop_remote_console", "(", ")", "yield", "from", "self", ".", "_stop_ubridge", "(", ")", "try", ":", "if", "(", "yield", "from", "self"...
Stops this VMware VM.
[ "Stops", "this", "VMware", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L475-L517
train
221,223
GNS3/gns3-server
gns3server/compute/vmware/vmware_vm.py
VMwareVM.suspend
def suspend(self): """ Suspends this VMware VM. """ if self.manager.host_type != "ws": raise VMwareError("Pausing a VM is only supported by VMware Workstation") yield from self._control_vm("pause") self.status = "suspended" log.info("VMware VM '{name}' [{id}] paused".format(name=self.name, id=self.id))
python
def suspend(self): """ Suspends this VMware VM. """ if self.manager.host_type != "ws": raise VMwareError("Pausing a VM is only supported by VMware Workstation") yield from self._control_vm("pause") self.status = "suspended" log.info("VMware VM '{name}' [{id}] paused".format(name=self.name, id=self.id))
[ "def", "suspend", "(", "self", ")", ":", "if", "self", ".", "manager", ".", "host_type", "!=", "\"ws\"", ":", "raise", "VMwareError", "(", "\"Pausing a VM is only supported by VMware Workstation\"", ")", "yield", "from", "self", ".", "_control_vm", "(", "\"pause\"...
Suspends this VMware VM.
[ "Suspends", "this", "VMware", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L520-L529
train
221,224
GNS3/gns3-server
gns3server/compute/vmware/vmware_vm.py
VMwareVM.close
def close(self): """ Closes this VMware VM. """ if not (yield from super().close()): return False for adapter in self._ethernet_adapters.values(): if adapter is not None: for nio in adapter.ports.values(): if nio and isinstance(nio, NIOUDP): self.manager.port_manager.release_udp_port(nio.lport, self._project) try: self.acpi_shutdown = False yield from self.stop() except VMwareError: pass if self.linked_clone: yield from self.manager.remove_from_vmware_inventory(self._vmx_path)
python
def close(self): """ Closes this VMware VM. """ if not (yield from super().close()): return False for adapter in self._ethernet_adapters.values(): if adapter is not None: for nio in adapter.ports.values(): if nio and isinstance(nio, NIOUDP): self.manager.port_manager.release_udp_port(nio.lport, self._project) try: self.acpi_shutdown = False yield from self.stop() except VMwareError: pass if self.linked_clone: yield from self.manager.remove_from_vmware_inventory(self._vmx_path)
[ "def", "close", "(", "self", ")", ":", "if", "not", "(", "yield", "from", "super", "(", ")", ".", "close", "(", ")", ")", ":", "return", "False", "for", "adapter", "in", "self", ".", "_ethernet_adapters", ".", "values", "(", ")", ":", "if", "adapte...
Closes this VMware VM.
[ "Closes", "this", "VMware", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L553-L573
train
221,225
GNS3/gns3-server
gns3server/compute/vmware/vmware_vm.py
VMwareVM.headless
def headless(self, headless): """ Sets either the VM will start in headless mode :param headless: boolean """ if headless: log.info("VMware VM '{name}' [{id}] has enabled the headless mode".format(name=self.name, id=self.id)) else: log.info("VMware VM '{name}' [{id}] has disabled the headless mode".format(name=self.name, id=self.id)) self._headless = headless
python
def headless(self, headless): """ Sets either the VM will start in headless mode :param headless: boolean """ if headless: log.info("VMware VM '{name}' [{id}] has enabled the headless mode".format(name=self.name, id=self.id)) else: log.info("VMware VM '{name}' [{id}] has disabled the headless mode".format(name=self.name, id=self.id)) self._headless = headless
[ "def", "headless", "(", "self", ",", "headless", ")", ":", "if", "headless", ":", "log", ".", "info", "(", "\"VMware VM '{name}' [{id}] has enabled the headless mode\"", ".", "format", "(", "name", "=", "self", ".", "name", ",", "id", "=", "self", ".", "id",...
Sets either the VM will start in headless mode :param headless: boolean
[ "Sets", "either", "the", "VM", "will", "start", "in", "headless", "mode" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L586-L597
train
221,226
GNS3/gns3-server
gns3server/compute/vmware/vmware_vm.py
VMwareVM.vmx_path
def vmx_path(self, vmx_path): """ Sets the path to the vmx file. :param vmx_path: VMware vmx file """ log.info("VMware VM '{name}' [{id}] has set the vmx file path to '{vmx}'".format(name=self.name, id=self.id, vmx=vmx_path)) self._vmx_path = vmx_path
python
def vmx_path(self, vmx_path): """ Sets the path to the vmx file. :param vmx_path: VMware vmx file """ log.info("VMware VM '{name}' [{id}] has set the vmx file path to '{vmx}'".format(name=self.name, id=self.id, vmx=vmx_path)) self._vmx_path = vmx_path
[ "def", "vmx_path", "(", "self", ",", "vmx_path", ")", ":", "log", ".", "info", "(", "\"VMware VM '{name}' [{id}] has set the vmx file path to '{vmx}'\"", ".", "format", "(", "name", "=", "self", ".", "name", ",", "id", "=", "self", ".", "id", ",", "vmx", "="...
Sets the path to the vmx file. :param vmx_path: VMware vmx file
[ "Sets", "the", "path", "to", "the", "vmx", "file", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L634-L642
train
221,227
GNS3/gns3-server
gns3server/compute/vmware/vmware_vm.py
VMwareVM.adapters
def adapters(self, adapters): """ Sets the number of Ethernet adapters for this VMware VM instance. :param adapters: number of adapters """ # VMware VMs are limited to 10 adapters if adapters > 10: raise VMwareError("Number of adapters above the maximum supported of 10") self._ethernet_adapters.clear() for adapter_number in range(0, adapters): self._ethernet_adapters[adapter_number] = EthernetAdapter() self._adapters = len(self._ethernet_adapters) log.info("VMware VM '{name}' [{id}] has changed the number of Ethernet adapters to {adapters}".format(name=self.name, id=self.id, adapters=adapters))
python
def adapters(self, adapters): """ Sets the number of Ethernet adapters for this VMware VM instance. :param adapters: number of adapters """ # VMware VMs are limited to 10 adapters if adapters > 10: raise VMwareError("Number of adapters above the maximum supported of 10") self._ethernet_adapters.clear() for adapter_number in range(0, adapters): self._ethernet_adapters[adapter_number] = EthernetAdapter() self._adapters = len(self._ethernet_adapters) log.info("VMware VM '{name}' [{id}] has changed the number of Ethernet adapters to {adapters}".format(name=self.name, id=self.id, adapters=adapters))
[ "def", "adapters", "(", "self", ",", "adapters", ")", ":", "# VMware VMs are limited to 10 adapters", "if", "adapters", ">", "10", ":", "raise", "VMwareError", "(", "\"Number of adapters above the maximum supported of 10\"", ")", "self", ".", "_ethernet_adapters", ".", ...
Sets the number of Ethernet adapters for this VMware VM instance. :param adapters: number of adapters
[ "Sets", "the", "number", "of", "Ethernet", "adapters", "for", "this", "VMware", "VM", "instance", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L655-L673
train
221,228
GNS3/gns3-server
gns3server/compute/vmware/vmware_vm.py
VMwareVM.adapter_type
def adapter_type(self, adapter_type): """ Sets the adapter type for this VMware VM instance. :param adapter_type: adapter type (string) """ self._adapter_type = adapter_type log.info("VMware VM '{name}' [{id}]: adapter type changed to {adapter_type}".format(name=self.name, id=self.id, adapter_type=adapter_type))
python
def adapter_type(self, adapter_type): """ Sets the adapter type for this VMware VM instance. :param adapter_type: adapter type (string) """ self._adapter_type = adapter_type log.info("VMware VM '{name}' [{id}]: adapter type changed to {adapter_type}".format(name=self.name, id=self.id, adapter_type=adapter_type))
[ "def", "adapter_type", "(", "self", ",", "adapter_type", ")", ":", "self", ".", "_adapter_type", "=", "adapter_type", "log", ".", "info", "(", "\"VMware VM '{name}' [{id}]: adapter type changed to {adapter_type}\"", ".", "format", "(", "name", "=", "self", ".", "nam...
Sets the adapter type for this VMware VM instance. :param adapter_type: adapter type (string)
[ "Sets", "the", "adapter", "type", "for", "this", "VMware", "VM", "instance", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L686-L696
train
221,229
GNS3/gns3-server
gns3server/compute/vmware/vmware_vm.py
VMwareVM.use_any_adapter
def use_any_adapter(self, use_any_adapter): """ Allows GNS3 to use any VMware adapter on this instance. :param use_any_adapter: boolean """ if use_any_adapter: log.info("VMware VM '{name}' [{id}] is allowed to use any adapter".format(name=self.name, id=self.id)) else: log.info("VMware VM '{name}' [{id}] is not allowed to use any adapter".format(name=self.name, id=self.id)) self._use_any_adapter = use_any_adapter
python
def use_any_adapter(self, use_any_adapter): """ Allows GNS3 to use any VMware adapter on this instance. :param use_any_adapter: boolean """ if use_any_adapter: log.info("VMware VM '{name}' [{id}] is allowed to use any adapter".format(name=self.name, id=self.id)) else: log.info("VMware VM '{name}' [{id}] is not allowed to use any adapter".format(name=self.name, id=self.id)) self._use_any_adapter = use_any_adapter
[ "def", "use_any_adapter", "(", "self", ",", "use_any_adapter", ")", ":", "if", "use_any_adapter", ":", "log", ".", "info", "(", "\"VMware VM '{name}' [{id}] is allowed to use any adapter\"", ".", "format", "(", "name", "=", "self", ".", "name", ",", "id", "=", "...
Allows GNS3 to use any VMware adapter on this instance. :param use_any_adapter: boolean
[ "Allows", "GNS3", "to", "use", "any", "VMware", "adapter", "on", "this", "instance", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L709-L720
train
221,230
GNS3/gns3-server
gns3server/compute/vmware/vmware_vm.py
VMwareVM._get_pipe_name
def _get_pipe_name(self): """ Returns the pipe name to create a serial connection. :returns: pipe path (string) """ if sys.platform.startswith("win"): pipe_name = r"\\.\pipe\gns3_vmware\{}".format(self.id) else: pipe_name = os.path.join(tempfile.gettempdir(), "gns3_vmware", "{}".format(self.id)) try: os.makedirs(os.path.dirname(pipe_name), exist_ok=True) except OSError as e: raise VMwareError("Could not create the VMware pipe directory: {}".format(e)) return pipe_name
python
def _get_pipe_name(self): """ Returns the pipe name to create a serial connection. :returns: pipe path (string) """ if sys.platform.startswith("win"): pipe_name = r"\\.\pipe\gns3_vmware\{}".format(self.id) else: pipe_name = os.path.join(tempfile.gettempdir(), "gns3_vmware", "{}".format(self.id)) try: os.makedirs(os.path.dirname(pipe_name), exist_ok=True) except OSError as e: raise VMwareError("Could not create the VMware pipe directory: {}".format(e)) return pipe_name
[ "def", "_get_pipe_name", "(", "self", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", ":", "pipe_name", "=", "r\"\\\\.\\pipe\\gns3_vmware\\{}\"", ".", "format", "(", "self", ".", "id", ")", "else", ":", "pipe_name", "=", "os...
Returns the pipe name to create a serial connection. :returns: pipe path (string)
[ "Returns", "the", "pipe", "name", "to", "create", "a", "serial", "connection", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L811-L826
train
221,231
GNS3/gns3-server
gns3server/compute/vmware/vmware_vm.py
VMwareVM._start_console
def _start_console(self): """ Starts remote console support for this VM. """ self._remote_pipe = yield from asyncio_open_serial(self._get_pipe_name()) server = AsyncioTelnetServer(reader=self._remote_pipe, writer=self._remote_pipe, binary=True, echo=True) self._telnet_server = yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console)
python
def _start_console(self): """ Starts remote console support for this VM. """ self._remote_pipe = yield from asyncio_open_serial(self._get_pipe_name()) server = AsyncioTelnetServer(reader=self._remote_pipe, writer=self._remote_pipe, binary=True, echo=True) self._telnet_server = yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console)
[ "def", "_start_console", "(", "self", ")", ":", "self", ".", "_remote_pipe", "=", "yield", "from", "asyncio_open_serial", "(", "self", ".", "_get_pipe_name", "(", ")", ")", "server", "=", "AsyncioTelnetServer", "(", "reader", "=", "self", ".", "_remote_pipe", ...
Starts remote console support for this VM.
[ "Starts", "remote", "console", "support", "for", "this", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L842-L851
train
221,232
GNS3/gns3-server
gns3server/compute/vmware/vmware_vm.py
VMwareVM._stop_remote_console
def _stop_remote_console(self): """ Stops remote console support for this VM. """ if self._telnet_server: self._telnet_server.close() yield from self._telnet_server.wait_closed() self._remote_pipe.close() self._telnet_server = None
python
def _stop_remote_console(self): """ Stops remote console support for this VM. """ if self._telnet_server: self._telnet_server.close() yield from self._telnet_server.wait_closed() self._remote_pipe.close() self._telnet_server = None
[ "def", "_stop_remote_console", "(", "self", ")", ":", "if", "self", ".", "_telnet_server", ":", "self", ".", "_telnet_server", ".", "close", "(", ")", "yield", "from", "self", ".", "_telnet_server", ".", "wait_closed", "(", ")", "self", ".", "_remote_pipe", ...
Stops remote console support for this VM.
[ "Stops", "remote", "console", "support", "for", "this", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L854-L862
train
221,233
GNS3/gns3-server
gns3server/utils/path.py
get_default_project_directory
def get_default_project_directory(): """ Return the default location for the project directory depending of the operating system """ server_config = Config.instance().get_section_config("Server") path = os.path.expanduser(server_config.get("projects_path", "~/GNS3/projects")) path = os.path.normpath(path) try: os.makedirs(path, exist_ok=True) except OSError as e: raise aiohttp.web.HTTPInternalServerError(text="Could not create project directory: {}".format(e)) return path
python
def get_default_project_directory(): """ Return the default location for the project directory depending of the operating system """ server_config = Config.instance().get_section_config("Server") path = os.path.expanduser(server_config.get("projects_path", "~/GNS3/projects")) path = os.path.normpath(path) try: os.makedirs(path, exist_ok=True) except OSError as e: raise aiohttp.web.HTTPInternalServerError(text="Could not create project directory: {}".format(e)) return path
[ "def", "get_default_project_directory", "(", ")", ":", "server_config", "=", "Config", ".", "instance", "(", ")", ".", "get_section_config", "(", "\"Server\"", ")", "path", "=", "os", ".", "path", ".", "expanduser", "(", "server_config", ".", "get", "(", "\"...
Return the default location for the project directory depending of the operating system
[ "Return", "the", "default", "location", "for", "the", "project", "directory", "depending", "of", "the", "operating", "system" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/path.py#L24-L37
train
221,234
GNS3/gns3-server
gns3server/utils/path.py
check_path_allowed
def check_path_allowed(path): """ If the server is non local raise an error if the path is outside project directories Raise a 403 in case of error """ config = Config.instance().get_section_config("Server") project_directory = get_default_project_directory() if len(os.path.commonprefix([project_directory, path])) == len(project_directory): return if "local" in config and config.getboolean("local") is False: raise aiohttp.web.HTTPForbidden(text="The path is not allowed")
python
def check_path_allowed(path): """ If the server is non local raise an error if the path is outside project directories Raise a 403 in case of error """ config = Config.instance().get_section_config("Server") project_directory = get_default_project_directory() if len(os.path.commonprefix([project_directory, path])) == len(project_directory): return if "local" in config and config.getboolean("local") is False: raise aiohttp.web.HTTPForbidden(text="The path is not allowed")
[ "def", "check_path_allowed", "(", "path", ")", ":", "config", "=", "Config", ".", "instance", "(", ")", ".", "get_section_config", "(", "\"Server\"", ")", "project_directory", "=", "get_default_project_directory", "(", ")", "if", "len", "(", "os", ".", "path",...
If the server is non local raise an error if the path is outside project directories Raise a 403 in case of error
[ "If", "the", "server", "is", "non", "local", "raise", "an", "error", "if", "the", "path", "is", "outside", "project", "directories" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/path.py#L40-L55
train
221,235
GNS3/gns3-server
gns3server/compute/dynamips/nodes/ethernet_hub.py
EthernetHub.ports_mapping
def ports_mapping(self, ports): """ Set the ports on this hub :param ports: ports info """ if ports != self._ports: if len(self._mappings) > 0: raise NodeError("Can't modify a hub already connected.") port_number = 0 for port in ports: port["name"] = "Ethernet{}".format(port_number) port["port_number"] = port_number port_number += 1 self._ports = ports
python
def ports_mapping(self, ports): """ Set the ports on this hub :param ports: ports info """ if ports != self._ports: if len(self._mappings) > 0: raise NodeError("Can't modify a hub already connected.") port_number = 0 for port in ports: port["name"] = "Ethernet{}".format(port_number) port["port_number"] = port_number port_number += 1 self._ports = ports
[ "def", "ports_mapping", "(", "self", ",", "ports", ")", ":", "if", "ports", "!=", "self", ".", "_ports", ":", "if", "len", "(", "self", ".", "_mappings", ")", ">", "0", ":", "raise", "NodeError", "(", "\"Can't modify a hub already connected.\"", ")", "port...
Set the ports on this hub :param ports: ports info
[ "Set", "the", "ports", "on", "this", "hub" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/ethernet_hub.py#L78-L94
train
221,236
GNS3/gns3-server
gns3server/compute/dynamips/nodes/ethernet_hub.py
EthernetHub.close
def close(self): """ Deletes this hub. """ for nio in self._nios: if nio: yield from nio.close() try: yield from Bridge.delete(self) log.info('Ethernet hub "{name}" [{id}] has been deleted'.format(name=self._name, id=self._id)) except DynamipsError: log.debug("Could not properly delete Ethernet hub {}".format(self._name)) if self._hypervisor and not self._hypervisor.devices: yield from self.hypervisor.stop() self._hypervisor = None return True
python
def close(self): """ Deletes this hub. """ for nio in self._nios: if nio: yield from nio.close() try: yield from Bridge.delete(self) log.info('Ethernet hub "{name}" [{id}] has been deleted'.format(name=self._name, id=self._id)) except DynamipsError: log.debug("Could not properly delete Ethernet hub {}".format(self._name)) if self._hypervisor and not self._hypervisor.devices: yield from self.hypervisor.stop() self._hypervisor = None return True
[ "def", "close", "(", "self", ")", ":", "for", "nio", "in", "self", ".", "_nios", ":", "if", "nio", ":", "yield", "from", "nio", ".", "close", "(", ")", "try", ":", "yield", "from", "Bridge", ".", "delete", "(", "self", ")", "log", ".", "info", ...
Deletes this hub.
[ "Deletes", "this", "hub", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/ethernet_hub.py#L117-L134
train
221,237
GNS3/gns3-server
gns3server/compute/dynamips/nodes/ethernet_hub.py
EthernetHub.add_nio
def add_nio(self, nio, port_number): """ Adds a NIO as new port on this hub. :param nio: NIO instance to add :param port_number: port to allocate for the NIO """ if port_number not in [port["port_number"] for port in self._ports]: raise DynamipsError("Port {} doesn't exist".format(port_number)) if port_number in self._mappings: raise DynamipsError("Port {} isn't free".format(port_number)) yield from Bridge.add_nio(self, nio) log.info('Ethernet hub "{name}" [{id}]: NIO {nio} bound to port {port}'.format(name=self._name, id=self._id, nio=nio, port=port_number)) self._mappings[port_number] = nio
python
def add_nio(self, nio, port_number): """ Adds a NIO as new port on this hub. :param nio: NIO instance to add :param port_number: port to allocate for the NIO """ if port_number not in [port["port_number"] for port in self._ports]: raise DynamipsError("Port {} doesn't exist".format(port_number)) if port_number in self._mappings: raise DynamipsError("Port {} isn't free".format(port_number)) yield from Bridge.add_nio(self, nio) log.info('Ethernet hub "{name}" [{id}]: NIO {nio} bound to port {port}'.format(name=self._name, id=self._id, nio=nio, port=port_number)) self._mappings[port_number] = nio
[ "def", "add_nio", "(", "self", ",", "nio", ",", "port_number", ")", ":", "if", "port_number", "not", "in", "[", "port", "[", "\"port_number\"", "]", "for", "port", "in", "self", ".", "_ports", "]", ":", "raise", "DynamipsError", "(", "\"Port {} doesn't exi...
Adds a NIO as new port on this hub. :param nio: NIO instance to add :param port_number: port to allocate for the NIO
[ "Adds", "a", "NIO", "as", "new", "port", "on", "this", "hub", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/ethernet_hub.py#L137-L157
train
221,238
GNS3/gns3-server
gns3server/compute/dynamips/nodes/ethernet_hub.py
EthernetHub.remove_nio
def remove_nio(self, port_number): """ Removes the specified NIO as member of this hub. :param port_number: allocated port number :returns: the NIO that was bound to the allocated port """ if port_number not in self._mappings: raise DynamipsError("Port {} is not allocated".format(port_number)) nio = self._mappings[port_number] if isinstance(nio, NIOUDP): self.manager.port_manager.release_udp_port(nio.lport, self._project) yield from Bridge.remove_nio(self, nio) log.info('Ethernet hub "{name}" [{id}]: NIO {nio} removed from port {port}'.format(name=self._name, id=self._id, nio=nio, port=port_number)) del self._mappings[port_number] return nio
python
def remove_nio(self, port_number): """ Removes the specified NIO as member of this hub. :param port_number: allocated port number :returns: the NIO that was bound to the allocated port """ if port_number not in self._mappings: raise DynamipsError("Port {} is not allocated".format(port_number)) nio = self._mappings[port_number] if isinstance(nio, NIOUDP): self.manager.port_manager.release_udp_port(nio.lport, self._project) yield from Bridge.remove_nio(self, nio) log.info('Ethernet hub "{name}" [{id}]: NIO {nio} removed from port {port}'.format(name=self._name, id=self._id, nio=nio, port=port_number)) del self._mappings[port_number] return nio
[ "def", "remove_nio", "(", "self", ",", "port_number", ")", ":", "if", "port_number", "not", "in", "self", ".", "_mappings", ":", "raise", "DynamipsError", "(", "\"Port {} is not allocated\"", ".", "format", "(", "port_number", ")", ")", "nio", "=", "self", "...
Removes the specified NIO as member of this hub. :param port_number: allocated port number :returns: the NIO that was bound to the allocated port
[ "Removes", "the", "specified", "NIO", "as", "member", "of", "this", "hub", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/ethernet_hub.py#L160-L183
train
221,239
GNS3/gns3-server
gns3server/compute/base_manager.py
BaseManager.instance
def instance(cls): """ Singleton to return only one instance of BaseManager. :returns: instance of BaseManager """ if not hasattr(cls, "_instance") or cls._instance is None: cls._instance = cls() return cls._instance
python
def instance(cls): """ Singleton to return only one instance of BaseManager. :returns: instance of BaseManager """ if not hasattr(cls, "_instance") or cls._instance is None: cls._instance = cls() return cls._instance
[ "def", "instance", "(", "cls", ")", ":", "if", "not", "hasattr", "(", "cls", ",", "\"_instance\"", ")", "or", "cls", ".", "_instance", "is", "None", ":", "cls", ".", "_instance", "=", "cls", "(", ")", "return", "cls", ".", "_instance" ]
Singleton to return only one instance of BaseManager. :returns: instance of BaseManager
[ "Singleton", "to", "return", "only", "one", "instance", "of", "BaseManager", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_manager.py#L78-L87
train
221,240
GNS3/gns3-server
gns3server/compute/base_manager.py
BaseManager.port_manager
def port_manager(self): """ Returns the port manager. :returns: Port manager """ if self._port_manager is None: self._port_manager = PortManager.instance() return self._port_manager
python
def port_manager(self): """ Returns the port manager. :returns: Port manager """ if self._port_manager is None: self._port_manager = PortManager.instance() return self._port_manager
[ "def", "port_manager", "(", "self", ")", ":", "if", "self", ".", "_port_manager", "is", "None", ":", "self", ".", "_port_manager", "=", "PortManager", ".", "instance", "(", ")", "return", "self", ".", "_port_manager" ]
Returns the port manager. :returns: Port manager
[ "Returns", "the", "port", "manager", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_manager.py#L100-L108
train
221,241
GNS3/gns3-server
gns3server/compute/base_manager.py
BaseManager.convert_old_project
def convert_old_project(self, project, legacy_id, name): """ Convert projects made before version 1.3 :param project: Project instance :param legacy_id: old identifier :param name: node name :returns: new identifier """ new_id = str(uuid4()) legacy_project_files_path = os.path.join(project.path, "{}-files".format(project.name)) new_project_files_path = os.path.join(project.path, "project-files") if os.path.exists(legacy_project_files_path) and not os.path.exists(new_project_files_path): # move the project files log.info("Converting old project...") try: log.info('Moving "{}" to "{}"'.format(legacy_project_files_path, new_project_files_path)) yield from wait_run_in_executor(shutil.move, legacy_project_files_path, new_project_files_path) except OSError as e: raise aiohttp.web.HTTPInternalServerError(text="Could not move project files directory: {} to {} {}".format(legacy_project_files_path, new_project_files_path, e)) if project.is_local() is False: legacy_remote_project_path = os.path.join(project.location, project.name, self.module_name.lower()) new_remote_project_path = os.path.join(project.path, "project-files", self.module_name.lower()) if os.path.exists(legacy_remote_project_path) and not os.path.exists(new_remote_project_path): # move the legacy remote project (remote servers only) log.info("Converting old remote project...") try: log.info('Moving "{}" to "{}"'.format(legacy_remote_project_path, new_remote_project_path)) yield from wait_run_in_executor(shutil.move, legacy_remote_project_path, new_remote_project_path) except OSError as e: raise aiohttp.web.HTTPInternalServerError(text="Could not move directory: {} to {} {}".format(legacy_remote_project_path, new_remote_project_path, e)) if hasattr(self, "get_legacy_vm_workdir"): # rename old project node working dir log.info("Converting old node working directory...") legacy_vm_dir = self.get_legacy_vm_workdir(legacy_id, name) legacy_vm_working_path = os.path.join(new_project_files_path, legacy_vm_dir) new_vm_working_path = os.path.join(new_project_files_path, self.module_name.lower(), new_id) if os.path.exists(legacy_vm_working_path) and not os.path.exists(new_vm_working_path): try: log.info('Moving "{}" to "{}"'.format(legacy_vm_working_path, new_vm_working_path)) yield from wait_run_in_executor(shutil.move, legacy_vm_working_path, new_vm_working_path) except OSError as e: raise aiohttp.web.HTTPInternalServerError(text="Could not move vm working directory: {} to {} {}".format(legacy_vm_working_path, new_vm_working_path, e)) return new_id
python
def convert_old_project(self, project, legacy_id, name): """ Convert projects made before version 1.3 :param project: Project instance :param legacy_id: old identifier :param name: node name :returns: new identifier """ new_id = str(uuid4()) legacy_project_files_path = os.path.join(project.path, "{}-files".format(project.name)) new_project_files_path = os.path.join(project.path, "project-files") if os.path.exists(legacy_project_files_path) and not os.path.exists(new_project_files_path): # move the project files log.info("Converting old project...") try: log.info('Moving "{}" to "{}"'.format(legacy_project_files_path, new_project_files_path)) yield from wait_run_in_executor(shutil.move, legacy_project_files_path, new_project_files_path) except OSError as e: raise aiohttp.web.HTTPInternalServerError(text="Could not move project files directory: {} to {} {}".format(legacy_project_files_path, new_project_files_path, e)) if project.is_local() is False: legacy_remote_project_path = os.path.join(project.location, project.name, self.module_name.lower()) new_remote_project_path = os.path.join(project.path, "project-files", self.module_name.lower()) if os.path.exists(legacy_remote_project_path) and not os.path.exists(new_remote_project_path): # move the legacy remote project (remote servers only) log.info("Converting old remote project...") try: log.info('Moving "{}" to "{}"'.format(legacy_remote_project_path, new_remote_project_path)) yield from wait_run_in_executor(shutil.move, legacy_remote_project_path, new_remote_project_path) except OSError as e: raise aiohttp.web.HTTPInternalServerError(text="Could not move directory: {} to {} {}".format(legacy_remote_project_path, new_remote_project_path, e)) if hasattr(self, "get_legacy_vm_workdir"): # rename old project node working dir log.info("Converting old node working directory...") legacy_vm_dir = self.get_legacy_vm_workdir(legacy_id, name) legacy_vm_working_path = os.path.join(new_project_files_path, legacy_vm_dir) new_vm_working_path = os.path.join(new_project_files_path, self.module_name.lower(), new_id) if os.path.exists(legacy_vm_working_path) and not os.path.exists(new_vm_working_path): try: log.info('Moving "{}" to "{}"'.format(legacy_vm_working_path, new_vm_working_path)) yield from wait_run_in_executor(shutil.move, legacy_vm_working_path, new_vm_working_path) except OSError as e: raise aiohttp.web.HTTPInternalServerError(text="Could not move vm working directory: {} to {} {}".format(legacy_vm_working_path, new_vm_working_path, e)) return new_id
[ "def", "convert_old_project", "(", "self", ",", "project", ",", "legacy_id", ",", "name", ")", ":", "new_id", "=", "str", "(", "uuid4", "(", ")", ")", "legacy_project_files_path", "=", "os", ".", "path", ".", "join", "(", "project", ".", "path", ",", "...
Convert projects made before version 1.3 :param project: Project instance :param legacy_id: old identifier :param name: node name :returns: new identifier
[ "Convert", "projects", "made", "before", "version", "1", ".", "3" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_manager.py#L175-L226
train
221,242
GNS3/gns3-server
gns3server/compute/base_manager.py
BaseManager.close_node
def close_node(self, node_id): """ Close a node :param node_id: Node identifier :returns: Node instance """ node = self.get_node(node_id) if asyncio.iscoroutinefunction(node.close): yield from node.close() else: node.close() return node
python
def close_node(self, node_id): """ Close a node :param node_id: Node identifier :returns: Node instance """ node = self.get_node(node_id) if asyncio.iscoroutinefunction(node.close): yield from node.close() else: node.close() return node
[ "def", "close_node", "(", "self", ",", "node_id", ")", ":", "node", "=", "self", ".", "get_node", "(", "node_id", ")", "if", "asyncio", ".", "iscoroutinefunction", "(", "node", ".", "close", ")", ":", "yield", "from", "node", ".", "close", "(", ")", ...
Close a node :param node_id: Node identifier :returns: Node instance
[ "Close", "a", "node" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_manager.py#L291-L305
train
221,243
GNS3/gns3-server
gns3server/compute/base_manager.py
BaseManager.delete_node
def delete_node(self, node_id): """ Delete a node. The node working directory will be destroyed when a commit is received. :param node_id: Node identifier :returns: Node instance """ node = None try: node = self.get_node(node_id) yield from self.close_node(node_id) finally: if node: node.project.emit("node.deleted", node) yield from node.project.remove_node(node) if node.id in self._nodes: del self._nodes[node.id] return node
python
def delete_node(self, node_id): """ Delete a node. The node working directory will be destroyed when a commit is received. :param node_id: Node identifier :returns: Node instance """ node = None try: node = self.get_node(node_id) yield from self.close_node(node_id) finally: if node: node.project.emit("node.deleted", node) yield from node.project.remove_node(node) if node.id in self._nodes: del self._nodes[node.id] return node
[ "def", "delete_node", "(", "self", ",", "node_id", ")", ":", "node", "=", "None", "try", ":", "node", "=", "self", ".", "get_node", "(", "node_id", ")", "yield", "from", "self", ".", "close_node", "(", "node_id", ")", "finally", ":", "if", "node", ":...
Delete a node. The node working directory will be destroyed when a commit is received. :param node_id: Node identifier :returns: Node instance
[ "Delete", "a", "node", ".", "The", "node", "working", "directory", "will", "be", "destroyed", "when", "a", "commit", "is", "received", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_manager.py#L330-L348
train
221,244
GNS3/gns3-server
gns3server/compute/base_manager.py
BaseManager.has_privileged_access
def has_privileged_access(executable): """ Check if an executable have the right to attach to Ethernet and TAP adapters. :param executable: executable path :returns: True or False """ if sys.platform.startswith("win"): # do not check anything on Windows return True if sys.platform.startswith("darwin"): if os.stat(executable).st_uid == 0: return True if os.geteuid() == 0: # we are root, so we should have privileged access. return True if os.stat(executable).st_uid == 0 and (os.stat(executable).st_mode & stat.S_ISUID or os.stat(executable).st_mode & stat.S_ISGID): # the executable has set UID bit. return True # test if the executable has the CAP_NET_RAW capability (Linux only) try: if sys.platform.startswith("linux") and "security.capability" in os.listxattr(executable): caps = os.getxattr(executable, "security.capability") # test the 2nd byte and check if the 13th bit (CAP_NET_RAW) is set if struct.unpack("<IIIII", caps)[1] & 1 << 13: return True except (AttributeError, OSError) as e: log.error("could not determine if CAP_NET_RAW capability is set for {}: {}".format(executable, e)) return False
python
def has_privileged_access(executable): """ Check if an executable have the right to attach to Ethernet and TAP adapters. :param executable: executable path :returns: True or False """ if sys.platform.startswith("win"): # do not check anything on Windows return True if sys.platform.startswith("darwin"): if os.stat(executable).st_uid == 0: return True if os.geteuid() == 0: # we are root, so we should have privileged access. return True if os.stat(executable).st_uid == 0 and (os.stat(executable).st_mode & stat.S_ISUID or os.stat(executable).st_mode & stat.S_ISGID): # the executable has set UID bit. return True # test if the executable has the CAP_NET_RAW capability (Linux only) try: if sys.platform.startswith("linux") and "security.capability" in os.listxattr(executable): caps = os.getxattr(executable, "security.capability") # test the 2nd byte and check if the 13th bit (CAP_NET_RAW) is set if struct.unpack("<IIIII", caps)[1] & 1 << 13: return True except (AttributeError, OSError) as e: log.error("could not determine if CAP_NET_RAW capability is set for {}: {}".format(executable, e)) return False
[ "def", "has_privileged_access", "(", "executable", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", ":", "# do not check anything on Windows", "return", "True", "if", "sys", ".", "platform", ".", "startswith", "(", "\"darwin\"", ")...
Check if an executable have the right to attach to Ethernet and TAP adapters. :param executable: executable path :returns: True or False
[ "Check", "if", "an", "executable", "have", "the", "right", "to", "attach", "to", "Ethernet", "and", "TAP", "adapters", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_manager.py#L351-L386
train
221,245
GNS3/gns3-server
gns3server/compute/base_manager.py
BaseManager.get_abs_image_path
def get_abs_image_path(self, path): """ Get the absolute path of an image :param path: file path :return: file path """ if not path: return "" orig_path = path server_config = self.config.get_section_config("Server") img_directory = self.get_images_directory() # Windows path should not be send to a unix server if not sys.platform.startswith("win"): if re.match(r"^[A-Z]:", path) is not None: raise NodeError("{} is not allowed on this remote server. Please use only a filename in {}.".format(path, img_directory)) if not os.path.isabs(path): for directory in images_directories(self._NODE_TYPE): path = self._recursive_search_file_in_directory(directory, orig_path) if path: return force_unix_path(path) # Not found we try the default directory s = os.path.split(orig_path) path = force_unix_path(os.path.join(img_directory, *s)) if os.path.exists(path): return path raise ImageMissingError(orig_path) # For non local server we disallow using absolute path outside image directory if server_config.getboolean("local", False) is True: path = force_unix_path(path) if os.path.exists(path): return path raise ImageMissingError(orig_path) path = force_unix_path(path) for directory in images_directories(self._NODE_TYPE): if os.path.commonprefix([directory, path]) == directory: if os.path.exists(path): return path raise ImageMissingError(orig_path) raise NodeError("{} is not allowed on this remote server. Please use only a filename in {}.".format(path, img_directory))
python
def get_abs_image_path(self, path): """ Get the absolute path of an image :param path: file path :return: file path """ if not path: return "" orig_path = path server_config = self.config.get_section_config("Server") img_directory = self.get_images_directory() # Windows path should not be send to a unix server if not sys.platform.startswith("win"): if re.match(r"^[A-Z]:", path) is not None: raise NodeError("{} is not allowed on this remote server. Please use only a filename in {}.".format(path, img_directory)) if not os.path.isabs(path): for directory in images_directories(self._NODE_TYPE): path = self._recursive_search_file_in_directory(directory, orig_path) if path: return force_unix_path(path) # Not found we try the default directory s = os.path.split(orig_path) path = force_unix_path(os.path.join(img_directory, *s)) if os.path.exists(path): return path raise ImageMissingError(orig_path) # For non local server we disallow using absolute path outside image directory if server_config.getboolean("local", False) is True: path = force_unix_path(path) if os.path.exists(path): return path raise ImageMissingError(orig_path) path = force_unix_path(path) for directory in images_directories(self._NODE_TYPE): if os.path.commonprefix([directory, path]) == directory: if os.path.exists(path): return path raise ImageMissingError(orig_path) raise NodeError("{} is not allowed on this remote server. Please use only a filename in {}.".format(path, img_directory))
[ "def", "get_abs_image_path", "(", "self", ",", "path", ")", ":", "if", "not", "path", ":", "return", "\"\"", "orig_path", "=", "path", "server_config", "=", "self", ".", "config", ".", "get_section_config", "(", "\"Server\"", ")", "img_directory", "=", "self...
Get the absolute path of an image :param path: file path :return: file path
[ "Get", "the", "absolute", "path", "of", "an", "image" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_manager.py#L430-L476
train
221,246
GNS3/gns3-server
gns3server/compute/base_manager.py
BaseManager._recursive_search_file_in_directory
def _recursive_search_file_in_directory(self, directory, searched_file): """ Search for a file in directory and is subdirectories :returns: Path or None if not found """ s = os.path.split(searched_file) for root, dirs, files in os.walk(directory): for file in files: # If filename is the same if s[1] == file and (s[0] == '' or s[0] == os.path.basename(root)): path = os.path.normpath(os.path.join(root, s[1])) if os.path.exists(path): return path return None
python
def _recursive_search_file_in_directory(self, directory, searched_file): """ Search for a file in directory and is subdirectories :returns: Path or None if not found """ s = os.path.split(searched_file) for root, dirs, files in os.walk(directory): for file in files: # If filename is the same if s[1] == file and (s[0] == '' or s[0] == os.path.basename(root)): path = os.path.normpath(os.path.join(root, s[1])) if os.path.exists(path): return path return None
[ "def", "_recursive_search_file_in_directory", "(", "self", ",", "directory", ",", "searched_file", ")", ":", "s", "=", "os", ".", "path", ".", "split", "(", "searched_file", ")", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "di...
Search for a file in directory and is subdirectories :returns: Path or None if not found
[ "Search", "for", "a", "file", "in", "directory", "and", "is", "subdirectories" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_manager.py#L478-L493
train
221,247
GNS3/gns3-server
gns3server/compute/base_manager.py
BaseManager.get_relative_image_path
def get_relative_image_path(self, path): """ Get a path relative to images directory path or an abspath if the path is not located inside image directory :param path: file path :return: file path """ if not path: return "" path = force_unix_path(self.get_abs_image_path(path)) img_directory = self.get_images_directory() for directory in images_directories(self._NODE_TYPE): if os.path.commonprefix([directory, path]) == directory: relpath = os.path.relpath(path, directory) # We don't allow to recurse search from the top image directory just for image type directory (compatibility with old releases) if os.sep not in relpath or directory == img_directory: return relpath return path
python
def get_relative_image_path(self, path): """ Get a path relative to images directory path or an abspath if the path is not located inside image directory :param path: file path :return: file path """ if not path: return "" path = force_unix_path(self.get_abs_image_path(path)) img_directory = self.get_images_directory() for directory in images_directories(self._NODE_TYPE): if os.path.commonprefix([directory, path]) == directory: relpath = os.path.relpath(path, directory) # We don't allow to recurse search from the top image directory just for image type directory (compatibility with old releases) if os.sep not in relpath or directory == img_directory: return relpath return path
[ "def", "get_relative_image_path", "(", "self", ",", "path", ")", ":", "if", "not", "path", ":", "return", "\"\"", "path", "=", "force_unix_path", "(", "self", ".", "get_abs_image_path", "(", "path", ")", ")", "img_directory", "=", "self", ".", "get_images_di...
Get a path relative to images directory path or an abspath if the path is not located inside image directory :param path: file path :return: file path
[ "Get", "a", "path", "relative", "to", "images", "directory", "path", "or", "an", "abspath", "if", "the", "path", "is", "not", "located", "inside", "image", "directory" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_manager.py#L495-L517
train
221,248
GNS3/gns3-server
gns3server/compute/base_manager.py
BaseManager.list_images
def list_images(self): """ Return the list of available images for this node type :returns: Array of hash """ try: return list_images(self._NODE_TYPE) except OSError as e: raise aiohttp.web.HTTPConflict(text="Can not list images {}".format(e))
python
def list_images(self): """ Return the list of available images for this node type :returns: Array of hash """ try: return list_images(self._NODE_TYPE) except OSError as e: raise aiohttp.web.HTTPConflict(text="Can not list images {}".format(e))
[ "def", "list_images", "(", "self", ")", ":", "try", ":", "return", "list_images", "(", "self", ".", "_NODE_TYPE", ")", "except", "OSError", "as", "e", ":", "raise", "aiohttp", ".", "web", ".", "HTTPConflict", "(", "text", "=", "\"Can not list images {}\"", ...
Return the list of available images for this node type :returns: Array of hash
[ "Return", "the", "list", "of", "available", "images", "for", "this", "node", "type" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_manager.py#L520-L530
train
221,249
GNS3/gns3-server
gns3server/compute/dynamips/hypervisor.py
Hypervisor.start
def start(self): """ Starts the Dynamips hypervisor process. """ self._command = self._build_command() env = os.environ.copy() if sys.platform.startswith("win"): # add the Npcap directory to $PATH to force Dynamips to use npcap DLL instead of Winpcap (if installed) system_root = os.path.join(os.path.expandvars("%SystemRoot%"), "System32", "Npcap") if os.path.isdir(system_root): env["PATH"] = system_root + ';' + env["PATH"] try: log.info("Starting Dynamips: {}".format(self._command)) self._stdout_file = os.path.join(self.working_dir, "dynamips_i{}_stdout.txt".format(self._id)) log.info("Dynamips process logging to {}".format(self._stdout_file)) with open(self._stdout_file, "w", encoding="utf-8") as fd: self._process = yield from asyncio.create_subprocess_exec(*self._command, stdout=fd, stderr=subprocess.STDOUT, cwd=self._working_dir, env=env) log.info("Dynamips process started PID={}".format(self._process.pid)) self._started = True except (OSError, subprocess.SubprocessError) as e: log.error("Could not start Dynamips: {}".format(e)) raise DynamipsError("Could not start Dynamips: {}".format(e))
python
def start(self): """ Starts the Dynamips hypervisor process. """ self._command = self._build_command() env = os.environ.copy() if sys.platform.startswith("win"): # add the Npcap directory to $PATH to force Dynamips to use npcap DLL instead of Winpcap (if installed) system_root = os.path.join(os.path.expandvars("%SystemRoot%"), "System32", "Npcap") if os.path.isdir(system_root): env["PATH"] = system_root + ';' + env["PATH"] try: log.info("Starting Dynamips: {}".format(self._command)) self._stdout_file = os.path.join(self.working_dir, "dynamips_i{}_stdout.txt".format(self._id)) log.info("Dynamips process logging to {}".format(self._stdout_file)) with open(self._stdout_file, "w", encoding="utf-8") as fd: self._process = yield from asyncio.create_subprocess_exec(*self._command, stdout=fd, stderr=subprocess.STDOUT, cwd=self._working_dir, env=env) log.info("Dynamips process started PID={}".format(self._process.pid)) self._started = True except (OSError, subprocess.SubprocessError) as e: log.error("Could not start Dynamips: {}".format(e)) raise DynamipsError("Could not start Dynamips: {}".format(e))
[ "def", "start", "(", "self", ")", ":", "self", ".", "_command", "=", "self", ".", "_build_command", "(", ")", "env", "=", "os", ".", "environ", ".", "copy", "(", ")", "if", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", ":", "# add...
Starts the Dynamips hypervisor process.
[ "Starts", "the", "Dynamips", "hypervisor", "process", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/hypervisor.py#L115-L141
train
221,250
GNS3/gns3-server
gns3server/compute/dynamips/hypervisor.py
Hypervisor.stop
def stop(self): """ Stops the Dynamips hypervisor process. """ if self.is_running(): log.info("Stopping Dynamips process PID={}".format(self._process.pid)) yield from DynamipsHypervisor.stop(self) # give some time for the hypervisor to properly stop. # time to delete UNIX NIOs for instance. yield from asyncio.sleep(0.01) try: yield from wait_for_process_termination(self._process, timeout=3) except asyncio.TimeoutError: if self._process.returncode is None: log.warn("Dynamips process {} is still running... killing it".format(self._process.pid)) try: self._process.kill() except OSError as e: log.error("Cannot stop the Dynamips process: {}".format(e)) if self._process.returncode is None: log.warn('Dynamips hypervisor with PID={} is still running'.format(self._process.pid)) if self._stdout_file and os.access(self._stdout_file, os.W_OK): try: os.remove(self._stdout_file) except OSError as e: log.warning("could not delete temporary Dynamips log file: {}".format(e)) self._started = False
python
def stop(self): """ Stops the Dynamips hypervisor process. """ if self.is_running(): log.info("Stopping Dynamips process PID={}".format(self._process.pid)) yield from DynamipsHypervisor.stop(self) # give some time for the hypervisor to properly stop. # time to delete UNIX NIOs for instance. yield from asyncio.sleep(0.01) try: yield from wait_for_process_termination(self._process, timeout=3) except asyncio.TimeoutError: if self._process.returncode is None: log.warn("Dynamips process {} is still running... killing it".format(self._process.pid)) try: self._process.kill() except OSError as e: log.error("Cannot stop the Dynamips process: {}".format(e)) if self._process.returncode is None: log.warn('Dynamips hypervisor with PID={} is still running'.format(self._process.pid)) if self._stdout_file and os.access(self._stdout_file, os.W_OK): try: os.remove(self._stdout_file) except OSError as e: log.warning("could not delete temporary Dynamips log file: {}".format(e)) self._started = False
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "is_running", "(", ")", ":", "log", ".", "info", "(", "\"Stopping Dynamips process PID={}\"", ".", "format", "(", "self", ".", "_process", ".", "pid", ")", ")", "yield", "from", "DynamipsHypervisor",...
Stops the Dynamips hypervisor process.
[ "Stops", "the", "Dynamips", "hypervisor", "process", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/hypervisor.py#L144-L172
train
221,251
GNS3/gns3-server
gns3server/compute/dynamips/hypervisor.py
Hypervisor.read_stdout
def read_stdout(self): """ Reads the standard output of the Dynamips process. Only use when the process has been stopped or has crashed. """ output = "" if self._stdout_file and os.access(self._stdout_file, os.R_OK): try: with open(self._stdout_file, "rb") as file: output = file.read().decode("utf-8", errors="replace") except OSError as e: log.warn("could not read {}: {}".format(self._stdout_file, e)) return output
python
def read_stdout(self): """ Reads the standard output of the Dynamips process. Only use when the process has been stopped or has crashed. """ output = "" if self._stdout_file and os.access(self._stdout_file, os.R_OK): try: with open(self._stdout_file, "rb") as file: output = file.read().decode("utf-8", errors="replace") except OSError as e: log.warn("could not read {}: {}".format(self._stdout_file, e)) return output
[ "def", "read_stdout", "(", "self", ")", ":", "output", "=", "\"\"", "if", "self", ".", "_stdout_file", "and", "os", ".", "access", "(", "self", ".", "_stdout_file", ",", "os", ".", "R_OK", ")", ":", "try", ":", "with", "open", "(", "self", ".", "_s...
Reads the standard output of the Dynamips process. Only use when the process has been stopped or has crashed.
[ "Reads", "the", "standard", "output", "of", "the", "Dynamips", "process", ".", "Only", "use", "when", "the", "process", "has", "been", "stopped", "or", "has", "crashed", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/hypervisor.py#L174-L187
train
221,252
GNS3/gns3-server
gns3server/compute/dynamips/adapters/adapter.py
Adapter.install_wic
def install_wic(self, wic_slot_id, wic): """ Installs a WIC on this adapter. :param wic_slot_id: WIC slot ID (integer) :param wic: WIC instance """ self._wics[wic_slot_id] = wic # Dynamips WICs ports start on a multiple of 16 + port number # WIC1 port 1 = 16, WIC1 port 2 = 17 # WIC2 port 1 = 32, WIC2 port 2 = 33 # WIC3 port 1 = 48, WIC3 port 2 = 49 base = 16 * (wic_slot_id + 1) for wic_port in range(0, wic.interfaces): port_number = base + wic_port self._ports[port_number] = None
python
def install_wic(self, wic_slot_id, wic): """ Installs a WIC on this adapter. :param wic_slot_id: WIC slot ID (integer) :param wic: WIC instance """ self._wics[wic_slot_id] = wic # Dynamips WICs ports start on a multiple of 16 + port number # WIC1 port 1 = 16, WIC1 port 2 = 17 # WIC2 port 1 = 32, WIC2 port 2 = 33 # WIC3 port 1 = 48, WIC3 port 2 = 49 base = 16 * (wic_slot_id + 1) for wic_port in range(0, wic.interfaces): port_number = base + wic_port self._ports[port_number] = None
[ "def", "install_wic", "(", "self", ",", "wic_slot_id", ",", "wic", ")", ":", "self", ".", "_wics", "[", "wic_slot_id", "]", "=", "wic", "# Dynamips WICs ports start on a multiple of 16 + port number", "# WIC1 port 1 = 16, WIC1 port 2 = 17", "# WIC2 port 1 = 32, WIC2 port 2 = ...
Installs a WIC on this adapter. :param wic_slot_id: WIC slot ID (integer) :param wic: WIC instance
[ "Installs", "a", "WIC", "on", "this", "adapter", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/adapters/adapter.py#L70-L87
train
221,253
GNS3/gns3-server
gns3server/controller/link.py
Link.update_filters
def update_filters(self, filters): """ Modify the filters list. Filter with value 0 will be dropped because not active """ new_filters = {} for (filter, values) in filters.items(): new_values = [] for value in values: if isinstance(value, str): new_values.append(value.strip("\n ")) else: new_values.append(int(value)) values = new_values if len(values) != 0 and values[0] != 0 and values[0] != '': new_filters[filter] = values if new_filters != self.filters: self._filters = new_filters if self._created: yield from self.update() self._project.controller.notification.emit("link.updated", self.__json__()) self._project.dump()
python
def update_filters(self, filters): """ Modify the filters list. Filter with value 0 will be dropped because not active """ new_filters = {} for (filter, values) in filters.items(): new_values = [] for value in values: if isinstance(value, str): new_values.append(value.strip("\n ")) else: new_values.append(int(value)) values = new_values if len(values) != 0 and values[0] != 0 and values[0] != '': new_filters[filter] = values if new_filters != self.filters: self._filters = new_filters if self._created: yield from self.update() self._project.controller.notification.emit("link.updated", self.__json__()) self._project.dump()
[ "def", "update_filters", "(", "self", ",", "filters", ")", ":", "new_filters", "=", "{", "}", "for", "(", "filter", ",", "values", ")", "in", "filters", ".", "items", "(", ")", ":", "new_values", "=", "[", "]", "for", "value", "in", "values", ":", ...
Modify the filters list. Filter with value 0 will be dropped because not active
[ "Modify", "the", "filters", "list", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/link.py#L152-L175
train
221,254
GNS3/gns3-server
gns3server/controller/link.py
Link.add_node
def add_node(self, node, adapter_number, port_number, label=None, dump=True): """ Add a node to the link :param dump: Dump project on disk """ port = node.get_port(adapter_number, port_number) if port is None: raise aiohttp.web.HTTPNotFound(text="Port {}/{} for {} not found".format(adapter_number, port_number, node.name)) if port.link is not None: raise aiohttp.web.HTTPConflict(text="Port is already used") self._link_type = port.link_type for other_node in self._nodes: if other_node["node"] == node: raise aiohttp.web.HTTPConflict(text="Cannot connect to itself") if node.node_type in ["nat", "cloud"]: if other_node["node"].node_type in ["nat", "cloud"]: raise aiohttp.web.HTTPConflict(text="It's not allowed to connect a {} to a {}".format(other_node["node"].node_type, node.node_type)) # Check if user is not connecting serial => ethernet other_port = other_node["node"].get_port(other_node["adapter_number"], other_node["port_number"]) if other_port is None: raise aiohttp.web.HTTPNotFound(text="Port {}/{} for {} not found".format(other_node["adapter_number"], other_node["port_number"], other_node["node"].name)) if port.link_type != other_port.link_type: raise aiohttp.web.HTTPConflict(text="It's not allowed to connect a {} to a {}".format(other_port.link_type, port.link_type)) if label is None: label = { "x": -10, "y": -10, "rotation": 0, "text": html.escape("{}/{}".format(adapter_number, port_number)), "style": "font-size: 10; font-style: Verdana" } self._nodes.append({ "node": node, "adapter_number": adapter_number, "port_number": port_number, "port": port, "label": label }) if len(self._nodes) == 2: yield from self.create() for n in self._nodes: n["node"].add_link(self) n["port"].link = self self._created = True self._project.controller.notification.emit("link.created", self.__json__()) if dump: self._project.dump()
python
def add_node(self, node, adapter_number, port_number, label=None, dump=True): """ Add a node to the link :param dump: Dump project on disk """ port = node.get_port(adapter_number, port_number) if port is None: raise aiohttp.web.HTTPNotFound(text="Port {}/{} for {} not found".format(adapter_number, port_number, node.name)) if port.link is not None: raise aiohttp.web.HTTPConflict(text="Port is already used") self._link_type = port.link_type for other_node in self._nodes: if other_node["node"] == node: raise aiohttp.web.HTTPConflict(text="Cannot connect to itself") if node.node_type in ["nat", "cloud"]: if other_node["node"].node_type in ["nat", "cloud"]: raise aiohttp.web.HTTPConflict(text="It's not allowed to connect a {} to a {}".format(other_node["node"].node_type, node.node_type)) # Check if user is not connecting serial => ethernet other_port = other_node["node"].get_port(other_node["adapter_number"], other_node["port_number"]) if other_port is None: raise aiohttp.web.HTTPNotFound(text="Port {}/{} for {} not found".format(other_node["adapter_number"], other_node["port_number"], other_node["node"].name)) if port.link_type != other_port.link_type: raise aiohttp.web.HTTPConflict(text="It's not allowed to connect a {} to a {}".format(other_port.link_type, port.link_type)) if label is None: label = { "x": -10, "y": -10, "rotation": 0, "text": html.escape("{}/{}".format(adapter_number, port_number)), "style": "font-size: 10; font-style: Verdana" } self._nodes.append({ "node": node, "adapter_number": adapter_number, "port_number": port_number, "port": port, "label": label }) if len(self._nodes) == 2: yield from self.create() for n in self._nodes: n["node"].add_link(self) n["port"].link = self self._created = True self._project.controller.notification.emit("link.created", self.__json__()) if dump: self._project.dump()
[ "def", "add_node", "(", "self", ",", "node", ",", "adapter_number", ",", "port_number", ",", "label", "=", "None", ",", "dump", "=", "True", ")", ":", "port", "=", "node", ".", "get_port", "(", "adapter_number", ",", "port_number", ")", "if", "port", "...
Add a node to the link :param dump: Dump project on disk
[ "Add", "a", "node", "to", "the", "link" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/link.py#L193-L249
train
221,255
GNS3/gns3-server
gns3server/controller/link.py
Link.delete
def delete(self): """ Delete the link """ for n in self._nodes: # It could be different of self if we rollback an already existing link if n["port"].link == self: n["port"].link = None n["node"].remove_link(self)
python
def delete(self): """ Delete the link """ for n in self._nodes: # It could be different of self if we rollback an already existing link if n["port"].link == self: n["port"].link = None n["node"].remove_link(self)
[ "def", "delete", "(", "self", ")", ":", "for", "n", "in", "self", ".", "_nodes", ":", "# It could be different of self if we rollback an already existing link", "if", "n", "[", "\"port\"", "]", ".", "link", "==", "self", ":", "n", "[", "\"port\"", "]", ".", ...
Delete the link
[ "Delete", "the", "link" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/link.py#L279-L287
train
221,256
GNS3/gns3-server
gns3server/controller/link.py
Link.start_capture
def start_capture(self, data_link_type="DLT_EN10MB", capture_file_name=None): """ Start capture on the link :returns: Capture object """ self._capturing = True self._capture_file_name = capture_file_name self._streaming_pcap = asyncio.async(self._start_streaming_pcap()) self._project.controller.notification.emit("link.updated", self.__json__())
python
def start_capture(self, data_link_type="DLT_EN10MB", capture_file_name=None): """ Start capture on the link :returns: Capture object """ self._capturing = True self._capture_file_name = capture_file_name self._streaming_pcap = asyncio.async(self._start_streaming_pcap()) self._project.controller.notification.emit("link.updated", self.__json__())
[ "def", "start_capture", "(", "self", ",", "data_link_type", "=", "\"DLT_EN10MB\"", ",", "capture_file_name", "=", "None", ")", ":", "self", ".", "_capturing", "=", "True", "self", ".", "_capture_file_name", "=", "capture_file_name", "self", ".", "_streaming_pcap",...
Start capture on the link :returns: Capture object
[ "Start", "capture", "on", "the", "link" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/link.py#L290-L300
train
221,257
GNS3/gns3-server
gns3server/controller/link.py
Link._start_streaming_pcap
def _start_streaming_pcap(self): """ Dump a pcap file on disk """ if os.path.exists(self.capture_file_path): try: os.remove(self.capture_file_path) except OSError as e: raise aiohttp.web.HTTPConflict(text="Could not delete old capture file '{}': {}".format(self.capture_file_path, e)) try: stream_content = yield from self.read_pcap_from_source() except aiohttp.web.HTTPException as e: error_msg = "Could not stream PCAP file: error {}: {}".format(e.status, e.text) log.error(error_msg) self._capturing = False self._project.notification.emit("log.error", {"message": error_msg}) self._project.controller.notification.emit("link.updated", self.__json__()) with stream_content as stream: try: with open(self.capture_file_path, "wb") as f: while self._capturing: # We read 1 bytes by 1 otherwise the remaining data is not read if the traffic stops data = yield from stream.read(1) if data: f.write(data) # Flush to disk otherwise the live is not really live f.flush() else: break except OSError as e: raise aiohttp.web.HTTPConflict(text="Could not write capture file '{}': {}".format(self.capture_file_path, e))
python
def _start_streaming_pcap(self): """ Dump a pcap file on disk """ if os.path.exists(self.capture_file_path): try: os.remove(self.capture_file_path) except OSError as e: raise aiohttp.web.HTTPConflict(text="Could not delete old capture file '{}': {}".format(self.capture_file_path, e)) try: stream_content = yield from self.read_pcap_from_source() except aiohttp.web.HTTPException as e: error_msg = "Could not stream PCAP file: error {}: {}".format(e.status, e.text) log.error(error_msg) self._capturing = False self._project.notification.emit("log.error", {"message": error_msg}) self._project.controller.notification.emit("link.updated", self.__json__()) with stream_content as stream: try: with open(self.capture_file_path, "wb") as f: while self._capturing: # We read 1 bytes by 1 otherwise the remaining data is not read if the traffic stops data = yield from stream.read(1) if data: f.write(data) # Flush to disk otherwise the live is not really live f.flush() else: break except OSError as e: raise aiohttp.web.HTTPConflict(text="Could not write capture file '{}': {}".format(self.capture_file_path, e))
[ "def", "_start_streaming_pcap", "(", "self", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "capture_file_path", ")", ":", "try", ":", "os", ".", "remove", "(", "self", ".", "capture_file_path", ")", "except", "OSError", "as", "e", ...
Dump a pcap file on disk
[ "Dump", "a", "pcap", "file", "on", "disk" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/link.py#L303-L336
train
221,258
GNS3/gns3-server
gns3server/controller/link.py
Link.stop_capture
def stop_capture(self): """ Stop capture on the link """ self._capturing = False self._project.controller.notification.emit("link.updated", self.__json__())
python
def stop_capture(self): """ Stop capture on the link """ self._capturing = False self._project.controller.notification.emit("link.updated", self.__json__())
[ "def", "stop_capture", "(", "self", ")", ":", "self", ".", "_capturing", "=", "False", "self", ".", "_project", ".", "controller", ".", "notification", ".", "emit", "(", "\"link.updated\"", ",", "self", ".", "__json__", "(", ")", ")" ]
Stop capture on the link
[ "Stop", "capture", "on", "the", "link" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/link.py#L339-L345
train
221,259
GNS3/gns3-server
gns3server/controller/link.py
Link.capture_file_path
def capture_file_path(self): """ Get the path of the capture """ if self._capture_file_name: return os.path.join(self._project.captures_directory, self._capture_file_name) else: return None
python
def capture_file_path(self): """ Get the path of the capture """ if self._capture_file_name: return os.path.join(self._project.captures_directory, self._capture_file_name) else: return None
[ "def", "capture_file_path", "(", "self", ")", ":", "if", "self", ".", "_capture_file_name", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "_project", ".", "captures_directory", ",", "self", ".", "_capture_file_name", ")", "else", ":", "r...
Get the path of the capture
[ "Get", "the", "path", "of", "the", "capture" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/link.py#L388-L396
train
221,260
GNS3/gns3-server
gns3server/compute/dynamips/dynamips_hypervisor.py
DynamipsHypervisor.connect
def connect(self, timeout=10): """ Connects to the hypervisor. """ # connect to a local address by default # if listening to all addresses (IPv4 or IPv6) if self._host == "0.0.0.0": host = "127.0.0.1" elif self._host == "::": host = "::1" else: host = self._host begin = time.time() connection_success = False last_exception = None while time.time() - begin < timeout: yield from asyncio.sleep(0.01) try: self._reader, self._writer = yield from asyncio.wait_for(asyncio.open_connection(host, self._port), timeout=1) except (asyncio.TimeoutError, OSError) as e: last_exception = e continue connection_success = True break if not connection_success: raise DynamipsError("Couldn't connect to hypervisor on {}:{} :{}".format(host, self._port, last_exception)) else: log.info("Connected to Dynamips hypervisor after {:.4f} seconds".format(time.time() - begin)) try: version = yield from self.send("hypervisor version") self._version = version[0].split("-", 1)[0] except IndexError: self._version = "Unknown" # this forces to send the working dir to Dynamips yield from self.set_working_dir(self._working_dir)
python
def connect(self, timeout=10): """ Connects to the hypervisor. """ # connect to a local address by default # if listening to all addresses (IPv4 or IPv6) if self._host == "0.0.0.0": host = "127.0.0.1" elif self._host == "::": host = "::1" else: host = self._host begin = time.time() connection_success = False last_exception = None while time.time() - begin < timeout: yield from asyncio.sleep(0.01) try: self._reader, self._writer = yield from asyncio.wait_for(asyncio.open_connection(host, self._port), timeout=1) except (asyncio.TimeoutError, OSError) as e: last_exception = e continue connection_success = True break if not connection_success: raise DynamipsError("Couldn't connect to hypervisor on {}:{} :{}".format(host, self._port, last_exception)) else: log.info("Connected to Dynamips hypervisor after {:.4f} seconds".format(time.time() - begin)) try: version = yield from self.send("hypervisor version") self._version = version[0].split("-", 1)[0] except IndexError: self._version = "Unknown" # this forces to send the working dir to Dynamips yield from self.set_working_dir(self._working_dir)
[ "def", "connect", "(", "self", ",", "timeout", "=", "10", ")", ":", "# connect to a local address by default", "# if listening to all addresses (IPv4 or IPv6)", "if", "self", ".", "_host", "==", "\"0.0.0.0\"", ":", "host", "=", "\"127.0.0.1\"", "elif", "self", ".", ...
Connects to the hypervisor.
[ "Connects", "to", "the", "hypervisor", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/dynamips_hypervisor.py#L63-L102
train
221,261
GNS3/gns3-server
gns3server/compute/dynamips/dynamips_hypervisor.py
DynamipsHypervisor.set_working_dir
def set_working_dir(self, working_dir): """ Sets the working directory for this hypervisor. :param working_dir: path to the working directory """ # encase working_dir in quotes to protect spaces in the path yield from self.send('hypervisor working_dir "{}"'.format(working_dir)) self._working_dir = working_dir log.debug("Working directory set to {}".format(self._working_dir))
python
def set_working_dir(self, working_dir): """ Sets the working directory for this hypervisor. :param working_dir: path to the working directory """ # encase working_dir in quotes to protect spaces in the path yield from self.send('hypervisor working_dir "{}"'.format(working_dir)) self._working_dir = working_dir log.debug("Working directory set to {}".format(self._working_dir))
[ "def", "set_working_dir", "(", "self", ",", "working_dir", ")", ":", "# encase working_dir in quotes to protect spaces in the path", "yield", "from", "self", ".", "send", "(", "'hypervisor working_dir \"{}\"'", ".", "format", "(", "working_dir", ")", ")", "self", ".", ...
Sets the working directory for this hypervisor. :param working_dir: path to the working directory
[ "Sets", "the", "working", "directory", "for", "this", "hypervisor", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/dynamips_hypervisor.py#L152-L162
train
221,262
GNS3/gns3-server
gns3server/utils/asyncio/embed_shell.py
create_stdin_shell
def create_stdin_shell(shell, loop=None): """ Run a shell application with a stdin frontend :param application: An EmbedShell instance :param loop: The event loop :returns: Telnet server """ @asyncio.coroutine def feed_stdin(loop, reader, shell): history = InMemoryHistory() completer = WordCompleter([name for name, _ in shell.get_commands()], ignore_case=True) while True: line = yield from prompt( ">", patch_stdout=True, return_asyncio_coroutine=True, history=history, completer=completer) line += '\n' reader.feed_data(line.encode()) @asyncio.coroutine def read_stdout(writer): while True: c = yield from writer.read(1) print(c.decode(), end='') sys.stdout.flush() reader = asyncio.StreamReader() writer = asyncio.StreamReader() shell.reader = reader shell.writer = writer if loop is None: loop = asyncio.get_event_loop() reader_task = loop.create_task(feed_stdin(loop, reader, shell)) writer_task = loop.create_task(read_stdout(writer)) shell_task = loop.create_task(shell.run()) return asyncio.gather(shell_task, writer_task, reader_task)
python
def create_stdin_shell(shell, loop=None): """ Run a shell application with a stdin frontend :param application: An EmbedShell instance :param loop: The event loop :returns: Telnet server """ @asyncio.coroutine def feed_stdin(loop, reader, shell): history = InMemoryHistory() completer = WordCompleter([name for name, _ in shell.get_commands()], ignore_case=True) while True: line = yield from prompt( ">", patch_stdout=True, return_asyncio_coroutine=True, history=history, completer=completer) line += '\n' reader.feed_data(line.encode()) @asyncio.coroutine def read_stdout(writer): while True: c = yield from writer.read(1) print(c.decode(), end='') sys.stdout.flush() reader = asyncio.StreamReader() writer = asyncio.StreamReader() shell.reader = reader shell.writer = writer if loop is None: loop = asyncio.get_event_loop() reader_task = loop.create_task(feed_stdin(loop, reader, shell)) writer_task = loop.create_task(read_stdout(writer)) shell_task = loop.create_task(shell.run()) return asyncio.gather(shell_task, writer_task, reader_task)
[ "def", "create_stdin_shell", "(", "shell", ",", "loop", "=", "None", ")", ":", "@", "asyncio", ".", "coroutine", "def", "feed_stdin", "(", "loop", ",", "reader", ",", "shell", ")", ":", "history", "=", "InMemoryHistory", "(", ")", "completer", "=", "Word...
Run a shell application with a stdin frontend :param application: An EmbedShell instance :param loop: The event loop :returns: Telnet server
[ "Run", "a", "shell", "application", "with", "a", "stdin", "frontend" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/embed_shell.py#L300-L335
train
221,263
GNS3/gns3-server
gns3server/utils/asyncio/embed_shell.py
ShellConnection.reset
def reset(self): """ Resets terminal screen""" self._cli.reset() self._cli.buffers[DEFAULT_BUFFER].reset() self._cli.renderer.request_absolute_cursor_position() self._cli._redraw()
python
def reset(self): """ Resets terminal screen""" self._cli.reset() self._cli.buffers[DEFAULT_BUFFER].reset() self._cli.renderer.request_absolute_cursor_position() self._cli._redraw()
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_cli", ".", "reset", "(", ")", "self", ".", "_cli", ".", "buffers", "[", "DEFAULT_BUFFER", "]", ".", "reset", "(", ")", "self", ".", "_cli", ".", "renderer", ".", "request_absolute_cursor_position", ...
Resets terminal screen
[ "Resets", "terminal", "screen" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/embed_shell.py#L267-L272
train
221,264
GNS3/gns3-server
gns3server/compute/project_manager.py
ProjectManager.get_project
def get_project(self, project_id): """ Returns a Project instance. :param project_id: Project identifier :returns: Project instance """ try: UUID(project_id, version=4) except ValueError: raise aiohttp.web.HTTPBadRequest(text="Project ID {} is not a valid UUID".format(project_id)) if project_id not in self._projects: raise aiohttp.web.HTTPNotFound(text="Project ID {} doesn't exist".format(project_id)) return self._projects[project_id]
python
def get_project(self, project_id): """ Returns a Project instance. :param project_id: Project identifier :returns: Project instance """ try: UUID(project_id, version=4) except ValueError: raise aiohttp.web.HTTPBadRequest(text="Project ID {} is not a valid UUID".format(project_id)) if project_id not in self._projects: raise aiohttp.web.HTTPNotFound(text="Project ID {} doesn't exist".format(project_id)) return self._projects[project_id]
[ "def", "get_project", "(", "self", ",", "project_id", ")", ":", "try", ":", "UUID", "(", "project_id", ",", "version", "=", "4", ")", "except", "ValueError", ":", "raise", "aiohttp", ".", "web", ".", "HTTPBadRequest", "(", "text", "=", "\"Project ID {} is ...
Returns a Project instance. :param project_id: Project identifier :returns: Project instance
[ "Returns", "a", "Project", "instance", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/project_manager.py#L60-L76
train
221,265
GNS3/gns3-server
gns3server/compute/project_manager.py
ProjectManager._check_available_disk_space
def _check_available_disk_space(self, project): """ Sends a warning notification if disk space is getting low. :param project: project instance """ try: used_disk_space = psutil.disk_usage(project.path).percent except FileNotFoundError: log.warning('Could not find "{}" when checking for used disk space'.format(project.path)) return # send a warning if used disk space is >= 90% if used_disk_space >= 90: message = 'Only {}% or less of disk space detected in "{}" on "{}"'.format(used_disk_space, project.path, platform.node()) log.warning(message) project.emit("log.warning", {"message": message})
python
def _check_available_disk_space(self, project): """ Sends a warning notification if disk space is getting low. :param project: project instance """ try: used_disk_space = psutil.disk_usage(project.path).percent except FileNotFoundError: log.warning('Could not find "{}" when checking for used disk space'.format(project.path)) return # send a warning if used disk space is >= 90% if used_disk_space >= 90: message = 'Only {}% or less of disk space detected in "{}" on "{}"'.format(used_disk_space, project.path, platform.node()) log.warning(message) project.emit("log.warning", {"message": message})
[ "def", "_check_available_disk_space", "(", "self", ",", "project", ")", ":", "try", ":", "used_disk_space", "=", "psutil", ".", "disk_usage", "(", "project", ".", "path", ")", ".", "percent", "except", "FileNotFoundError", ":", "log", ".", "warning", "(", "'...
Sends a warning notification if disk space is getting low. :param project: project instance
[ "Sends", "a", "warning", "notification", "if", "disk", "space", "is", "getting", "low", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/project_manager.py#L78-L96
train
221,266
GNS3/gns3-server
gns3server/compute/project_manager.py
ProjectManager.create_project
def create_project(self, name=None, project_id=None, path=None): """ Create a project and keep a references to it in project manager. See documentation of Project for arguments """ if project_id is not None and project_id in self._projects: return self._projects[project_id] project = Project(name=name, project_id=project_id, path=path) self._check_available_disk_space(project) self._projects[project.id] = project return project
python
def create_project(self, name=None, project_id=None, path=None): """ Create a project and keep a references to it in project manager. See documentation of Project for arguments """ if project_id is not None and project_id in self._projects: return self._projects[project_id] project = Project(name=name, project_id=project_id, path=path) self._check_available_disk_space(project) self._projects[project.id] = project return project
[ "def", "create_project", "(", "self", ",", "name", "=", "None", ",", "project_id", "=", "None", ",", "path", "=", "None", ")", ":", "if", "project_id", "is", "not", "None", "and", "project_id", "in", "self", ".", "_projects", ":", "return", "self", "."...
Create a project and keep a references to it in project manager. See documentation of Project for arguments
[ "Create", "a", "project", "and", "keep", "a", "references", "to", "it", "in", "project", "manager", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/project_manager.py#L98-L110
train
221,267
GNS3/gns3-server
gns3server/compute/project_manager.py
ProjectManager.remove_project
def remove_project(self, project_id): """ Removes a Project instance from the list of projects in use. :param project_id: Project identifier """ if project_id not in self._projects: raise aiohttp.web.HTTPNotFound(text="Project ID {} doesn't exist".format(project_id)) del self._projects[project_id]
python
def remove_project(self, project_id): """ Removes a Project instance from the list of projects in use. :param project_id: Project identifier """ if project_id not in self._projects: raise aiohttp.web.HTTPNotFound(text="Project ID {} doesn't exist".format(project_id)) del self._projects[project_id]
[ "def", "remove_project", "(", "self", ",", "project_id", ")", ":", "if", "project_id", "not", "in", "self", ".", "_projects", ":", "raise", "aiohttp", ".", "web", ".", "HTTPNotFound", "(", "text", "=", "\"Project ID {} doesn't exist\"", ".", "format", "(", "...
Removes a Project instance from the list of projects in use. :param project_id: Project identifier
[ "Removes", "a", "Project", "instance", "from", "the", "list", "of", "projects", "in", "use", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/project_manager.py#L112-L121
train
221,268
GNS3/gns3-server
gns3server/compute/project_manager.py
ProjectManager.check_hardware_virtualization
def check_hardware_virtualization(self, source_node): """ Checks if hardware virtualization can be used. :returns: boolean """ for project in self._projects.values(): for node in project.nodes: if node == source_node: continue if node.hw_virtualization and node.__class__.__name__ != source_node.__class__.__name__: return False return True
python
def check_hardware_virtualization(self, source_node): """ Checks if hardware virtualization can be used. :returns: boolean """ for project in self._projects.values(): for node in project.nodes: if node == source_node: continue if node.hw_virtualization and node.__class__.__name__ != source_node.__class__.__name__: return False return True
[ "def", "check_hardware_virtualization", "(", "self", ",", "source_node", ")", ":", "for", "project", "in", "self", ".", "_projects", ".", "values", "(", ")", ":", "for", "node", "in", "project", ".", "nodes", ":", "if", "node", "==", "source_node", ":", ...
Checks if hardware virtualization can be used. :returns: boolean
[ "Checks", "if", "hardware", "virtualization", "can", "be", "used", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/project_manager.py#L123-L136
train
221,269
GNS3/gns3-server
gns3server/compute/builtin/nodes/cloud.py
Cloud.ports_mapping
def ports_mapping(self, ports): """ Set the ports on this cloud. :param ports: ports info """ if ports != self._ports_mapping: if len(self._nios) > 0: raise NodeError("Can't modify a cloud already connected.") port_number = 0 for port in ports: port["port_number"] = port_number port_number += 1 self._ports_mapping = ports
python
def ports_mapping(self, ports): """ Set the ports on this cloud. :param ports: ports info """ if ports != self._ports_mapping: if len(self._nios) > 0: raise NodeError("Can't modify a cloud already connected.") port_number = 0 for port in ports: port["port_number"] = port_number port_number += 1 self._ports_mapping = ports
[ "def", "ports_mapping", "(", "self", ",", "ports", ")", ":", "if", "ports", "!=", "self", ".", "_ports_mapping", ":", "if", "len", "(", "self", ".", "_nios", ")", ">", "0", ":", "raise", "NodeError", "(", "\"Can't modify a cloud already connected.\"", ")", ...
Set the ports on this cloud. :param ports: ports info
[ "Set", "the", "ports", "on", "this", "cloud", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/builtin/nodes/cloud.py#L103-L119
train
221,270
GNS3/gns3-server
gns3server/compute/builtin/nodes/cloud.py
Cloud.close
def close(self): """ Closes this cloud. """ if not (yield from super().close()): return False for nio in self._nios.values(): if nio and isinstance(nio, NIOUDP): self.manager.port_manager.release_udp_port(nio.lport, self._project) yield from self._stop_ubridge() log.info('Cloud "{name}" [{id}] has been closed'.format(name=self._name, id=self._id))
python
def close(self): """ Closes this cloud. """ if not (yield from super().close()): return False for nio in self._nios.values(): if nio and isinstance(nio, NIOUDP): self.manager.port_manager.release_udp_port(nio.lport, self._project) yield from self._stop_ubridge() log.info('Cloud "{name}" [{id}] has been closed'.format(name=self._name, id=self._id))
[ "def", "close", "(", "self", ")", ":", "if", "not", "(", "yield", "from", "super", "(", ")", ".", "close", "(", ")", ")", ":", "return", "False", "for", "nio", "in", "self", ".", "_nios", ".", "values", "(", ")", ":", "if", "nio", "and", "isins...
Closes this cloud.
[ "Closes", "this", "cloud", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/builtin/nodes/cloud.py#L146-L159
train
221,271
GNS3/gns3-server
gns3server/compute/builtin/nodes/cloud.py
Cloud._add_linux_ethernet
def _add_linux_ethernet(self, port_info, bridge_name): """ Use raw sockets on Linux. If interface is a bridge we connect a tap to it """ interface = port_info["interface"] if gns3server.utils.interfaces.is_interface_bridge(interface): network_interfaces = [interface["name"] for interface in self._interfaces()] i = 0 while True: tap = "gns3tap{}-{}".format(i, port_info["port_number"]) if tap not in network_interfaces: break i += 1 yield from self._ubridge_send('bridge add_nio_tap "{name}" "{interface}"'.format(name=bridge_name, interface=tap)) yield from self._ubridge_send('brctl addif "{interface}" "{tap}"'.format(tap=tap, interface=interface)) else: yield from self._ubridge_send('bridge add_nio_linux_raw {name} "{interface}"'.format(name=bridge_name, interface=interface))
python
def _add_linux_ethernet(self, port_info, bridge_name): """ Use raw sockets on Linux. If interface is a bridge we connect a tap to it """ interface = port_info["interface"] if gns3server.utils.interfaces.is_interface_bridge(interface): network_interfaces = [interface["name"] for interface in self._interfaces()] i = 0 while True: tap = "gns3tap{}-{}".format(i, port_info["port_number"]) if tap not in network_interfaces: break i += 1 yield from self._ubridge_send('bridge add_nio_tap "{name}" "{interface}"'.format(name=bridge_name, interface=tap)) yield from self._ubridge_send('brctl addif "{interface}" "{tap}"'.format(tap=tap, interface=interface)) else: yield from self._ubridge_send('bridge add_nio_linux_raw {name} "{interface}"'.format(name=bridge_name, interface=interface))
[ "def", "_add_linux_ethernet", "(", "self", ",", "port_info", ",", "bridge_name", ")", ":", "interface", "=", "port_info", "[", "\"interface\"", "]", "if", "gns3server", ".", "utils", ".", "interfaces", ".", "is_interface_bridge", "(", "interface", ")", ":", "n...
Use raw sockets on Linux. If interface is a bridge we connect a tap to it
[ "Use", "raw", "sockets", "on", "Linux", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/builtin/nodes/cloud.py#L245-L265
train
221,272
GNS3/gns3-server
gns3server/compute/builtin/nodes/cloud.py
Cloud.add_nio
def add_nio(self, nio, port_number): """ Adds a NIO as new port on this cloud. :param nio: NIO instance to add :param port_number: port to allocate for the NIO """ if port_number in self._nios: raise NodeError("Port {} isn't free".format(port_number)) log.info('Cloud "{name}" [{id}]: NIO {nio} bound to port {port}'.format(name=self._name, id=self._id, nio=nio, port=port_number)) try: yield from self.start() yield from self._add_ubridge_connection(nio, port_number) self._nios[port_number] = nio except NodeError as e: self.project.emit("log.error", {"message": str(e)}) yield from self._stop_ubridge() self.status = "stopped" self._nios[port_number] = nio # Cleanup stuff except UbridgeError as e: self.project.emit("log.error", {"message": str(e)}) yield from self._stop_ubridge() self.status = "stopped" self._nios[port_number] = nio
python
def add_nio(self, nio, port_number): """ Adds a NIO as new port on this cloud. :param nio: NIO instance to add :param port_number: port to allocate for the NIO """ if port_number in self._nios: raise NodeError("Port {} isn't free".format(port_number)) log.info('Cloud "{name}" [{id}]: NIO {nio} bound to port {port}'.format(name=self._name, id=self._id, nio=nio, port=port_number)) try: yield from self.start() yield from self._add_ubridge_connection(nio, port_number) self._nios[port_number] = nio except NodeError as e: self.project.emit("log.error", {"message": str(e)}) yield from self._stop_ubridge() self.status = "stopped" self._nios[port_number] = nio # Cleanup stuff except UbridgeError as e: self.project.emit("log.error", {"message": str(e)}) yield from self._stop_ubridge() self.status = "stopped" self._nios[port_number] = nio
[ "def", "add_nio", "(", "self", ",", "nio", ",", "port_number", ")", ":", "if", "port_number", "in", "self", ".", "_nios", ":", "raise", "NodeError", "(", "\"Port {} isn't free\"", ".", "format", "(", "port_number", ")", ")", "log", ".", "info", "(", "'Cl...
Adds a NIO as new port on this cloud. :param nio: NIO instance to add :param port_number: port to allocate for the NIO
[ "Adds", "a", "NIO", "as", "new", "port", "on", "this", "cloud", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/builtin/nodes/cloud.py#L288-L317
train
221,273
GNS3/gns3-server
gns3server/compute/builtin/nodes/cloud.py
Cloud.update_nio
def update_nio(self, port_number, nio): """ Update an nio on this node :param nio: NIO instance to add :param port_number: port to allocate for the NIO """ bridge_name = "{}-{}".format(self._id, port_number) if self._ubridge_hypervisor and self._ubridge_hypervisor.is_running(): yield from self._ubridge_apply_filters(bridge_name, nio.filters)
python
def update_nio(self, port_number, nio): """ Update an nio on this node :param nio: NIO instance to add :param port_number: port to allocate for the NIO """ bridge_name = "{}-{}".format(self._id, port_number) if self._ubridge_hypervisor and self._ubridge_hypervisor.is_running(): yield from self._ubridge_apply_filters(bridge_name, nio.filters)
[ "def", "update_nio", "(", "self", ",", "port_number", ",", "nio", ")", ":", "bridge_name", "=", "\"{}-{}\"", ".", "format", "(", "self", ".", "_id", ",", "port_number", ")", "if", "self", ".", "_ubridge_hypervisor", "and", "self", ".", "_ubridge_hypervisor",...
Update an nio on this node :param nio: NIO instance to add :param port_number: port to allocate for the NIO
[ "Update", "an", "nio", "on", "this", "node" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/builtin/nodes/cloud.py#L320-L330
train
221,274
GNS3/gns3-server
gns3server/compute/builtin/nodes/cloud.py
Cloud.remove_nio
def remove_nio(self, port_number): """ Removes the specified NIO as member of cloud. :param port_number: allocated port number :returns: the NIO that was bound to the allocated port """ if port_number not in self._nios: raise NodeError("Port {} is not allocated".format(port_number)) nio = self._nios[port_number] if isinstance(nio, NIOUDP): self.manager.port_manager.release_udp_port(nio.lport, self._project) log.info('Cloud "{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] if self._ubridge_hypervisor and self._ubridge_hypervisor.is_running(): yield from self._delete_ubridge_connection(port_number) yield from self.start() return nio
python
def remove_nio(self, port_number): """ Removes the specified NIO as member of cloud. :param port_number: allocated port number :returns: the NIO that was bound to the allocated port """ if port_number not in self._nios: raise NodeError("Port {} is not allocated".format(port_number)) nio = self._nios[port_number] if isinstance(nio, NIOUDP): self.manager.port_manager.release_udp_port(nio.lport, self._project) log.info('Cloud "{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] if self._ubridge_hypervisor and self._ubridge_hypervisor.is_running(): yield from self._delete_ubridge_connection(port_number) yield from self.start() return nio
[ "def", "remove_nio", "(", "self", ",", "port_number", ")", ":", "if", "port_number", "not", "in", "self", ".", "_nios", ":", "raise", "NodeError", "(", "\"Port {} is not allocated\"", ".", "format", "(", "port_number", ")", ")", "nio", "=", "self", ".", "_...
Removes the specified NIO as member of cloud. :param port_number: allocated port number :returns: the NIO that was bound to the allocated port
[ "Removes", "the", "specified", "NIO", "as", "member", "of", "cloud", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/builtin/nodes/cloud.py#L344-L369
train
221,275
GNS3/gns3-server
gns3server/run.py
pid_lock
def pid_lock(path): """ Write the file in a file on the system. Check if the process is not already running. """ if os.path.exists(path): pid = None try: with open(path) as f: try: pid = int(f.read()) os.kill(pid, 0) # kill returns an error if the process is not running except (OSError, SystemError, ValueError): pid = None except OSError as e: log.critical("Can't open pid file %s: %s", pid, str(e)) sys.exit(1) if pid: log.critical("GNS3 is already running pid: %d", pid) sys.exit(1) try: with open(path, 'w+') as f: f.write(str(os.getpid())) except OSError as e: log.critical("Can't write pid file %s: %s", path, str(e)) sys.exit(1)
python
def pid_lock(path): """ Write the file in a file on the system. Check if the process is not already running. """ if os.path.exists(path): pid = None try: with open(path) as f: try: pid = int(f.read()) os.kill(pid, 0) # kill returns an error if the process is not running except (OSError, SystemError, ValueError): pid = None except OSError as e: log.critical("Can't open pid file %s: %s", pid, str(e)) sys.exit(1) if pid: log.critical("GNS3 is already running pid: %d", pid) sys.exit(1) try: with open(path, 'w+') as f: f.write(str(os.getpid())) except OSError as e: log.critical("Can't write pid file %s: %s", path, str(e)) sys.exit(1)
[ "def", "pid_lock", "(", "path", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "pid", "=", "None", "try", ":", "with", "open", "(", "path", ")", "as", "f", ":", "try", ":", "pid", "=", "int", "(", "f", ".", "read", ...
Write the file in a file on the system. Check if the process is not already running.
[ "Write", "the", "file", "in", "a", "file", "on", "the", "system", ".", "Check", "if", "the", "process", "is", "not", "already", "running", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/run.py#L151-L179
train
221,276
GNS3/gns3-server
gns3server/run.py
kill_ghosts
def kill_ghosts(): """ Kill process from previous GNS3 session """ detect_process = ["vpcs", "ubridge", "dynamips"] for proc in psutil.process_iter(): try: name = proc.name().lower().split(".")[0] if name in detect_process: proc.kill() log.warning("Killed ghost process %s", name) except (psutil.NoSuchProcess, psutil.AccessDenied): pass
python
def kill_ghosts(): """ Kill process from previous GNS3 session """ detect_process = ["vpcs", "ubridge", "dynamips"] for proc in psutil.process_iter(): try: name = proc.name().lower().split(".")[0] if name in detect_process: proc.kill() log.warning("Killed ghost process %s", name) except (psutil.NoSuchProcess, psutil.AccessDenied): pass
[ "def", "kill_ghosts", "(", ")", ":", "detect_process", "=", "[", "\"vpcs\"", ",", "\"ubridge\"", ",", "\"dynamips\"", "]", "for", "proc", "in", "psutil", ".", "process_iter", "(", ")", ":", "try", ":", "name", "=", "proc", ".", "name", "(", ")", ".", ...
Kill process from previous GNS3 session
[ "Kill", "process", "from", "previous", "GNS3", "session" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/run.py#L182-L194
train
221,277
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.qemu_path
def qemu_path(self, qemu_path): """ Sets the QEMU binary path this QEMU VM. :param qemu_path: QEMU path """ if qemu_path and os.pathsep not in qemu_path: if sys.platform.startswith("win") and ".exe" not in qemu_path.lower(): qemu_path += "w.exe" new_qemu_path = shutil.which(qemu_path, path=os.pathsep.join(self._manager.paths_list())) if new_qemu_path is None: raise QemuError("QEMU binary path {} is not found in the path".format(qemu_path)) qemu_path = new_qemu_path self._check_qemu_path(qemu_path) self._qemu_path = qemu_path self._platform = os.path.basename(qemu_path) if self._platform == "qemu-kvm": self._platform = "x86_64" else: qemu_bin = os.path.basename(qemu_path) qemu_bin = re.sub(r'(w)?\.(exe|EXE)$', '', qemu_bin) # Old version of GNS3 provide a binary named qemu.exe if qemu_bin == "qemu": self._platform = "i386" else: self._platform = re.sub(r'^qemu-system-(.*)$', r'\1', qemu_bin, re.IGNORECASE) if self._platform.split(".")[0] not in QEMU_PLATFORMS: raise QemuError("Platform {} is unknown".format(self._platform)) log.info('QEMU VM "{name}" [{id}] has set the QEMU path to {qemu_path}'.format(name=self._name, id=self._id, qemu_path=qemu_path))
python
def qemu_path(self, qemu_path): """ Sets the QEMU binary path this QEMU VM. :param qemu_path: QEMU path """ if qemu_path and os.pathsep not in qemu_path: if sys.platform.startswith("win") and ".exe" not in qemu_path.lower(): qemu_path += "w.exe" new_qemu_path = shutil.which(qemu_path, path=os.pathsep.join(self._manager.paths_list())) if new_qemu_path is None: raise QemuError("QEMU binary path {} is not found in the path".format(qemu_path)) qemu_path = new_qemu_path self._check_qemu_path(qemu_path) self._qemu_path = qemu_path self._platform = os.path.basename(qemu_path) if self._platform == "qemu-kvm": self._platform = "x86_64" else: qemu_bin = os.path.basename(qemu_path) qemu_bin = re.sub(r'(w)?\.(exe|EXE)$', '', qemu_bin) # Old version of GNS3 provide a binary named qemu.exe if qemu_bin == "qemu": self._platform = "i386" else: self._platform = re.sub(r'^qemu-system-(.*)$', r'\1', qemu_bin, re.IGNORECASE) if self._platform.split(".")[0] not in QEMU_PLATFORMS: raise QemuError("Platform {} is unknown".format(self._platform)) log.info('QEMU VM "{name}" [{id}] has set the QEMU path to {qemu_path}'.format(name=self._name, id=self._id, qemu_path=qemu_path))
[ "def", "qemu_path", "(", "self", ",", "qemu_path", ")", ":", "if", "qemu_path", "and", "os", ".", "pathsep", "not", "in", "qemu_path", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", "and", "\".exe\"", "not", "in", "qemu_path",...
Sets the QEMU binary path this QEMU VM. :param qemu_path: QEMU path
[ "Sets", "the", "QEMU", "binary", "path", "this", "QEMU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L146-L178
train
221,278
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM._disk_setter
def _disk_setter(self, variable, value): """ Use by disk image setter for checking and apply modifications :param variable: Variable name in the class :param value: New disk value """ value = self.manager.get_abs_image_path(value) if not self.linked_clone: for node in self.manager.nodes: if node != self and getattr(node, variable) == value: raise QemuError("Sorry a node without the linked base setting enabled can only be used once on your server. {} is already used by {}".format(value, node.name)) setattr(self, "_" + variable, value) log.info('QEMU VM "{name}" [{id}] has set the QEMU {variable} path to {disk_image}'.format(name=self._name, variable=variable, id=self._id, disk_image=value))
python
def _disk_setter(self, variable, value): """ Use by disk image setter for checking and apply modifications :param variable: Variable name in the class :param value: New disk value """ value = self.manager.get_abs_image_path(value) if not self.linked_clone: for node in self.manager.nodes: if node != self and getattr(node, variable) == value: raise QemuError("Sorry a node without the linked base setting enabled can only be used once on your server. {} is already used by {}".format(value, node.name)) setattr(self, "_" + variable, value) log.info('QEMU VM "{name}" [{id}] has set the QEMU {variable} path to {disk_image}'.format(name=self._name, variable=variable, id=self._id, disk_image=value))
[ "def", "_disk_setter", "(", "self", ",", "variable", ",", "value", ")", ":", "value", "=", "self", ".", "manager", ".", "get_abs_image_path", "(", "value", ")", "if", "not", "self", ".", "linked_clone", ":", "for", "node", "in", "self", ".", "manager", ...
Use by disk image setter for checking and apply modifications :param variable: Variable name in the class :param value: New disk value
[ "Use", "by", "disk", "image", "setter", "for", "checking", "and", "apply", "modifications" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L203-L219
train
221,279
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.hdc_disk_interface
def hdc_disk_interface(self, hdc_disk_interface): """ Sets the hdc disk interface for this QEMU VM. :param hdc_disk_interface: QEMU hdc disk interface """ self._hdc_disk_interface = hdc_disk_interface log.info('QEMU VM "{name}" [{id}] has set the QEMU hdc disk interface to {interface}'.format(name=self._name, id=self._id, interface=self._hdc_disk_interface))
python
def hdc_disk_interface(self, hdc_disk_interface): """ Sets the hdc disk interface for this QEMU VM. :param hdc_disk_interface: QEMU hdc disk interface """ self._hdc_disk_interface = hdc_disk_interface log.info('QEMU VM "{name}" [{id}] has set the QEMU hdc disk interface to {interface}'.format(name=self._name, id=self._id, interface=self._hdc_disk_interface))
[ "def", "hdc_disk_interface", "(", "self", ",", "hdc_disk_interface", ")", ":", "self", ".", "_hdc_disk_interface", "=", "hdc_disk_interface", "log", ".", "info", "(", "'QEMU VM \"{name}\" [{id}] has set the QEMU hdc disk interface to {interface}'", ".", "format", "(", "name...
Sets the hdc disk interface for this QEMU VM. :param hdc_disk_interface: QEMU hdc disk interface
[ "Sets", "the", "hdc", "disk", "interface", "for", "this", "QEMU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L357-L367
train
221,280
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.hdd_disk_interface
def hdd_disk_interface(self, hdd_disk_interface): """ Sets the hdd disk interface for this QEMU VM. :param hdd_disk_interface: QEMU hdd disk interface """ self._hdd_disk_interface = hdd_disk_interface log.info('QEMU VM "{name}" [{id}] has set the QEMU hdd disk interface to {interface}'.format(name=self._name, id=self._id, interface=self._hdd_disk_interface))
python
def hdd_disk_interface(self, hdd_disk_interface): """ Sets the hdd disk interface for this QEMU VM. :param hdd_disk_interface: QEMU hdd disk interface """ self._hdd_disk_interface = hdd_disk_interface log.info('QEMU VM "{name}" [{id}] has set the QEMU hdd disk interface to {interface}'.format(name=self._name, id=self._id, interface=self._hdd_disk_interface))
[ "def", "hdd_disk_interface", "(", "self", ",", "hdd_disk_interface", ")", ":", "self", ".", "_hdd_disk_interface", "=", "hdd_disk_interface", "log", ".", "info", "(", "'QEMU VM \"{name}\" [{id}] has set the QEMU hdd disk interface to {interface}'", ".", "format", "(", "name...
Sets the hdd disk interface for this QEMU VM. :param hdd_disk_interface: QEMU hdd disk interface
[ "Sets", "the", "hdd", "disk", "interface", "for", "this", "QEMU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L380-L390
train
221,281
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.cdrom_image
def cdrom_image(self, cdrom_image): """ Sets the cdrom image for this QEMU VM. :param cdrom_image: QEMU cdrom image path """ self._cdrom_image = self.manager.get_abs_image_path(cdrom_image) log.info('QEMU VM "{name}" [{id}] has set the QEMU cdrom image path to {cdrom_image}'.format(name=self._name, id=self._id, cdrom_image=self._cdrom_image))
python
def cdrom_image(self, cdrom_image): """ Sets the cdrom image for this QEMU VM. :param cdrom_image: QEMU cdrom image path """ self._cdrom_image = self.manager.get_abs_image_path(cdrom_image) log.info('QEMU VM "{name}" [{id}] has set the QEMU cdrom image path to {cdrom_image}'.format(name=self._name, id=self._id, cdrom_image=self._cdrom_image))
[ "def", "cdrom_image", "(", "self", ",", "cdrom_image", ")", ":", "self", ".", "_cdrom_image", "=", "self", ".", "manager", ".", "get_abs_image_path", "(", "cdrom_image", ")", "log", ".", "info", "(", "'QEMU VM \"{name}\" [{id}] has set the QEMU cdrom image path to {cd...
Sets the cdrom image for this QEMU VM. :param cdrom_image: QEMU cdrom image path
[ "Sets", "the", "cdrom", "image", "for", "this", "QEMU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L403-L412
train
221,282
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.bios_image
def bios_image(self, bios_image): """ Sets the bios image for this QEMU VM. :param bios_image: QEMU bios image path """ self._bios_image = self.manager.get_abs_image_path(bios_image) log.info('QEMU VM "{name}" [{id}] has set the QEMU bios image path to {bios_image}'.format(name=self._name, id=self._id, bios_image=self._bios_image))
python
def bios_image(self, bios_image): """ Sets the bios image for this QEMU VM. :param bios_image: QEMU bios image path """ self._bios_image = self.manager.get_abs_image_path(bios_image) log.info('QEMU VM "{name}" [{id}] has set the QEMU bios image path to {bios_image}'.format(name=self._name, id=self._id, bios_image=self._bios_image))
[ "def", "bios_image", "(", "self", ",", "bios_image", ")", ":", "self", ".", "_bios_image", "=", "self", ".", "manager", ".", "get_abs_image_path", "(", "bios_image", ")", "log", ".", "info", "(", "'QEMU VM \"{name}\" [{id}] has set the QEMU bios image path to {bios_im...
Sets the bios image for this QEMU VM. :param bios_image: QEMU bios image path
[ "Sets", "the", "bios", "image", "for", "this", "QEMU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L425-L434
train
221,283
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.boot_priority
def boot_priority(self, boot_priority): """ Sets the boot priority for this QEMU VM. :param boot_priority: QEMU boot priority """ self._boot_priority = boot_priority log.info('QEMU VM "{name}" [{id}] has set the boot priority to {boot_priority}'.format(name=self._name, id=self._id, boot_priority=self._boot_priority))
python
def boot_priority(self, boot_priority): """ Sets the boot priority for this QEMU VM. :param boot_priority: QEMU boot priority """ self._boot_priority = boot_priority log.info('QEMU VM "{name}" [{id}] has set the boot priority to {boot_priority}'.format(name=self._name, id=self._id, boot_priority=self._boot_priority))
[ "def", "boot_priority", "(", "self", ",", "boot_priority", ")", ":", "self", ".", "_boot_priority", "=", "boot_priority", "log", ".", "info", "(", "'QEMU VM \"{name}\" [{id}] has set the boot priority to {boot_priority}'", ".", "format", "(", "name", "=", "self", ".",...
Sets the boot priority for this QEMU VM. :param boot_priority: QEMU boot priority
[ "Sets", "the", "boot", "priority", "for", "this", "QEMU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L447-L457
train
221,284
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.adapters
def adapters(self, adapters): """ Sets the number of Ethernet adapters for this QEMU VM. :param adapters: number of adapters """ self._ethernet_adapters.clear() for adapter_number in range(0, adapters): self._ethernet_adapters.append(EthernetAdapter()) log.info('QEMU VM "{name}" [{id}]: number of Ethernet adapters changed to {adapters}'.format(name=self._name, id=self._id, adapters=adapters))
python
def adapters(self, adapters): """ Sets the number of Ethernet adapters for this QEMU VM. :param adapters: number of adapters """ self._ethernet_adapters.clear() for adapter_number in range(0, adapters): self._ethernet_adapters.append(EthernetAdapter()) log.info('QEMU VM "{name}" [{id}]: number of Ethernet adapters changed to {adapters}'.format(name=self._name, id=self._id, adapters=adapters))
[ "def", "adapters", "(", "self", ",", "adapters", ")", ":", "self", ".", "_ethernet_adapters", ".", "clear", "(", ")", "for", "adapter_number", "in", "range", "(", "0", ",", "adapters", ")", ":", "self", ".", "_ethernet_adapters", ".", "append", "(", "Eth...
Sets the number of Ethernet adapters for this QEMU VM. :param adapters: number of adapters
[ "Sets", "the", "number", "of", "Ethernet", "adapters", "for", "this", "QEMU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L477-L490
train
221,285
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.mac_address
def mac_address(self, mac_address): """ Sets the MAC address for this QEMU VM. :param mac_address: MAC address """ if not mac_address: # use the node UUID to generate a random MAC address self._mac_address = "52:%s:%s:%s:%s:00" % (self.project.id[-4:-2], self.project.id[-2:], self.id[-4:-2], self.id[-2:]) else: self._mac_address = mac_address log.info('QEMU VM "{name}" [{id}]: MAC address changed to {mac_addr}'.format(name=self._name, id=self._id, mac_addr=self._mac_address))
python
def mac_address(self, mac_address): """ Sets the MAC address for this QEMU VM. :param mac_address: MAC address """ if not mac_address: # use the node UUID to generate a random MAC address self._mac_address = "52:%s:%s:%s:%s:00" % (self.project.id[-4:-2], self.project.id[-2:], self.id[-4:-2], self.id[-2:]) else: self._mac_address = mac_address log.info('QEMU VM "{name}" [{id}]: MAC address changed to {mac_addr}'.format(name=self._name, id=self._id, mac_addr=self._mac_address))
[ "def", "mac_address", "(", "self", ",", "mac_address", ")", ":", "if", "not", "mac_address", ":", "# use the node UUID to generate a random MAC address", "self", ".", "_mac_address", "=", "\"52:%s:%s:%s:%s:00\"", "%", "(", "self", ".", "project", ".", "id", "[", "...
Sets the MAC address for this QEMU VM. :param mac_address: MAC address
[ "Sets", "the", "MAC", "address", "for", "this", "QEMU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L527-L542
train
221,286
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.legacy_networking
def legacy_networking(self, legacy_networking): """ Sets either QEMU legacy networking commands are used. :param legacy_networking: boolean """ if legacy_networking: log.info('QEMU VM "{name}" [{id}] has enabled legacy networking'.format(name=self._name, id=self._id)) else: log.info('QEMU VM "{name}" [{id}] has disabled legacy networking'.format(name=self._name, id=self._id)) self._legacy_networking = legacy_networking
python
def legacy_networking(self, legacy_networking): """ Sets either QEMU legacy networking commands are used. :param legacy_networking: boolean """ if legacy_networking: log.info('QEMU VM "{name}" [{id}] has enabled legacy networking'.format(name=self._name, id=self._id)) else: log.info('QEMU VM "{name}" [{id}] has disabled legacy networking'.format(name=self._name, id=self._id)) self._legacy_networking = legacy_networking
[ "def", "legacy_networking", "(", "self", ",", "legacy_networking", ")", ":", "if", "legacy_networking", ":", "log", ".", "info", "(", "'QEMU VM \"{name}\" [{id}] has enabled legacy networking'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "id", "="...
Sets either QEMU legacy networking commands are used. :param legacy_networking: boolean
[ "Sets", "either", "QEMU", "legacy", "networking", "commands", "are", "used", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L555-L566
train
221,287
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.acpi_shutdown
def acpi_shutdown(self, acpi_shutdown): """ Sets either this QEMU VM can be ACPI shutdown. :param acpi_shutdown: boolean """ if acpi_shutdown: log.info('QEMU VM "{name}" [{id}] has enabled ACPI shutdown'.format(name=self._name, id=self._id)) else: log.info('QEMU VM "{name}" [{id}] has disabled ACPI shutdown'.format(name=self._name, id=self._id)) self._acpi_shutdown = acpi_shutdown
python
def acpi_shutdown(self, acpi_shutdown): """ Sets either this QEMU VM can be ACPI shutdown. :param acpi_shutdown: boolean """ if acpi_shutdown: log.info('QEMU VM "{name}" [{id}] has enabled ACPI shutdown'.format(name=self._name, id=self._id)) else: log.info('QEMU VM "{name}" [{id}] has disabled ACPI shutdown'.format(name=self._name, id=self._id)) self._acpi_shutdown = acpi_shutdown
[ "def", "acpi_shutdown", "(", "self", ",", "acpi_shutdown", ")", ":", "if", "acpi_shutdown", ":", "log", ".", "info", "(", "'QEMU VM \"{name}\" [{id}] has enabled ACPI shutdown'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "id", "=", "self", "....
Sets either this QEMU VM can be ACPI shutdown. :param acpi_shutdown: boolean
[ "Sets", "either", "this", "QEMU", "VM", "can", "be", "ACPI", "shutdown", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L579-L590
train
221,288
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.cpu_throttling
def cpu_throttling(self, cpu_throttling): """ Sets the percentage of CPU allowed. :param cpu_throttling: integer """ log.info('QEMU VM "{name}" [{id}] has set the percentage of CPU allowed to {cpu}'.format(name=self._name, id=self._id, cpu=cpu_throttling)) self._cpu_throttling = cpu_throttling self._stop_cpulimit() if cpu_throttling: self._set_cpu_throttling()
python
def cpu_throttling(self, cpu_throttling): """ Sets the percentage of CPU allowed. :param cpu_throttling: integer """ log.info('QEMU VM "{name}" [{id}] has set the percentage of CPU allowed to {cpu}'.format(name=self._name, id=self._id, cpu=cpu_throttling)) self._cpu_throttling = cpu_throttling self._stop_cpulimit() if cpu_throttling: self._set_cpu_throttling()
[ "def", "cpu_throttling", "(", "self", ",", "cpu_throttling", ")", ":", "log", ".", "info", "(", "'QEMU VM \"{name}\" [{id}] has set the percentage of CPU allowed to {cpu}'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "id", "=", "self", ".", "_id",...
Sets the percentage of CPU allowed. :param cpu_throttling: integer
[ "Sets", "the", "percentage", "of", "CPU", "allowed", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L603-L616
train
221,289
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.process_priority
def process_priority(self, process_priority): """ Sets the process priority. :param process_priority: string """ log.info('QEMU VM "{name}" [{id}] has set the process priority to {priority}'.format(name=self._name, id=self._id, priority=process_priority)) self._process_priority = process_priority
python
def process_priority(self, process_priority): """ Sets the process priority. :param process_priority: string """ log.info('QEMU VM "{name}" [{id}] has set the process priority to {priority}'.format(name=self._name, id=self._id, priority=process_priority)) self._process_priority = process_priority
[ "def", "process_priority", "(", "self", ",", "process_priority", ")", ":", "log", ".", "info", "(", "'QEMU VM \"{name}\" [{id}] has set the process priority to {priority}'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "id", "=", "self", ".", "_id",...
Sets the process priority. :param process_priority: string
[ "Sets", "the", "process", "priority", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L629-L639
train
221,290
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.cpus
def cpus(self, cpus): """ Sets the number of vCPUs this QEMU VM. :param cpus: number of vCPUs. """ log.info('QEMU VM "{name}" [{id}] has set the number of vCPUs to {cpus}'.format(name=self._name, id=self._id, cpus=cpus)) self._cpus = cpus
python
def cpus(self, cpus): """ Sets the number of vCPUs this QEMU VM. :param cpus: number of vCPUs. """ log.info('QEMU VM "{name}" [{id}] has set the number of vCPUs to {cpus}'.format(name=self._name, id=self._id, cpus=cpus)) self._cpus = cpus
[ "def", "cpus", "(", "self", ",", "cpus", ")", ":", "log", ".", "info", "(", "'QEMU VM \"{name}\" [{id}] has set the number of vCPUs to {cpus}'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "id", "=", "self", ".", "_id", ",", "cpus", "=", "c...
Sets the number of vCPUs this QEMU VM. :param cpus: number of vCPUs.
[ "Sets", "the", "number", "of", "vCPUs", "this", "QEMU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L673-L681
train
221,291
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.options
def options(self, options): """ Sets the options for this QEMU VM. :param options: QEMU options """ log.info('QEMU VM "{name}" [{id}] has set the QEMU options to {options}'.format(name=self._name, id=self._id, options=options)) if not sys.platform.startswith("linux"): if "-no-kvm" in options: options = options.replace("-no-kvm", "") if "-enable-kvm" in options: options = options.replace("-enable-kvm", "") elif "-icount" in options and ("-no-kvm" not in options): # automatically add the -no-kvm option if -icount is detected # to help with the migration of ASA VMs created before version 1.4 options = "-no-kvm " + options self._options = options.strip()
python
def options(self, options): """ Sets the options for this QEMU VM. :param options: QEMU options """ log.info('QEMU VM "{name}" [{id}] has set the QEMU options to {options}'.format(name=self._name, id=self._id, options=options)) if not sys.platform.startswith("linux"): if "-no-kvm" in options: options = options.replace("-no-kvm", "") if "-enable-kvm" in options: options = options.replace("-enable-kvm", "") elif "-icount" in options and ("-no-kvm" not in options): # automatically add the -no-kvm option if -icount is detected # to help with the migration of ASA VMs created before version 1.4 options = "-no-kvm " + options self._options = options.strip()
[ "def", "options", "(", "self", ",", "options", ")", ":", "log", ".", "info", "(", "'QEMU VM \"{name}\" [{id}] has set the QEMU options to {options}'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "id", "=", "self", ".", "_id", ",", "options", ...
Sets the options for this QEMU VM. :param options: QEMU options
[ "Sets", "the", "options", "for", "this", "QEMU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L694-L714
train
221,292
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.initrd
def initrd(self, initrd): """ Sets the initrd path for this QEMU VM. :param initrd: QEMU initrd path """ initrd = self.manager.get_abs_image_path(initrd) log.info('QEMU VM "{name}" [{id}] has set the QEMU initrd path to {initrd}'.format(name=self._name, id=self._id, initrd=initrd)) if "asa" in initrd: self.project.emit("log.warning", {"message": "Warning ASA 8 is not supported by GNS3 and Cisco, you need to use ASAv. Depending of your hardware and OS this could not work or you could be limited to one instance. If ASA 8 is not booting their is no GNS3 solution, you need to upgrade to ASAv."}) self._initrd = initrd
python
def initrd(self, initrd): """ Sets the initrd path for this QEMU VM. :param initrd: QEMU initrd path """ initrd = self.manager.get_abs_image_path(initrd) log.info('QEMU VM "{name}" [{id}] has set the QEMU initrd path to {initrd}'.format(name=self._name, id=self._id, initrd=initrd)) if "asa" in initrd: self.project.emit("log.warning", {"message": "Warning ASA 8 is not supported by GNS3 and Cisco, you need to use ASAv. Depending of your hardware and OS this could not work or you could be limited to one instance. If ASA 8 is not booting their is no GNS3 solution, you need to upgrade to ASAv."}) self._initrd = initrd
[ "def", "initrd", "(", "self", ",", "initrd", ")", ":", "initrd", "=", "self", ".", "manager", ".", "get_abs_image_path", "(", "initrd", ")", "log", ".", "info", "(", "'QEMU VM \"{name}\" [{id}] has set the QEMU initrd path to {initrd}'", ".", "format", "(", "name"...
Sets the initrd path for this QEMU VM. :param initrd: QEMU initrd path
[ "Sets", "the", "initrd", "path", "for", "this", "QEMU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L727-L741
train
221,293
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.kernel_image
def kernel_image(self, kernel_image): """ Sets the kernel image path for this QEMU VM. :param kernel_image: QEMU kernel image path """ kernel_image = self.manager.get_abs_image_path(kernel_image) log.info('QEMU VM "{name}" [{id}] has set the QEMU kernel image path to {kernel_image}'.format(name=self._name, id=self._id, kernel_image=kernel_image)) self._kernel_image = kernel_image
python
def kernel_image(self, kernel_image): """ Sets the kernel image path for this QEMU VM. :param kernel_image: QEMU kernel image path """ kernel_image = self.manager.get_abs_image_path(kernel_image) log.info('QEMU VM "{name}" [{id}] has set the QEMU kernel image path to {kernel_image}'.format(name=self._name, id=self._id, kernel_image=kernel_image)) self._kernel_image = kernel_image
[ "def", "kernel_image", "(", "self", ",", "kernel_image", ")", ":", "kernel_image", "=", "self", ".", "manager", ".", "get_abs_image_path", "(", "kernel_image", ")", "log", ".", "info", "(", "'QEMU VM \"{name}\" [{id}] has set the QEMU kernel image path to {kernel_image}'"...
Sets the kernel image path for this QEMU VM. :param kernel_image: QEMU kernel image path
[ "Sets", "the", "kernel", "image", "path", "for", "this", "QEMU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L754-L765
train
221,294
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.kernel_command_line
def kernel_command_line(self, kernel_command_line): """ Sets the kernel command line for this QEMU VM. :param kernel_command_line: QEMU kernel command line """ log.info('QEMU VM "{name}" [{id}] has set the QEMU kernel command line to {kernel_command_line}'.format(name=self._name, id=self._id, kernel_command_line=kernel_command_line)) self._kernel_command_line = kernel_command_line
python
def kernel_command_line(self, kernel_command_line): """ Sets the kernel command line for this QEMU VM. :param kernel_command_line: QEMU kernel command line """ log.info('QEMU VM "{name}" [{id}] has set the QEMU kernel command line to {kernel_command_line}'.format(name=self._name, id=self._id, kernel_command_line=kernel_command_line)) self._kernel_command_line = kernel_command_line
[ "def", "kernel_command_line", "(", "self", ",", "kernel_command_line", ")", ":", "log", ".", "info", "(", "'QEMU VM \"{name}\" [{id}] has set the QEMU kernel command line to {kernel_command_line}'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "id", "=", ...
Sets the kernel command line for this QEMU VM. :param kernel_command_line: QEMU kernel command line
[ "Sets", "the", "kernel", "command", "line", "for", "this", "QEMU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L778-L788
train
221,295
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM._set_process_priority
def _set_process_priority(self): """ Changes the process priority """ if self._process_priority == "normal": return if sys.platform.startswith("win"): try: import win32api import win32con import win32process except ImportError: log.error("pywin32 must be installed to change the priority class for QEMU VM {}".format(self._name)) else: log.info("Setting QEMU VM {} priority class to {}".format(self._name, self._process_priority)) handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, self._process.pid) if self._process_priority == "realtime": priority = win32process.REALTIME_PRIORITY_CLASS elif self._process_priority == "very high": priority = win32process.HIGH_PRIORITY_CLASS elif self._process_priority == "high": priority = win32process.ABOVE_NORMAL_PRIORITY_CLASS elif self._process_priority == "low": priority = win32process.BELOW_NORMAL_PRIORITY_CLASS elif self._process_priority == "very low": priority = win32process.IDLE_PRIORITY_CLASS else: priority = win32process.NORMAL_PRIORITY_CLASS try: win32process.SetPriorityClass(handle, priority) except win32process.error as e: log.error('Could not change process priority for QEMU VM "{}": {}'.format(self._name, e)) else: if self._process_priority == "realtime": priority = -20 elif self._process_priority == "very high": priority = -15 elif self._process_priority == "high": priority = -5 elif self._process_priority == "low": priority = 5 elif self._process_priority == "very low": priority = 19 else: priority = 0 try: process = yield from asyncio.create_subprocess_exec('renice', '-n', str(priority), '-p', str(self._process.pid)) yield from process.wait() except (OSError, subprocess.SubprocessError) as e: log.error('Could not change process priority for QEMU VM "{}": {}'.format(self._name, e))
python
def _set_process_priority(self): """ Changes the process priority """ if self._process_priority == "normal": return if sys.platform.startswith("win"): try: import win32api import win32con import win32process except ImportError: log.error("pywin32 must be installed to change the priority class for QEMU VM {}".format(self._name)) else: log.info("Setting QEMU VM {} priority class to {}".format(self._name, self._process_priority)) handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, self._process.pid) if self._process_priority == "realtime": priority = win32process.REALTIME_PRIORITY_CLASS elif self._process_priority == "very high": priority = win32process.HIGH_PRIORITY_CLASS elif self._process_priority == "high": priority = win32process.ABOVE_NORMAL_PRIORITY_CLASS elif self._process_priority == "low": priority = win32process.BELOW_NORMAL_PRIORITY_CLASS elif self._process_priority == "very low": priority = win32process.IDLE_PRIORITY_CLASS else: priority = win32process.NORMAL_PRIORITY_CLASS try: win32process.SetPriorityClass(handle, priority) except win32process.error as e: log.error('Could not change process priority for QEMU VM "{}": {}'.format(self._name, e)) else: if self._process_priority == "realtime": priority = -20 elif self._process_priority == "very high": priority = -15 elif self._process_priority == "high": priority = -5 elif self._process_priority == "low": priority = 5 elif self._process_priority == "very low": priority = 19 else: priority = 0 try: process = yield from asyncio.create_subprocess_exec('renice', '-n', str(priority), '-p', str(self._process.pid)) yield from process.wait() except (OSError, subprocess.SubprocessError) as e: log.error('Could not change process priority for QEMU VM "{}": {}'.format(self._name, e))
[ "def", "_set_process_priority", "(", "self", ")", ":", "if", "self", ".", "_process_priority", "==", "\"normal\"", ":", "return", "if", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", ":", "try", ":", "import", "win32api", "import", "win32con...
Changes the process priority
[ "Changes", "the", "process", "priority" ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L791-L842
train
221,296
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM._stop_cpulimit
def _stop_cpulimit(self): """ Stops the cpulimit process. """ if self._cpulimit_process and self._cpulimit_process.returncode is None: self._cpulimit_process.kill() try: self._process.wait(3) except subprocess.TimeoutExpired: log.error("Could not kill cpulimit process {}".format(self._cpulimit_process.pid))
python
def _stop_cpulimit(self): """ Stops the cpulimit process. """ if self._cpulimit_process and self._cpulimit_process.returncode is None: self._cpulimit_process.kill() try: self._process.wait(3) except subprocess.TimeoutExpired: log.error("Could not kill cpulimit process {}".format(self._cpulimit_process.pid))
[ "def", "_stop_cpulimit", "(", "self", ")", ":", "if", "self", ".", "_cpulimit_process", "and", "self", ".", "_cpulimit_process", ".", "returncode", "is", "None", ":", "self", ".", "_cpulimit_process", ".", "kill", "(", ")", "try", ":", "self", ".", "_proce...
Stops the cpulimit process.
[ "Stops", "the", "cpulimit", "process", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L844-L854
train
221,297
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM._set_cpu_throttling
def _set_cpu_throttling(self): """ Limits the CPU usage for current QEMU process. """ if not self.is_running(): return try: if sys.platform.startswith("win") and hasattr(sys, "frozen"): cpulimit_exec = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), "cpulimit", "cpulimit.exe") else: cpulimit_exec = "cpulimit" subprocess.Popen([cpulimit_exec, "--lazy", "--pid={}".format(self._process.pid), "--limit={}".format(self._cpu_throttling)], cwd=self.working_dir) log.info("CPU throttled to {}%".format(self._cpu_throttling)) except FileNotFoundError: raise QemuError("cpulimit could not be found, please install it or deactivate CPU throttling") except (OSError, subprocess.SubprocessError) as e: raise QemuError("Could not throttle CPU: {}".format(e))
python
def _set_cpu_throttling(self): """ Limits the CPU usage for current QEMU process. """ if not self.is_running(): return try: if sys.platform.startswith("win") and hasattr(sys, "frozen"): cpulimit_exec = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), "cpulimit", "cpulimit.exe") else: cpulimit_exec = "cpulimit" subprocess.Popen([cpulimit_exec, "--lazy", "--pid={}".format(self._process.pid), "--limit={}".format(self._cpu_throttling)], cwd=self.working_dir) log.info("CPU throttled to {}%".format(self._cpu_throttling)) except FileNotFoundError: raise QemuError("cpulimit could not be found, please install it or deactivate CPU throttling") except (OSError, subprocess.SubprocessError) as e: raise QemuError("Could not throttle CPU: {}".format(e))
[ "def", "_set_cpu_throttling", "(", "self", ")", ":", "if", "not", "self", ".", "is_running", "(", ")", ":", "return", "try", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", "and", "hasattr", "(", "sys", ",", "\"frozen\"", ")"...
Limits the CPU usage for current QEMU process.
[ "Limits", "the", "CPU", "usage", "for", "current", "QEMU", "process", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L856-L874
train
221,298
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
QemuVM.stop
def stop(self): """ Stops this QEMU VM. """ yield from self._stop_ubridge() with (yield from self._execute_lock): # stop the QEMU process self._hw_virtualization = False if self.is_running(): log.info('Stopping QEMU VM "{}" PID={}'.format(self._name, self._process.pid)) try: if self.acpi_shutdown: yield from self._control_vm("system_powerdown") yield from gns3server.utils.asyncio.wait_for_process_termination(self._process, timeout=30) else: self._process.terminate() yield from gns3server.utils.asyncio.wait_for_process_termination(self._process, timeout=3) except ProcessLookupError: pass except asyncio.TimeoutError: if self._process: try: self._process.kill() except ProcessLookupError: pass if self._process.returncode is None: log.warn('QEMU VM "{}" PID={} is still running'.format(self._name, self._process.pid)) self._process = None self._stop_cpulimit() yield from super().stop()
python
def stop(self): """ Stops this QEMU VM. """ yield from self._stop_ubridge() with (yield from self._execute_lock): # stop the QEMU process self._hw_virtualization = False if self.is_running(): log.info('Stopping QEMU VM "{}" PID={}'.format(self._name, self._process.pid)) try: if self.acpi_shutdown: yield from self._control_vm("system_powerdown") yield from gns3server.utils.asyncio.wait_for_process_termination(self._process, timeout=30) else: self._process.terminate() yield from gns3server.utils.asyncio.wait_for_process_termination(self._process, timeout=3) except ProcessLookupError: pass except asyncio.TimeoutError: if self._process: try: self._process.kill() except ProcessLookupError: pass if self._process.returncode is None: log.warn('QEMU VM "{}" PID={} is still running'.format(self._name, self._process.pid)) self._process = None self._stop_cpulimit() yield from super().stop()
[ "def", "stop", "(", "self", ")", ":", "yield", "from", "self", ".", "_stop_ubridge", "(", ")", "with", "(", "yield", "from", "self", ".", "_execute_lock", ")", ":", "# stop the QEMU process", "self", ".", "_hw_virtualization", "=", "False", "if", "self", "...
Stops this QEMU VM.
[ "Stops", "this", "QEMU", "VM", "." ]
a221678448fb5d24e977ef562f81d56aacc89ab1
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L962-L992
train
221,299