id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
226,400 | 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 |
226,401 | 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 |
226,402 | 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 |
226,403 | 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 |
226,404 | 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 |
226,405 | 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 |
226,406 | 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 |
226,407 | 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 |
226,408 | 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 |
226,409 | 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 |
226,410 | 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 |
226,411 | 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 |
226,412 | 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 |
226,413 | 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 |
226,414 | 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 |
226,415 | 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 |
226,416 | 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 |
226,417 | 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 |
226,418 | 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 |
226,419 | 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 |
226,420 | 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 |
226,421 | 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 |
226,422 | 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 |
226,423 | 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 |
226,424 | 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 |
226,425 | 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 |
226,426 | 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 |
226,427 | 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 |
226,428 | 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 |
226,429 | 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 |
226,430 | 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 |
226,431 | 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 |
226,432 | 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 |
226,433 | 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 |
226,434 | 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 |
226,435 | 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 |
226,436 | 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 |
226,437 | 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 |
226,438 | 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 |
226,439 | 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 |
226,440 | 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 |
226,441 | 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 |
226,442 | 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 |
226,443 | 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 |
226,444 | 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 |
226,445 | 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 |
226,446 | GNS3/gns3-server | gns3server/compute/qemu/qemu_vm.py | QemuVM._control_vm | def _control_vm(self, command, expected=None):
"""
Executes a command with QEMU monitor when this VM is running.
:param command: QEMU monitor command (e.g. info status, stop etc.)
:param expected: An array of expected strings
:returns: result of the command (matched object or None)
"""
result = None
if self.is_running() and self._monitor:
log.debug("Execute QEMU monitor command: {}".format(command))
try:
log.info("Connecting to Qemu monitor on {}:{}".format(self._monitor_host, self._monitor))
reader, writer = yield from asyncio.open_connection(self._monitor_host, self._monitor)
except OSError as e:
log.warn("Could not connect to QEMU monitor: {}".format(e))
return result
try:
writer.write(command.encode('ascii') + b"\n")
except OSError as e:
log.warn("Could not write to QEMU monitor: {}".format(e))
writer.close()
return result
if expected:
try:
while result is None:
line = yield from reader.readline()
if not line:
break
for expect in expected:
if expect in line:
result = line.decode("utf-8").strip()
break
except EOFError as e:
log.warn("Could not read from QEMU monitor: {}".format(e))
writer.close()
return result | python | def _control_vm(self, command, expected=None):
"""
Executes a command with QEMU monitor when this VM is running.
:param command: QEMU monitor command (e.g. info status, stop etc.)
:param expected: An array of expected strings
:returns: result of the command (matched object or None)
"""
result = None
if self.is_running() and self._monitor:
log.debug("Execute QEMU monitor command: {}".format(command))
try:
log.info("Connecting to Qemu monitor on {}:{}".format(self._monitor_host, self._monitor))
reader, writer = yield from asyncio.open_connection(self._monitor_host, self._monitor)
except OSError as e:
log.warn("Could not connect to QEMU monitor: {}".format(e))
return result
try:
writer.write(command.encode('ascii') + b"\n")
except OSError as e:
log.warn("Could not write to QEMU monitor: {}".format(e))
writer.close()
return result
if expected:
try:
while result is None:
line = yield from reader.readline()
if not line:
break
for expect in expected:
if expect in line:
result = line.decode("utf-8").strip()
break
except EOFError as e:
log.warn("Could not read from QEMU monitor: {}".format(e))
writer.close()
return result | [
"def",
"_control_vm",
"(",
"self",
",",
"command",
",",
"expected",
"=",
"None",
")",
":",
"result",
"=",
"None",
"if",
"self",
".",
"is_running",
"(",
")",
"and",
"self",
".",
"_monitor",
":",
"log",
".",
"debug",
"(",
"\"Execute QEMU monitor command: {}\... | Executes a command with QEMU monitor when this VM is running.
:param command: QEMU monitor command (e.g. info status, stop etc.)
:param expected: An array of expected strings
:returns: result of the command (matched object or None) | [
"Executes",
"a",
"command",
"with",
"QEMU",
"monitor",
"when",
"this",
"VM",
"is",
"running",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L995-L1033 |
226,447 | GNS3/gns3-server | gns3server/compute/qemu/qemu_vm.py | QemuVM.close | def close(self):
"""
Closes this QEMU VM.
"""
if not (yield from super().close()):
return False
self.acpi_shutdown = False
yield from self.stop()
for adapter in self._ethernet_adapters:
if adapter is not None:
for nio in adapter.ports.values():
if nio and isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
for udp_tunnel in self._local_udp_tunnels.values():
self.manager.port_manager.release_udp_port(udp_tunnel[0].lport, self._project)
self.manager.port_manager.release_udp_port(udp_tunnel[1].lport, self._project)
self._local_udp_tunnels = {} | python | def close(self):
"""
Closes this QEMU VM.
"""
if not (yield from super().close()):
return False
self.acpi_shutdown = False
yield from self.stop()
for adapter in self._ethernet_adapters:
if adapter is not None:
for nio in adapter.ports.values():
if nio and isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
for udp_tunnel in self._local_udp_tunnels.values():
self.manager.port_manager.release_udp_port(udp_tunnel[0].lport, self._project)
self.manager.port_manager.release_udp_port(udp_tunnel[1].lport, self._project)
self._local_udp_tunnels = {} | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"(",
"yield",
"from",
"super",
"(",
")",
".",
"close",
"(",
")",
")",
":",
"return",
"False",
"self",
".",
"acpi_shutdown",
"=",
"False",
"yield",
"from",
"self",
".",
"stop",
"(",
")",
"for",
"... | Closes this QEMU VM. | [
"Closes",
"this",
"QEMU",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L1036-L1056 |
226,448 | GNS3/gns3-server | gns3server/compute/qemu/qemu_vm.py | QemuVM._get_vm_status | def _get_vm_status(self):
"""
Returns this VM suspend status.
Status are extracted from:
https://github.com/qemu/qemu/blob/master/qapi-schema.json#L152
:returns: status (string)
"""
result = yield from self._control_vm("info status", [
b"debug", b"inmigrate", b"internal-error", b"io-error",
b"paused", b"postmigrate", b"prelaunch", b"finish-migrate",
b"restore-vm", b"running", b"save-vm", b"shutdown", b"suspended",
b"watchdog", b"guest-panicked"
])
if result is None:
return result
status = result.rsplit(' ', 1)[1]
if status == "running" or status == "prelaunch":
self.status = "started"
elif status == "suspended":
self.status = "suspended"
elif status == "shutdown":
self.status = "stopped"
return status | python | def _get_vm_status(self):
"""
Returns this VM suspend status.
Status are extracted from:
https://github.com/qemu/qemu/blob/master/qapi-schema.json#L152
:returns: status (string)
"""
result = yield from self._control_vm("info status", [
b"debug", b"inmigrate", b"internal-error", b"io-error",
b"paused", b"postmigrate", b"prelaunch", b"finish-migrate",
b"restore-vm", b"running", b"save-vm", b"shutdown", b"suspended",
b"watchdog", b"guest-panicked"
])
if result is None:
return result
status = result.rsplit(' ', 1)[1]
if status == "running" or status == "prelaunch":
self.status = "started"
elif status == "suspended":
self.status = "suspended"
elif status == "shutdown":
self.status = "stopped"
return status | [
"def",
"_get_vm_status",
"(",
"self",
")",
":",
"result",
"=",
"yield",
"from",
"self",
".",
"_control_vm",
"(",
"\"info status\"",
",",
"[",
"b\"debug\"",
",",
"b\"inmigrate\"",
",",
"b\"internal-error\"",
",",
"b\"io-error\"",
",",
"b\"paused\"",
",",
"b\"post... | Returns this VM suspend status.
Status are extracted from:
https://github.com/qemu/qemu/blob/master/qapi-schema.json#L152
:returns: status (string) | [
"Returns",
"this",
"VM",
"suspend",
"status",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L1059-L1084 |
226,449 | GNS3/gns3-server | gns3server/compute/qemu/qemu_vm.py | QemuVM.suspend | def suspend(self):
"""
Suspends this QEMU VM.
"""
if self.is_running():
vm_status = yield from self._get_vm_status()
if vm_status is None:
raise QemuError("Suspending a QEMU VM is not supported")
elif vm_status == "running" or vm_status == "prelaunch":
yield from self._control_vm("stop")
self.status = "suspended"
log.debug("QEMU VM has been suspended")
else:
log.info("QEMU VM is not running to be suspended, current status is {}".format(vm_status)) | python | def suspend(self):
"""
Suspends this QEMU VM.
"""
if self.is_running():
vm_status = yield from self._get_vm_status()
if vm_status is None:
raise QemuError("Suspending a QEMU VM is not supported")
elif vm_status == "running" or vm_status == "prelaunch":
yield from self._control_vm("stop")
self.status = "suspended"
log.debug("QEMU VM has been suspended")
else:
log.info("QEMU VM is not running to be suspended, current status is {}".format(vm_status)) | [
"def",
"suspend",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_running",
"(",
")",
":",
"vm_status",
"=",
"yield",
"from",
"self",
".",
"_get_vm_status",
"(",
")",
"if",
"vm_status",
"is",
"None",
":",
"raise",
"QemuError",
"(",
"\"Suspending a QEMU VM is... | Suspends this QEMU VM. | [
"Suspends",
"this",
"QEMU",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L1087-L1101 |
226,450 | GNS3/gns3-server | gns3server/compute/qemu/qemu_vm.py | QemuVM.resume | def resume(self):
"""
Resumes this QEMU VM.
"""
vm_status = yield from self._get_vm_status()
if vm_status is None:
raise QemuError("Resuming a QEMU VM is not supported")
elif vm_status == "paused":
yield from self._control_vm("cont")
log.debug("QEMU VM has been resumed")
else:
log.info("QEMU VM is not paused to be resumed, current status is {}".format(vm_status)) | python | def resume(self):
"""
Resumes this QEMU VM.
"""
vm_status = yield from self._get_vm_status()
if vm_status is None:
raise QemuError("Resuming a QEMU VM is not supported")
elif vm_status == "paused":
yield from self._control_vm("cont")
log.debug("QEMU VM has been resumed")
else:
log.info("QEMU VM is not paused to be resumed, current status is {}".format(vm_status)) | [
"def",
"resume",
"(",
"self",
")",
":",
"vm_status",
"=",
"yield",
"from",
"self",
".",
"_get_vm_status",
"(",
")",
"if",
"vm_status",
"is",
"None",
":",
"raise",
"QemuError",
"(",
"\"Resuming a QEMU VM is not supported\"",
")",
"elif",
"vm_status",
"==",
"\"p... | Resumes this QEMU VM. | [
"Resumes",
"this",
"QEMU",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L1113-L1125 |
226,451 | GNS3/gns3-server | gns3server/compute/qemu/qemu_vm.py | QemuVM.read_stdout | def read_stdout(self):
"""
Reads the standard output of the QEMU process.
Only use when the process has been stopped or has crashed.
"""
output = ""
if self._stdout_file:
try:
with open(self._stdout_file, "rb") as file:
output = file.read().decode("utf-8", errors="replace")
except OSError as e:
log.warning("Could not read {}: {}".format(self._stdout_file, e))
return output | python | def read_stdout(self):
"""
Reads the standard output of the QEMU process.
Only use when the process has been stopped or has crashed.
"""
output = ""
if self._stdout_file:
try:
with open(self._stdout_file, "rb") as file:
output = file.read().decode("utf-8", errors="replace")
except OSError as e:
log.warning("Could not read {}: {}".format(self._stdout_file, e))
return output | [
"def",
"read_stdout",
"(",
"self",
")",
":",
"output",
"=",
"\"\"",
"if",
"self",
".",
"_stdout_file",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"_stdout_file",
",",
"\"rb\"",
")",
"as",
"file",
":",
"output",
"=",
"file",
".",
"read",
"(",
... | Reads the standard output of the QEMU process.
Only use when the process has been stopped or has crashed. | [
"Reads",
"the",
"standard",
"output",
"of",
"the",
"QEMU",
"process",
".",
"Only",
"use",
"when",
"the",
"process",
"has",
"been",
"stopped",
"or",
"has",
"crashed",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L1275-L1288 |
226,452 | GNS3/gns3-server | gns3server/compute/qemu/qemu_vm.py | QemuVM.read_qemu_img_stdout | def read_qemu_img_stdout(self):
"""
Reads the standard output of the QEMU-IMG process.
"""
output = ""
if self._qemu_img_stdout_file:
try:
with open(self._qemu_img_stdout_file, "rb") as file:
output = file.read().decode("utf-8", errors="replace")
except OSError as e:
log.warning("Could not read {}: {}".format(self._qemu_img_stdout_file, e))
return output | python | def read_qemu_img_stdout(self):
"""
Reads the standard output of the QEMU-IMG process.
"""
output = ""
if self._qemu_img_stdout_file:
try:
with open(self._qemu_img_stdout_file, "rb") as file:
output = file.read().decode("utf-8", errors="replace")
except OSError as e:
log.warning("Could not read {}: {}".format(self._qemu_img_stdout_file, e))
return output | [
"def",
"read_qemu_img_stdout",
"(",
"self",
")",
":",
"output",
"=",
"\"\"",
"if",
"self",
".",
"_qemu_img_stdout_file",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"_qemu_img_stdout_file",
",",
"\"rb\"",
")",
"as",
"file",
":",
"output",
"=",
"file... | Reads the standard output of the QEMU-IMG process. | [
"Reads",
"the",
"standard",
"output",
"of",
"the",
"QEMU",
"-",
"IMG",
"process",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L1290-L1302 |
226,453 | GNS3/gns3-server | gns3server/compute/qemu/qemu_vm.py | QemuVM.is_running | def is_running(self):
"""
Checks if the QEMU process is running
:returns: True or False
"""
if self._process:
if self._process.returncode is None:
return True
else:
self._process = None
return False | python | def is_running(self):
"""
Checks if the QEMU process is running
:returns: True or False
"""
if self._process:
if self._process.returncode is None:
return True
else:
self._process = None
return False | [
"def",
"is_running",
"(",
"self",
")",
":",
"if",
"self",
".",
"_process",
":",
"if",
"self",
".",
"_process",
".",
"returncode",
"is",
"None",
":",
"return",
"True",
"else",
":",
"self",
".",
"_process",
"=",
"None",
"return",
"False"
] | Checks if the QEMU process is running
:returns: True or False | [
"Checks",
"if",
"the",
"QEMU",
"process",
"is",
"running"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L1304-L1316 |
226,454 | GNS3/gns3-server | gns3server/compute/qemu/qemu_vm.py | QemuVM._get_qemu_img | def _get_qemu_img(self):
"""
Search the qemu-img binary in the same binary of the qemu binary
for avoiding version incompatibily.
:returns: qemu-img path or raise an error
"""
qemu_img_path = ""
qemu_path_dir = os.path.dirname(self.qemu_path)
try:
for f in os.listdir(qemu_path_dir):
if f.startswith("qemu-img"):
qemu_img_path = os.path.join(qemu_path_dir, f)
except OSError as e:
raise QemuError("Error while looking for qemu-img in {}: {}".format(qemu_path_dir, e))
if not qemu_img_path:
raise QemuError("Could not find qemu-img in {}".format(qemu_path_dir))
return qemu_img_path | python | def _get_qemu_img(self):
"""
Search the qemu-img binary in the same binary of the qemu binary
for avoiding version incompatibily.
:returns: qemu-img path or raise an error
"""
qemu_img_path = ""
qemu_path_dir = os.path.dirname(self.qemu_path)
try:
for f in os.listdir(qemu_path_dir):
if f.startswith("qemu-img"):
qemu_img_path = os.path.join(qemu_path_dir, f)
except OSError as e:
raise QemuError("Error while looking for qemu-img in {}: {}".format(qemu_path_dir, e))
if not qemu_img_path:
raise QemuError("Could not find qemu-img in {}".format(qemu_path_dir))
return qemu_img_path | [
"def",
"_get_qemu_img",
"(",
"self",
")",
":",
"qemu_img_path",
"=",
"\"\"",
"qemu_path_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"qemu_path",
")",
"try",
":",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"qemu_path_dir",
")",
":"... | Search the qemu-img binary in the same binary of the qemu binary
for avoiding version incompatibily.
:returns: qemu-img path or raise an error | [
"Search",
"the",
"qemu",
"-",
"img",
"binary",
"in",
"the",
"same",
"binary",
"of",
"the",
"qemu",
"binary",
"for",
"avoiding",
"version",
"incompatibily",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L1364-L1383 |
226,455 | GNS3/gns3-server | gns3server/compute/qemu/qemu_vm.py | QemuVM._graphic | def _graphic(self):
"""
Adds the correct graphic options depending of the OS
"""
if sys.platform.startswith("win"):
return []
if len(os.environ.get("DISPLAY", "")) > 0:
return []
if "-nographic" not in self._options:
return ["-nographic"]
return [] | python | def _graphic(self):
"""
Adds the correct graphic options depending of the OS
"""
if sys.platform.startswith("win"):
return []
if len(os.environ.get("DISPLAY", "")) > 0:
return []
if "-nographic" not in self._options:
return ["-nographic"]
return [] | [
"def",
"_graphic",
"(",
"self",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"return",
"[",
"]",
"if",
"len",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"\"DISPLAY\"",
",",
"\"\"",
")",
")",
">",
"0",
":",... | Adds the correct graphic options depending of the OS | [
"Adds",
"the",
"correct",
"graphic",
"options",
"depending",
"of",
"the",
"OS"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L1603-L1614 |
226,456 | GNS3/gns3-server | gns3server/compute/qemu/qemu_vm.py | QemuVM._run_with_kvm | def _run_with_kvm(self, qemu_path, options):
"""
Check if we could run qemu with KVM
:param qemu_path: Path to qemu
:param options: String of qemu user options
:returns: Boolean True if we need to enable KVM
"""
if sys.platform.startswith("linux") and self.manager.config.get_section_config("Qemu").getboolean("enable_kvm", True) \
and "-no-kvm" not in options:
# Turn OFF kvm for non x86 architectures
if os.path.basename(qemu_path) not in ["qemu-system-x86_64", "qemu-system-i386", "qemu-kvm"]:
return False
if not os.path.exists("/dev/kvm"):
if self.manager.config.get_section_config("Qemu").getboolean("require_kvm", True):
raise QemuError("KVM acceleration cannot be used (/dev/kvm doesn't exist). You can turn off KVM support in the gns3_server.conf by adding enable_kvm = false to the [Qemu] section.")
else:
return False
return True
return False | python | def _run_with_kvm(self, qemu_path, options):
"""
Check if we could run qemu with KVM
:param qemu_path: Path to qemu
:param options: String of qemu user options
:returns: Boolean True if we need to enable KVM
"""
if sys.platform.startswith("linux") and self.manager.config.get_section_config("Qemu").getboolean("enable_kvm", True) \
and "-no-kvm" not in options:
# Turn OFF kvm for non x86 architectures
if os.path.basename(qemu_path) not in ["qemu-system-x86_64", "qemu-system-i386", "qemu-kvm"]:
return False
if not os.path.exists("/dev/kvm"):
if self.manager.config.get_section_config("Qemu").getboolean("require_kvm", True):
raise QemuError("KVM acceleration cannot be used (/dev/kvm doesn't exist). You can turn off KVM support in the gns3_server.conf by adding enable_kvm = false to the [Qemu] section.")
else:
return False
return True
return False | [
"def",
"_run_with_kvm",
"(",
"self",
",",
"qemu_path",
",",
"options",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"linux\"",
")",
"and",
"self",
".",
"manager",
".",
"config",
".",
"get_section_config",
"(",
"\"Qemu\"",
")",
".",
"... | Check if we could run qemu with KVM
:param qemu_path: Path to qemu
:param options: String of qemu user options
:returns: Boolean True if we need to enable KVM | [
"Check",
"if",
"we",
"could",
"run",
"qemu",
"with",
"KVM"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L1616-L1638 |
226,457 | GNS3/gns3-server | gns3server/controller/gns3vm/__init__.py | GNS3VM.update_settings | def update_settings(self, settings):
"""
Update settings and will restart the VM if require
"""
new_settings = copy.copy(self._settings)
new_settings.update(settings)
if self.settings != new_settings:
yield from self._stop()
self._settings = settings
self._controller.save()
if self.enable:
yield from self.start()
else:
# When user fix something on his system and try again
if self.enable and not self.current_engine().running:
yield from self.start() | python | def update_settings(self, settings):
"""
Update settings and will restart the VM if require
"""
new_settings = copy.copy(self._settings)
new_settings.update(settings)
if self.settings != new_settings:
yield from self._stop()
self._settings = settings
self._controller.save()
if self.enable:
yield from self.start()
else:
# When user fix something on his system and try again
if self.enable and not self.current_engine().running:
yield from self.start() | [
"def",
"update_settings",
"(",
"self",
",",
"settings",
")",
":",
"new_settings",
"=",
"copy",
".",
"copy",
"(",
"self",
".",
"_settings",
")",
"new_settings",
".",
"update",
"(",
"settings",
")",
"if",
"self",
".",
"settings",
"!=",
"new_settings",
":",
... | Update settings and will restart the VM if require | [
"Update",
"settings",
"and",
"will",
"restart",
"the",
"VM",
"if",
"require"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/__init__.py#L183-L198 |
226,458 | GNS3/gns3-server | gns3server/controller/gns3vm/__init__.py | GNS3VM._get_engine | def _get_engine(self, engine):
"""
Load an engine
"""
if engine in self._engines:
return self._engines[engine]
if engine == "vmware":
self._engines["vmware"] = VMwareGNS3VM(self._controller)
return self._engines["vmware"]
elif engine == "virtualbox":
self._engines["virtualbox"] = VirtualBoxGNS3VM(self._controller)
return self._engines["virtualbox"]
elif engine == "remote":
self._engines["remote"] = RemoteGNS3VM(self._controller)
return self._engines["remote"]
raise NotImplementedError("The engine {} for the GNS3 VM is not supported".format(engine)) | python | def _get_engine(self, engine):
"""
Load an engine
"""
if engine in self._engines:
return self._engines[engine]
if engine == "vmware":
self._engines["vmware"] = VMwareGNS3VM(self._controller)
return self._engines["vmware"]
elif engine == "virtualbox":
self._engines["virtualbox"] = VirtualBoxGNS3VM(self._controller)
return self._engines["virtualbox"]
elif engine == "remote":
self._engines["remote"] = RemoteGNS3VM(self._controller)
return self._engines["remote"]
raise NotImplementedError("The engine {} for the GNS3 VM is not supported".format(engine)) | [
"def",
"_get_engine",
"(",
"self",
",",
"engine",
")",
":",
"if",
"engine",
"in",
"self",
".",
"_engines",
":",
"return",
"self",
".",
"_engines",
"[",
"engine",
"]",
"if",
"engine",
"==",
"\"vmware\"",
":",
"self",
".",
"_engines",
"[",
"\"vmware\"",
... | Load an engine | [
"Load",
"an",
"engine"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/__init__.py#L200-L216 |
226,459 | GNS3/gns3-server | gns3server/controller/gns3vm/__init__.py | GNS3VM.list | def list(self, engine):
"""
List VMS for an engine
"""
engine = self._get_engine(engine)
vms = []
try:
for vm in (yield from engine.list()):
vms.append({"vmname": vm["vmname"]})
except GNS3VMError as e:
# We raise error only if user activated the GNS3 VM
# otherwise you have noise when VMware is not installed
if self.enable:
raise e
return vms | python | def list(self, engine):
"""
List VMS for an engine
"""
engine = self._get_engine(engine)
vms = []
try:
for vm in (yield from engine.list()):
vms.append({"vmname": vm["vmname"]})
except GNS3VMError as e:
# We raise error only if user activated the GNS3 VM
# otherwise you have noise when VMware is not installed
if self.enable:
raise e
return vms | [
"def",
"list",
"(",
"self",
",",
"engine",
")",
":",
"engine",
"=",
"self",
".",
"_get_engine",
"(",
"engine",
")",
"vms",
"=",
"[",
"]",
"try",
":",
"for",
"vm",
"in",
"(",
"yield",
"from",
"engine",
".",
"list",
"(",
")",
")",
":",
"vms",
"."... | List VMS for an engine | [
"List",
"VMS",
"for",
"an",
"engine"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/__init__.py#L222-L236 |
226,460 | GNS3/gns3-server | gns3server/controller/gns3vm/__init__.py | GNS3VM.auto_start_vm | def auto_start_vm(self):
"""
Auto start the GNS3 VM if require
"""
if self.enable:
try:
yield from self.start()
except GNS3VMError as e:
# User will receive the error later when they will try to use the node
try:
yield from self._controller.add_compute(compute_id="vm",
name="GNS3 VM ({})".format(self.current_engine().vmname),
host=None,
force=True)
except aiohttp.web.HTTPConflict:
pass
log.error("Can't start the GNS3 VM: %s", str(e)) | python | def auto_start_vm(self):
"""
Auto start the GNS3 VM if require
"""
if self.enable:
try:
yield from self.start()
except GNS3VMError as e:
# User will receive the error later when they will try to use the node
try:
yield from self._controller.add_compute(compute_id="vm",
name="GNS3 VM ({})".format(self.current_engine().vmname),
host=None,
force=True)
except aiohttp.web.HTTPConflict:
pass
log.error("Can't start the GNS3 VM: %s", str(e)) | [
"def",
"auto_start_vm",
"(",
"self",
")",
":",
"if",
"self",
".",
"enable",
":",
"try",
":",
"yield",
"from",
"self",
".",
"start",
"(",
")",
"except",
"GNS3VMError",
"as",
"e",
":",
"# User will receive the error later when they will try to use the node",
"try",
... | Auto start the GNS3 VM if require | [
"Auto",
"start",
"the",
"GNS3",
"VM",
"if",
"require"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/__init__.py#L239-L255 |
226,461 | GNS3/gns3-server | gns3server/controller/gns3vm/__init__.py | GNS3VM.start | def start(self):
"""
Start the GNS3 VM
"""
engine = self.current_engine()
if not engine.running:
if self._settings["vmname"] is None:
return
log.info("Start the GNS3 VM")
engine.vmname = self._settings["vmname"]
engine.ram = self._settings["ram"]
engine.vcpus = self._settings["vcpus"]
engine.headless = self._settings["headless"]
compute = yield from self._controller.add_compute(compute_id="vm",
name="GNS3 VM is starting ({})".format(engine.vmname),
host=None,
force=True,
connect=False)
try:
yield from engine.start()
except Exception as e:
yield from self._controller.delete_compute("vm")
log.error("Can't start the GNS3 VM: {}".format(str(e)))
yield from compute.update(name="GNS3 VM ({})".format(engine.vmname))
raise e
yield from compute.connect() # we can connect now that the VM has started
yield from compute.update(name="GNS3 VM ({})".format(engine.vmname),
protocol=self.protocol,
host=self.ip_address,
port=self.port,
user=self.user,
password=self.password)
# check if the VM is in the same subnet as the local server, start 10 seconds later to give
# some time for the compute in the VM to be ready for requests
asyncio.get_event_loop().call_later(10, lambda: asyncio.async(self._check_network(compute))) | python | def start(self):
"""
Start the GNS3 VM
"""
engine = self.current_engine()
if not engine.running:
if self._settings["vmname"] is None:
return
log.info("Start the GNS3 VM")
engine.vmname = self._settings["vmname"]
engine.ram = self._settings["ram"]
engine.vcpus = self._settings["vcpus"]
engine.headless = self._settings["headless"]
compute = yield from self._controller.add_compute(compute_id="vm",
name="GNS3 VM is starting ({})".format(engine.vmname),
host=None,
force=True,
connect=False)
try:
yield from engine.start()
except Exception as e:
yield from self._controller.delete_compute("vm")
log.error("Can't start the GNS3 VM: {}".format(str(e)))
yield from compute.update(name="GNS3 VM ({})".format(engine.vmname))
raise e
yield from compute.connect() # we can connect now that the VM has started
yield from compute.update(name="GNS3 VM ({})".format(engine.vmname),
protocol=self.protocol,
host=self.ip_address,
port=self.port,
user=self.user,
password=self.password)
# check if the VM is in the same subnet as the local server, start 10 seconds later to give
# some time for the compute in the VM to be ready for requests
asyncio.get_event_loop().call_later(10, lambda: asyncio.async(self._check_network(compute))) | [
"def",
"start",
"(",
"self",
")",
":",
"engine",
"=",
"self",
".",
"current_engine",
"(",
")",
"if",
"not",
"engine",
".",
"running",
":",
"if",
"self",
".",
"_settings",
"[",
"\"vmname\"",
"]",
"is",
"None",
":",
"return",
"log",
".",
"info",
"(",
... | Start the GNS3 VM | [
"Start",
"the",
"GNS3",
"VM"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/__init__.py#L269-L305 |
226,462 | GNS3/gns3-server | gns3server/controller/gns3vm/__init__.py | GNS3VM._check_network | def _check_network(self, compute):
"""
Check that the VM is in the same subnet as the local server
"""
try:
vm_interfaces = yield from compute.interfaces()
vm_interface_netmask = None
for interface in vm_interfaces:
if interface["ip_address"] == self.ip_address:
vm_interface_netmask = interface["netmask"]
break
if vm_interface_netmask:
vm_network = ipaddress.ip_interface("{}/{}".format(compute.host_ip, vm_interface_netmask)).network
for compute_id in self._controller.computes:
if compute_id == "local":
compute = self._controller.get_compute(compute_id)
interfaces = yield from compute.interfaces()
netmask = None
for interface in interfaces:
if interface["ip_address"] == compute.host_ip:
netmask = interface["netmask"]
break
if netmask:
compute_network = ipaddress.ip_interface("{}/{}".format(compute.host_ip, netmask)).network
if vm_network.compare_networks(compute_network) != 0:
msg = "The GNS3 VM ({}) is not on the same network as the {} server ({}), please make sure the local server binding is in the same network as the GNS3 VM".format(
vm_network, compute_id, compute_network)
self._controller.notification.emit("log.warning", {"message": msg})
except ComputeError as e:
log.warning("Could not check the VM is in the same subnet as the local server: {}".format(e)) | python | def _check_network(self, compute):
"""
Check that the VM is in the same subnet as the local server
"""
try:
vm_interfaces = yield from compute.interfaces()
vm_interface_netmask = None
for interface in vm_interfaces:
if interface["ip_address"] == self.ip_address:
vm_interface_netmask = interface["netmask"]
break
if vm_interface_netmask:
vm_network = ipaddress.ip_interface("{}/{}".format(compute.host_ip, vm_interface_netmask)).network
for compute_id in self._controller.computes:
if compute_id == "local":
compute = self._controller.get_compute(compute_id)
interfaces = yield from compute.interfaces()
netmask = None
for interface in interfaces:
if interface["ip_address"] == compute.host_ip:
netmask = interface["netmask"]
break
if netmask:
compute_network = ipaddress.ip_interface("{}/{}".format(compute.host_ip, netmask)).network
if vm_network.compare_networks(compute_network) != 0:
msg = "The GNS3 VM ({}) is not on the same network as the {} server ({}), please make sure the local server binding is in the same network as the GNS3 VM".format(
vm_network, compute_id, compute_network)
self._controller.notification.emit("log.warning", {"message": msg})
except ComputeError as e:
log.warning("Could not check the VM is in the same subnet as the local server: {}".format(e)) | [
"def",
"_check_network",
"(",
"self",
",",
"compute",
")",
":",
"try",
":",
"vm_interfaces",
"=",
"yield",
"from",
"compute",
".",
"interfaces",
"(",
")",
"vm_interface_netmask",
"=",
"None",
"for",
"interface",
"in",
"vm_interfaces",
":",
"if",
"interface",
... | Check that the VM is in the same subnet as the local server | [
"Check",
"that",
"the",
"VM",
"is",
"in",
"the",
"same",
"subnet",
"as",
"the",
"local",
"server"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/__init__.py#L308-L338 |
226,463 | GNS3/gns3-server | gns3server/controller/gns3vm/__init__.py | GNS3VM._suspend | def _suspend(self):
"""
Suspend the GNS3 VM
"""
engine = self.current_engine()
if "vm" in self._controller.computes:
yield from self._controller.delete_compute("vm")
if engine.running:
log.info("Suspend the GNS3 VM")
yield from engine.suspend() | python | def _suspend(self):
"""
Suspend the GNS3 VM
"""
engine = self.current_engine()
if "vm" in self._controller.computes:
yield from self._controller.delete_compute("vm")
if engine.running:
log.info("Suspend the GNS3 VM")
yield from engine.suspend() | [
"def",
"_suspend",
"(",
"self",
")",
":",
"engine",
"=",
"self",
".",
"current_engine",
"(",
")",
"if",
"\"vm\"",
"in",
"self",
".",
"_controller",
".",
"computes",
":",
"yield",
"from",
"self",
".",
"_controller",
".",
"delete_compute",
"(",
"\"vm\"",
"... | Suspend the GNS3 VM | [
"Suspend",
"the",
"GNS3",
"VM"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/__init__.py#L341-L350 |
226,464 | GNS3/gns3-server | gns3server/controller/gns3vm/__init__.py | GNS3VM._stop | def _stop(self):
"""
Stop the GNS3 VM
"""
engine = self.current_engine()
if "vm" in self._controller.computes:
yield from self._controller.delete_compute("vm")
if engine.running:
log.info("Stop the GNS3 VM")
yield from engine.stop() | python | def _stop(self):
"""
Stop the GNS3 VM
"""
engine = self.current_engine()
if "vm" in self._controller.computes:
yield from self._controller.delete_compute("vm")
if engine.running:
log.info("Stop the GNS3 VM")
yield from engine.stop() | [
"def",
"_stop",
"(",
"self",
")",
":",
"engine",
"=",
"self",
".",
"current_engine",
"(",
")",
"if",
"\"vm\"",
"in",
"self",
".",
"_controller",
".",
"computes",
":",
"yield",
"from",
"self",
".",
"_controller",
".",
"delete_compute",
"(",
"\"vm\"",
")",... | Stop the GNS3 VM | [
"Stop",
"the",
"GNS3",
"VM"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/__init__.py#L353-L362 |
226,465 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router._convert_before_2_0_0_b3 | def _convert_before_2_0_0_b3(self, dynamips_id):
"""
Before 2.0.0 beta3 the node didn't have a folder by node
when we start we move the file, we can't do it in the topology
conversion due to case of remote servers
"""
dynamips_dir = self.project.module_working_directory(self.manager.module_name.lower())
for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "configs", "i{}_*".format(dynamips_id))):
dst = os.path.join(self._working_directory, "configs", os.path.basename(path))
if not os.path.exists(dst):
try:
shutil.move(path, dst)
except OSError as e:
raise DynamipsError("Can't move {}: {}".format(path, str(e)))
for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "*_i{}_*".format(dynamips_id))):
dst = os.path.join(self._working_directory, os.path.basename(path))
if not os.path.exists(dst):
try:
shutil.move(path, dst)
except OSError as e:
raise DynamipsError("Can't move {}: {}".format(path, str(e))) | python | def _convert_before_2_0_0_b3(self, dynamips_id):
"""
Before 2.0.0 beta3 the node didn't have a folder by node
when we start we move the file, we can't do it in the topology
conversion due to case of remote servers
"""
dynamips_dir = self.project.module_working_directory(self.manager.module_name.lower())
for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "configs", "i{}_*".format(dynamips_id))):
dst = os.path.join(self._working_directory, "configs", os.path.basename(path))
if not os.path.exists(dst):
try:
shutil.move(path, dst)
except OSError as e:
raise DynamipsError("Can't move {}: {}".format(path, str(e)))
for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "*_i{}_*".format(dynamips_id))):
dst = os.path.join(self._working_directory, os.path.basename(path))
if not os.path.exists(dst):
try:
shutil.move(path, dst)
except OSError as e:
raise DynamipsError("Can't move {}: {}".format(path, str(e))) | [
"def",
"_convert_before_2_0_0_b3",
"(",
"self",
",",
"dynamips_id",
")",
":",
"dynamips_dir",
"=",
"self",
".",
"project",
".",
"module_working_directory",
"(",
"self",
".",
"manager",
".",
"module_name",
".",
"lower",
"(",
")",
")",
"for",
"path",
"in",
"gl... | Before 2.0.0 beta3 the node didn't have a folder by node
when we start we move the file, we can't do it in the topology
conversion due to case of remote servers | [
"Before",
"2",
".",
"0",
".",
"0",
"beta3",
"the",
"node",
"didn",
"t",
"have",
"a",
"folder",
"by",
"node",
"when",
"we",
"start",
"we",
"move",
"the",
"file",
"we",
"can",
"t",
"do",
"it",
"in",
"the",
"topology",
"conversion",
"due",
"to",
"case... | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L121-L141 |
226,466 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.get_status | def get_status(self):
"""
Returns the status of this router
:returns: inactive, shutting down, running or suspended.
"""
status = yield from self._hypervisor.send('vm get_status "{name}"'.format(name=self._name))
if len(status) == 0:
raise DynamipsError("Can't get vm {name} status".format(name=self._name))
return self._status[int(status[0])] | python | def get_status(self):
"""
Returns the status of this router
:returns: inactive, shutting down, running or suspended.
"""
status = yield from self._hypervisor.send('vm get_status "{name}"'.format(name=self._name))
if len(status) == 0:
raise DynamipsError("Can't get vm {name} status".format(name=self._name))
return self._status[int(status[0])] | [
"def",
"get_status",
"(",
"self",
")",
":",
"status",
"=",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm get_status \"{name}\"'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
")",
")",
"if",
"len",
"(",
"status",
")",
"=... | Returns the status of this router
:returns: inactive, shutting down, running or suspended. | [
"Returns",
"the",
"status",
"of",
"this",
"router"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L241-L251 |
226,467 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.start | def start(self):
"""
Starts this router.
At least the IOS image must be set before it can start.
"""
status = yield from self.get_status()
if status == "suspended":
yield from self.resume()
elif status == "inactive":
if not os.path.isfile(self._image) or not os.path.exists(self._image):
if os.path.islink(self._image):
raise DynamipsError('IOS image "{}" linked to "{}" is not accessible'.format(self._image, os.path.realpath(self._image)))
else:
raise DynamipsError('IOS image "{}" is not accessible'.format(self._image))
try:
with open(self._image, "rb") as f:
# read the first 7 bytes of the file.
elf_header_start = f.read(7)
except OSError as e:
raise DynamipsError('Cannot read ELF header for IOS image "{}": {}'.format(self._image, e))
# IOS images must start with the ELF magic number, be 32-bit, big endian and have an ELF version of 1
if elf_header_start != b'\x7fELF\x01\x02\x01':
raise DynamipsError('"{}" is not a valid IOS image'.format(self._image))
# check if there is enough RAM to run
if not self._ghost_flag:
self.check_available_ram(self.ram)
# config paths are relative to the working directory configured on Dynamips hypervisor
startup_config_path = os.path.join("configs", "i{}_startup-config.cfg".format(self._dynamips_id))
private_config_path = os.path.join("configs", "i{}_private-config.cfg".format(self._dynamips_id))
if not os.path.exists(os.path.join(self._working_directory, private_config_path)) or \
not os.path.getsize(os.path.join(self._working_directory, private_config_path)):
# an empty private-config can prevent a router to boot.
private_config_path = ''
yield from self._hypervisor.send('vm set_config "{name}" "{startup}" "{private}"'.format(
name=self._name,
startup=startup_config_path,
private=private_config_path))
yield from self._hypervisor.send('vm start "{name}"'.format(name=self._name))
self.status = "started"
log.info('router "{name}" [{id}] has been started'.format(name=self._name, id=self._id))
self._memory_watcher = FileWatcher(self._memory_files(), self._memory_changed, strategy='hash', delay=30)
monitor_process(self._hypervisor.process, self._termination_callback) | python | def start(self):
"""
Starts this router.
At least the IOS image must be set before it can start.
"""
status = yield from self.get_status()
if status == "suspended":
yield from self.resume()
elif status == "inactive":
if not os.path.isfile(self._image) or not os.path.exists(self._image):
if os.path.islink(self._image):
raise DynamipsError('IOS image "{}" linked to "{}" is not accessible'.format(self._image, os.path.realpath(self._image)))
else:
raise DynamipsError('IOS image "{}" is not accessible'.format(self._image))
try:
with open(self._image, "rb") as f:
# read the first 7 bytes of the file.
elf_header_start = f.read(7)
except OSError as e:
raise DynamipsError('Cannot read ELF header for IOS image "{}": {}'.format(self._image, e))
# IOS images must start with the ELF magic number, be 32-bit, big endian and have an ELF version of 1
if elf_header_start != b'\x7fELF\x01\x02\x01':
raise DynamipsError('"{}" is not a valid IOS image'.format(self._image))
# check if there is enough RAM to run
if not self._ghost_flag:
self.check_available_ram(self.ram)
# config paths are relative to the working directory configured on Dynamips hypervisor
startup_config_path = os.path.join("configs", "i{}_startup-config.cfg".format(self._dynamips_id))
private_config_path = os.path.join("configs", "i{}_private-config.cfg".format(self._dynamips_id))
if not os.path.exists(os.path.join(self._working_directory, private_config_path)) or \
not os.path.getsize(os.path.join(self._working_directory, private_config_path)):
# an empty private-config can prevent a router to boot.
private_config_path = ''
yield from self._hypervisor.send('vm set_config "{name}" "{startup}" "{private}"'.format(
name=self._name,
startup=startup_config_path,
private=private_config_path))
yield from self._hypervisor.send('vm start "{name}"'.format(name=self._name))
self.status = "started"
log.info('router "{name}" [{id}] has been started'.format(name=self._name, id=self._id))
self._memory_watcher = FileWatcher(self._memory_files(), self._memory_changed, strategy='hash', delay=30)
monitor_process(self._hypervisor.process, self._termination_callback) | [
"def",
"start",
"(",
"self",
")",
":",
"status",
"=",
"yield",
"from",
"self",
".",
"get_status",
"(",
")",
"if",
"status",
"==",
"\"suspended\"",
":",
"yield",
"from",
"self",
".",
"resume",
"(",
")",
"elif",
"status",
"==",
"\"inactive\"",
":",
"if",... | Starts this router.
At least the IOS image must be set before it can start. | [
"Starts",
"this",
"router",
".",
"At",
"least",
"the",
"IOS",
"image",
"must",
"be",
"set",
"before",
"it",
"can",
"start",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L254-L304 |
226,468 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.stop | def stop(self):
"""
Stops this router.
"""
status = yield from self.get_status()
if status != "inactive":
try:
yield from self._hypervisor.send('vm stop "{name}"'.format(name=self._name))
except DynamipsError as e:
log.warn("Could not stop {}: {}".format(self._name, e))
self.status = "stopped"
log.info('Router "{name}" [{id}] has been stopped'.format(name=self._name, id=self._id))
if self._memory_watcher:
self._memory_watcher.close()
self._memory_watcher = None
yield from self.save_configs() | python | def stop(self):
"""
Stops this router.
"""
status = yield from self.get_status()
if status != "inactive":
try:
yield from self._hypervisor.send('vm stop "{name}"'.format(name=self._name))
except DynamipsError as e:
log.warn("Could not stop {}: {}".format(self._name, e))
self.status = "stopped"
log.info('Router "{name}" [{id}] has been stopped'.format(name=self._name, id=self._id))
if self._memory_watcher:
self._memory_watcher.close()
self._memory_watcher = None
yield from self.save_configs() | [
"def",
"stop",
"(",
"self",
")",
":",
"status",
"=",
"yield",
"from",
"self",
".",
"get_status",
"(",
")",
"if",
"status",
"!=",
"\"inactive\"",
":",
"try",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm stop \"{name}\"'",
".",
... | Stops this router. | [
"Stops",
"this",
"router",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L321-L337 |
226,469 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.suspend | def suspend(self):
"""
Suspends this router.
"""
status = yield from self.get_status()
if status == "running":
yield from self._hypervisor.send('vm suspend "{name}"'.format(name=self._name))
self.status = "suspended"
log.info('Router "{name}" [{id}] has been suspended'.format(name=self._name, id=self._id)) | python | def suspend(self):
"""
Suspends this router.
"""
status = yield from self.get_status()
if status == "running":
yield from self._hypervisor.send('vm suspend "{name}"'.format(name=self._name))
self.status = "suspended"
log.info('Router "{name}" [{id}] has been suspended'.format(name=self._name, id=self._id)) | [
"def",
"suspend",
"(",
"self",
")",
":",
"status",
"=",
"yield",
"from",
"self",
".",
"get_status",
"(",
")",
"if",
"status",
"==",
"\"running\"",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm suspend \"{name}\"'",
".",
"format",... | Suspends this router. | [
"Suspends",
"this",
"router",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L349-L358 |
226,470 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.set_image | def set_image(self, image):
"""
Sets the IOS image for this router.
There is no default.
:param image: path to IOS image file
"""
image = self.manager.get_abs_image_path(image)
yield from self._hypervisor.send('vm set_ios "{name}" "{image}"'.format(name=self._name, image=image))
log.info('Router "{name}" [{id}]: has a new IOS image set: "{image}"'.format(name=self._name,
id=self._id,
image=image))
self._image = image | python | def set_image(self, image):
"""
Sets the IOS image for this router.
There is no default.
:param image: path to IOS image file
"""
image = self.manager.get_abs_image_path(image)
yield from self._hypervisor.send('vm set_ios "{name}" "{image}"'.format(name=self._name, image=image))
log.info('Router "{name}" [{id}]: has a new IOS image set: "{image}"'.format(name=self._name,
id=self._id,
image=image))
self._image = image | [
"def",
"set_image",
"(",
"self",
",",
"image",
")",
":",
"image",
"=",
"self",
".",
"manager",
".",
"get_abs_image_path",
"(",
"image",
")",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm set_ios \"{name}\" \"{image}\"'",
".",
"format",
... | Sets the IOS image for this router.
There is no default.
:param image: path to IOS image file | [
"Sets",
"the",
"IOS",
"image",
"for",
"this",
"router",
".",
"There",
"is",
"no",
"default",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L491-L507 |
226,471 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.set_ram | def set_ram(self, ram):
"""
Sets amount of RAM allocated to this router
:param ram: amount of RAM in Mbytes (integer)
"""
if self._ram == ram:
return
yield from self._hypervisor.send('vm set_ram "{name}" {ram}'.format(name=self._name, ram=ram))
log.info('Router "{name}" [{id}]: RAM updated from {old_ram}MB to {new_ram}MB'.format(name=self._name,
id=self._id,
old_ram=self._ram,
new_ram=ram))
self._ram = ram | python | def set_ram(self, ram):
"""
Sets amount of RAM allocated to this router
:param ram: amount of RAM in Mbytes (integer)
"""
if self._ram == ram:
return
yield from self._hypervisor.send('vm set_ram "{name}" {ram}'.format(name=self._name, ram=ram))
log.info('Router "{name}" [{id}]: RAM updated from {old_ram}MB to {new_ram}MB'.format(name=self._name,
id=self._id,
old_ram=self._ram,
new_ram=ram))
self._ram = ram | [
"def",
"set_ram",
"(",
"self",
",",
"ram",
")",
":",
"if",
"self",
".",
"_ram",
"==",
"ram",
":",
"return",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm set_ram \"{name}\" {ram}'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_... | Sets amount of RAM allocated to this router
:param ram: amount of RAM in Mbytes (integer) | [
"Sets",
"amount",
"of",
"RAM",
"allocated",
"to",
"this",
"router"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L520-L535 |
226,472 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.set_nvram | def set_nvram(self, nvram):
"""
Sets amount of NVRAM allocated to this router
:param nvram: amount of NVRAM in Kbytes (integer)
"""
if self._nvram == nvram:
return
yield from self._hypervisor.send('vm set_nvram "{name}" {nvram}'.format(name=self._name, nvram=nvram))
log.info('Router "{name}" [{id}]: NVRAM updated from {old_nvram}KB to {new_nvram}KB'.format(name=self._name,
id=self._id,
old_nvram=self._nvram,
new_nvram=nvram))
self._nvram = nvram | python | def set_nvram(self, nvram):
"""
Sets amount of NVRAM allocated to this router
:param nvram: amount of NVRAM in Kbytes (integer)
"""
if self._nvram == nvram:
return
yield from self._hypervisor.send('vm set_nvram "{name}" {nvram}'.format(name=self._name, nvram=nvram))
log.info('Router "{name}" [{id}]: NVRAM updated from {old_nvram}KB to {new_nvram}KB'.format(name=self._name,
id=self._id,
old_nvram=self._nvram,
new_nvram=nvram))
self._nvram = nvram | [
"def",
"set_nvram",
"(",
"self",
",",
"nvram",
")",
":",
"if",
"self",
".",
"_nvram",
"==",
"nvram",
":",
"return",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm set_nvram \"{name}\" {nvram}'",
".",
"format",
"(",
"name",
"=",
"self",... | Sets amount of NVRAM allocated to this router
:param nvram: amount of NVRAM in Kbytes (integer) | [
"Sets",
"amount",
"of",
"NVRAM",
"allocated",
"to",
"this",
"router"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L548-L563 |
226,473 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.set_clock_divisor | def set_clock_divisor(self, clock_divisor):
"""
Sets the clock divisor value. The higher is the value, the faster is the clock in the
virtual machine. The default is 4, but it is often required to adjust it.
:param clock_divisor: clock divisor value (integer)
"""
yield from self._hypervisor.send('vm set_clock_divisor "{name}" {clock}'.format(name=self._name, clock=clock_divisor))
log.info('Router "{name}" [{id}]: clock divisor updated from {old_clock} to {new_clock}'.format(name=self._name,
id=self._id,
old_clock=self._clock_divisor,
new_clock=clock_divisor))
self._clock_divisor = clock_divisor | python | def set_clock_divisor(self, clock_divisor):
"""
Sets the clock divisor value. The higher is the value, the faster is the clock in the
virtual machine. The default is 4, but it is often required to adjust it.
:param clock_divisor: clock divisor value (integer)
"""
yield from self._hypervisor.send('vm set_clock_divisor "{name}" {clock}'.format(name=self._name, clock=clock_divisor))
log.info('Router "{name}" [{id}]: clock divisor updated from {old_clock} to {new_clock}'.format(name=self._name,
id=self._id,
old_clock=self._clock_divisor,
new_clock=clock_divisor))
self._clock_divisor = clock_divisor | [
"def",
"set_clock_divisor",
"(",
"self",
",",
"clock_divisor",
")",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm set_clock_divisor \"{name}\" {clock}'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"clock",
"=",
"cloc... | Sets the clock divisor value. The higher is the value, the faster is the clock in the
virtual machine. The default is 4, but it is often required to adjust it.
:param clock_divisor: clock divisor value (integer) | [
"Sets",
"the",
"clock",
"divisor",
"value",
".",
"The",
"higher",
"is",
"the",
"value",
"the",
"faster",
"is",
"the",
"clock",
"in",
"the",
"virtual",
"machine",
".",
"The",
"default",
"is",
"4",
"but",
"it",
"is",
"often",
"required",
"to",
"adjust",
... | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L638-L651 |
226,474 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.get_idle_pc_prop | def get_idle_pc_prop(self):
"""
Gets the idle PC proposals.
Takes 1000 measurements and records up to 10 idle PC proposals.
There is a 10ms wait between each measurement.
:returns: list of idle PC proposal
"""
is_running = yield from self.is_running()
was_auto_started = False
if not is_running:
yield from self.start()
was_auto_started = True
yield from asyncio.sleep(20) # leave time to the router to boot
log.info('Router "{name}" [{id}] has started calculating Idle-PC values'.format(name=self._name, id=self._id))
begin = time.time()
idlepcs = yield from self._hypervisor.send('vm get_idle_pc_prop "{}" 0'.format(self._name))
log.info('Router "{name}" [{id}] has finished calculating Idle-PC values after {time:.4f} seconds'.format(name=self._name,
id=self._id,
time=time.time() - begin))
if was_auto_started:
yield from self.stop()
return idlepcs | python | def get_idle_pc_prop(self):
"""
Gets the idle PC proposals.
Takes 1000 measurements and records up to 10 idle PC proposals.
There is a 10ms wait between each measurement.
:returns: list of idle PC proposal
"""
is_running = yield from self.is_running()
was_auto_started = False
if not is_running:
yield from self.start()
was_auto_started = True
yield from asyncio.sleep(20) # leave time to the router to boot
log.info('Router "{name}" [{id}] has started calculating Idle-PC values'.format(name=self._name, id=self._id))
begin = time.time()
idlepcs = yield from self._hypervisor.send('vm get_idle_pc_prop "{}" 0'.format(self._name))
log.info('Router "{name}" [{id}] has finished calculating Idle-PC values after {time:.4f} seconds'.format(name=self._name,
id=self._id,
time=time.time() - begin))
if was_auto_started:
yield from self.stop()
return idlepcs | [
"def",
"get_idle_pc_prop",
"(",
"self",
")",
":",
"is_running",
"=",
"yield",
"from",
"self",
".",
"is_running",
"(",
")",
"was_auto_started",
"=",
"False",
"if",
"not",
"is_running",
":",
"yield",
"from",
"self",
".",
"start",
"(",
")",
"was_auto_started",
... | Gets the idle PC proposals.
Takes 1000 measurements and records up to 10 idle PC proposals.
There is a 10ms wait between each measurement.
:returns: list of idle PC proposal | [
"Gets",
"the",
"idle",
"PC",
"proposals",
".",
"Takes",
"1000",
"measurements",
"and",
"records",
"up",
"to",
"10",
"idle",
"PC",
"proposals",
".",
"There",
"is",
"a",
"10ms",
"wait",
"between",
"each",
"measurement",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L685-L709 |
226,475 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.set_idlemax | def set_idlemax(self, idlemax):
"""
Sets CPU idle max value
:param idlemax: idle max value (integer)
"""
is_running = yield from self.is_running()
if is_running: # router is running
yield from self._hypervisor.send('vm set_idle_max "{name}" 0 {idlemax}'.format(name=self._name, idlemax=idlemax))
log.info('Router "{name}" [{id}]: idlemax updated from {old_idlemax} to {new_idlemax}'.format(name=self._name,
id=self._id,
old_idlemax=self._idlemax,
new_idlemax=idlemax))
self._idlemax = idlemax | python | def set_idlemax(self, idlemax):
"""
Sets CPU idle max value
:param idlemax: idle max value (integer)
"""
is_running = yield from self.is_running()
if is_running: # router is running
yield from self._hypervisor.send('vm set_idle_max "{name}" 0 {idlemax}'.format(name=self._name, idlemax=idlemax))
log.info('Router "{name}" [{id}]: idlemax updated from {old_idlemax} to {new_idlemax}'.format(name=self._name,
id=self._id,
old_idlemax=self._idlemax,
new_idlemax=idlemax))
self._idlemax = idlemax | [
"def",
"set_idlemax",
"(",
"self",
",",
"idlemax",
")",
":",
"is_running",
"=",
"yield",
"from",
"self",
".",
"is_running",
"(",
")",
"if",
"is_running",
":",
"# router is running",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm set_idle... | Sets CPU idle max value
:param idlemax: idle max value (integer) | [
"Sets",
"CPU",
"idle",
"max",
"value"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L738-L754 |
226,476 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.set_idlesleep | def set_idlesleep(self, idlesleep):
"""
Sets CPU idle sleep time value.
:param idlesleep: idle sleep value (integer)
"""
is_running = yield from self.is_running()
if is_running: # router is running
yield from self._hypervisor.send('vm set_idle_sleep_time "{name}" 0 {idlesleep}'.format(name=self._name,
idlesleep=idlesleep))
log.info('Router "{name}" [{id}]: idlesleep updated from {old_idlesleep} to {new_idlesleep}'.format(name=self._name,
id=self._id,
old_idlesleep=self._idlesleep,
new_idlesleep=idlesleep))
self._idlesleep = idlesleep | python | def set_idlesleep(self, idlesleep):
"""
Sets CPU idle sleep time value.
:param idlesleep: idle sleep value (integer)
"""
is_running = yield from self.is_running()
if is_running: # router is running
yield from self._hypervisor.send('vm set_idle_sleep_time "{name}" 0 {idlesleep}'.format(name=self._name,
idlesleep=idlesleep))
log.info('Router "{name}" [{id}]: idlesleep updated from {old_idlesleep} to {new_idlesleep}'.format(name=self._name,
id=self._id,
old_idlesleep=self._idlesleep,
new_idlesleep=idlesleep))
self._idlesleep = idlesleep | [
"def",
"set_idlesleep",
"(",
"self",
",",
"idlesleep",
")",
":",
"is_running",
"=",
"yield",
"from",
"self",
".",
"is_running",
"(",
")",
"if",
"is_running",
":",
"# router is running",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm set_... | Sets CPU idle sleep time value.
:param idlesleep: idle sleep value (integer) | [
"Sets",
"CPU",
"idle",
"sleep",
"time",
"value",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L767-L784 |
226,477 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.set_ghost_file | def set_ghost_file(self, ghost_file):
"""
Sets ghost RAM file
:ghost_file: path to ghost file
"""
yield from self._hypervisor.send('vm set_ghost_file "{name}" {ghost_file}'.format(name=self._name,
ghost_file=shlex.quote(ghost_file)))
log.info('Router "{name}" [{id}]: ghost file set to {ghost_file}'.format(name=self._name,
id=self._id,
ghost_file=ghost_file))
self._ghost_file = ghost_file | python | def set_ghost_file(self, ghost_file):
"""
Sets ghost RAM file
:ghost_file: path to ghost file
"""
yield from self._hypervisor.send('vm set_ghost_file "{name}" {ghost_file}'.format(name=self._name,
ghost_file=shlex.quote(ghost_file)))
log.info('Router "{name}" [{id}]: ghost file set to {ghost_file}'.format(name=self._name,
id=self._id,
ghost_file=ghost_file))
self._ghost_file = ghost_file | [
"def",
"set_ghost_file",
"(",
"self",
",",
"ghost_file",
")",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm set_ghost_file \"{name}\" {ghost_file}'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"ghost_file",
"=",
"shl... | Sets ghost RAM file
:ghost_file: path to ghost file | [
"Sets",
"ghost",
"RAM",
"file"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L797-L811 |
226,478 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.formatted_ghost_file | def formatted_ghost_file(self):
"""
Returns a properly formatted ghost file name.
:returns: formatted ghost_file name (string)
"""
# replace specials characters in 'drive:\filename' in Linux and Dynamips in MS Windows or viceversa.
ghost_file = "{}-{}.ghost".format(os.path.basename(self._image), self._ram)
ghost_file = ghost_file.replace('\\', '-').replace('/', '-').replace(':', '-')
return ghost_file | python | def formatted_ghost_file(self):
"""
Returns a properly formatted ghost file name.
:returns: formatted ghost_file name (string)
"""
# replace specials characters in 'drive:\filename' in Linux and Dynamips in MS Windows or viceversa.
ghost_file = "{}-{}.ghost".format(os.path.basename(self._image), self._ram)
ghost_file = ghost_file.replace('\\', '-').replace('/', '-').replace(':', '-')
return ghost_file | [
"def",
"formatted_ghost_file",
"(",
"self",
")",
":",
"# replace specials characters in 'drive:\\filename' in Linux and Dynamips in MS Windows or viceversa.",
"ghost_file",
"=",
"\"{}-{}.ghost\"",
".",
"format",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"_i... | Returns a properly formatted ghost file name.
:returns: formatted ghost_file name (string) | [
"Returns",
"a",
"properly",
"formatted",
"ghost",
"file",
"name",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L813-L823 |
226,479 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.set_ghost_status | def set_ghost_status(self, ghost_status):
"""
Sets ghost RAM status
:param ghost_status: state flag indicating status
0 => Do not use IOS ghosting
1 => This is a ghost instance
2 => Use an existing ghost instance
"""
yield from self._hypervisor.send('vm set_ghost_status "{name}" {ghost_status}'.format(name=self._name,
ghost_status=ghost_status))
log.info('Router "{name}" [{id}]: ghost status set to {ghost_status}'.format(name=self._name,
id=self._id,
ghost_status=ghost_status))
self._ghost_status = ghost_status | python | def set_ghost_status(self, ghost_status):
"""
Sets ghost RAM status
:param ghost_status: state flag indicating status
0 => Do not use IOS ghosting
1 => This is a ghost instance
2 => Use an existing ghost instance
"""
yield from self._hypervisor.send('vm set_ghost_status "{name}" {ghost_status}'.format(name=self._name,
ghost_status=ghost_status))
log.info('Router "{name}" [{id}]: ghost status set to {ghost_status}'.format(name=self._name,
id=self._id,
ghost_status=ghost_status))
self._ghost_status = ghost_status | [
"def",
"set_ghost_status",
"(",
"self",
",",
"ghost_status",
")",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm set_ghost_status \"{name}\" {ghost_status}'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"ghost_status",
"... | Sets ghost RAM status
:param ghost_status: state flag indicating status
0 => Do not use IOS ghosting
1 => This is a ghost instance
2 => Use an existing ghost instance | [
"Sets",
"ghost",
"RAM",
"status"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L835-L851 |
226,480 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.set_console | def set_console(self, console):
"""
Sets the TCP console port.
:param console: console port (integer)
"""
self.console = console
yield from self._hypervisor.send('vm set_con_tcp_port "{name}" {console}'.format(name=self._name, console=self.console)) | python | def set_console(self, console):
"""
Sets the TCP console port.
:param console: console port (integer)
"""
self.console = console
yield from self._hypervisor.send('vm set_con_tcp_port "{name}" {console}'.format(name=self._name, console=self.console)) | [
"def",
"set_console",
"(",
"self",
",",
"console",
")",
":",
"self",
".",
"console",
"=",
"console",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm set_con_tcp_port \"{name}\" {console}'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_... | Sets the TCP console port.
:param console: console port (integer) | [
"Sets",
"the",
"TCP",
"console",
"port",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L960-L968 |
226,481 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.set_aux | def set_aux(self, aux):
"""
Sets the TCP auxiliary port.
:param aux: console auxiliary port (integer)
"""
self.aux = aux
yield from self._hypervisor.send('vm set_aux_tcp_port "{name}" {aux}'.format(name=self._name, aux=aux)) | python | def set_aux(self, aux):
"""
Sets the TCP auxiliary port.
:param aux: console auxiliary port (integer)
"""
self.aux = aux
yield from self._hypervisor.send('vm set_aux_tcp_port "{name}" {aux}'.format(name=self._name, aux=aux)) | [
"def",
"set_aux",
"(",
"self",
",",
"aux",
")",
":",
"self",
".",
"aux",
"=",
"aux",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm set_aux_tcp_port \"{name}\" {aux}'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"aux... | Sets the TCP auxiliary port.
:param aux: console auxiliary port (integer) | [
"Sets",
"the",
"TCP",
"auxiliary",
"port",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L971-L979 |
226,482 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.get_cpu_usage | def get_cpu_usage(self, cpu_id=0):
"""
Shows cpu usage in seconds, "cpu_id" is ignored.
:returns: cpu usage in seconds
"""
cpu_usage = yield from self._hypervisor.send('vm cpu_usage "{name}" {cpu_id}'.format(name=self._name, cpu_id=cpu_id))
return int(cpu_usage[0]) | python | def get_cpu_usage(self, cpu_id=0):
"""
Shows cpu usage in seconds, "cpu_id" is ignored.
:returns: cpu usage in seconds
"""
cpu_usage = yield from self._hypervisor.send('vm cpu_usage "{name}" {cpu_id}'.format(name=self._name, cpu_id=cpu_id))
return int(cpu_usage[0]) | [
"def",
"get_cpu_usage",
"(",
"self",
",",
"cpu_id",
"=",
"0",
")",
":",
"cpu_usage",
"=",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm cpu_usage \"{name}\" {cpu_id}'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"cpu_... | Shows cpu usage in seconds, "cpu_id" is ignored.
:returns: cpu usage in seconds | [
"Shows",
"cpu",
"usage",
"in",
"seconds",
"cpu_id",
"is",
"ignored",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L982-L990 |
226,483 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.set_mac_addr | def set_mac_addr(self, mac_addr):
"""
Sets the MAC address.
:param mac_addr: a MAC address (hexadecimal format: hh:hh:hh:hh:hh:hh)
"""
yield from self._hypervisor.send('{platform} set_mac_addr "{name}" {mac_addr}'.format(platform=self._platform,
name=self._name,
mac_addr=mac_addr))
log.info('Router "{name}" [{id}]: MAC address updated from {old_mac} to {new_mac}'.format(name=self._name,
id=self._id,
old_mac=self._mac_addr,
new_mac=mac_addr))
self._mac_addr = mac_addr | python | def set_mac_addr(self, mac_addr):
"""
Sets the MAC address.
:param mac_addr: a MAC address (hexadecimal format: hh:hh:hh:hh:hh:hh)
"""
yield from self._hypervisor.send('{platform} set_mac_addr "{name}" {mac_addr}'.format(platform=self._platform,
name=self._name,
mac_addr=mac_addr))
log.info('Router "{name}" [{id}]: MAC address updated from {old_mac} to {new_mac}'.format(name=self._name,
id=self._id,
old_mac=self._mac_addr,
new_mac=mac_addr))
self._mac_addr = mac_addr | [
"def",
"set_mac_addr",
"(",
"self",
",",
"mac_addr",
")",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'{platform} set_mac_addr \"{name}\" {mac_addr}'",
".",
"format",
"(",
"platform",
"=",
"self",
".",
"_platform",
",",
"name",
"=",
"s... | Sets the MAC address.
:param mac_addr: a MAC address (hexadecimal format: hh:hh:hh:hh:hh:hh) | [
"Sets",
"the",
"MAC",
"address",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L1003-L1018 |
226,484 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.set_system_id | def set_system_id(self, system_id):
"""
Sets the system ID.
:param system_id: a system ID (also called board processor ID)
"""
yield from self._hypervisor.send('{platform} set_system_id "{name}" {system_id}'.format(platform=self._platform,
name=self._name,
system_id=system_id))
log.info('Router "{name}" [{id}]: system ID updated from {old_id} to {new_id}'.format(name=self._name,
id=self._id,
old_id=self._system_id,
new_id=system_id))
self._system_id = system_id | python | def set_system_id(self, system_id):
"""
Sets the system ID.
:param system_id: a system ID (also called board processor ID)
"""
yield from self._hypervisor.send('{platform} set_system_id "{name}" {system_id}'.format(platform=self._platform,
name=self._name,
system_id=system_id))
log.info('Router "{name}" [{id}]: system ID updated from {old_id} to {new_id}'.format(name=self._name,
id=self._id,
old_id=self._system_id,
new_id=system_id))
self._system_id = system_id | [
"def",
"set_system_id",
"(",
"self",
",",
"system_id",
")",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'{platform} set_system_id \"{name}\" {system_id}'",
".",
"format",
"(",
"platform",
"=",
"self",
".",
"_platform",
",",
"name",
"=",
... | Sets the system ID.
:param system_id: a system ID (also called board processor ID) | [
"Sets",
"the",
"system",
"ID",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L1031-L1046 |
226,485 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.get_slot_bindings | def get_slot_bindings(self):
"""
Returns slot bindings.
:returns: slot bindings (adapter names) list
"""
slot_bindings = yield from self._hypervisor.send('vm slot_bindings "{}"'.format(self._name))
return slot_bindings | python | def get_slot_bindings(self):
"""
Returns slot bindings.
:returns: slot bindings (adapter names) list
"""
slot_bindings = yield from self._hypervisor.send('vm slot_bindings "{}"'.format(self._name))
return slot_bindings | [
"def",
"get_slot_bindings",
"(",
"self",
")",
":",
"slot_bindings",
"=",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm slot_bindings \"{}\"'",
".",
"format",
"(",
"self",
".",
"_name",
")",
")",
"return",
"slot_bindings"
] | Returns slot bindings.
:returns: slot bindings (adapter names) list | [
"Returns",
"slot",
"bindings",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L1049-L1057 |
226,486 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.uninstall_wic | def uninstall_wic(self, wic_slot_number):
"""
Uninstalls a WIC adapter from this router.
:param wic_slot_number: WIC slot number
"""
# WICs are always installed on adapters in slot 0
slot_number = 0
# Do not check if slot has an adapter because adapters with WICs interfaces
# must be inserted by default in the router and cannot be removed.
adapter = self._slots[slot_number]
if wic_slot_number > len(adapter.wics) - 1:
raise DynamipsError("WIC slot {wic_slot_number} doesn't exist".format(wic_slot_number=wic_slot_number))
if adapter.wic_slot_available(wic_slot_number):
raise DynamipsError("No WIC is installed in WIC slot {wic_slot_number}".format(wic_slot_number=wic_slot_number))
# Dynamips WICs slot IDs start on a multiple of 16
# WIC1 = 16, WIC2 = 32 and WIC3 = 48
internal_wic_slot_number = 16 * (wic_slot_number + 1)
yield from self._hypervisor.send('vm slot_remove_binding "{name}" {slot_number} {wic_slot_number}'.format(name=self._name,
slot_number=slot_number,
wic_slot_number=internal_wic_slot_number))
log.info('Router "{name}" [{id}]: {wic} removed from WIC slot {wic_slot_number}'.format(name=self._name,
id=self._id,
wic=adapter.wics[wic_slot_number],
wic_slot_number=wic_slot_number))
adapter.uninstall_wic(wic_slot_number) | python | def uninstall_wic(self, wic_slot_number):
"""
Uninstalls a WIC adapter from this router.
:param wic_slot_number: WIC slot number
"""
# WICs are always installed on adapters in slot 0
slot_number = 0
# Do not check if slot has an adapter because adapters with WICs interfaces
# must be inserted by default in the router and cannot be removed.
adapter = self._slots[slot_number]
if wic_slot_number > len(adapter.wics) - 1:
raise DynamipsError("WIC slot {wic_slot_number} doesn't exist".format(wic_slot_number=wic_slot_number))
if adapter.wic_slot_available(wic_slot_number):
raise DynamipsError("No WIC is installed in WIC slot {wic_slot_number}".format(wic_slot_number=wic_slot_number))
# Dynamips WICs slot IDs start on a multiple of 16
# WIC1 = 16, WIC2 = 32 and WIC3 = 48
internal_wic_slot_number = 16 * (wic_slot_number + 1)
yield from self._hypervisor.send('vm slot_remove_binding "{name}" {slot_number} {wic_slot_number}'.format(name=self._name,
slot_number=slot_number,
wic_slot_number=internal_wic_slot_number))
log.info('Router "{name}" [{id}]: {wic} removed from WIC slot {wic_slot_number}'.format(name=self._name,
id=self._id,
wic=adapter.wics[wic_slot_number],
wic_slot_number=wic_slot_number))
adapter.uninstall_wic(wic_slot_number) | [
"def",
"uninstall_wic",
"(",
"self",
",",
"wic_slot_number",
")",
":",
"# WICs are always installed on adapters in slot 0",
"slot_number",
"=",
"0",
"# Do not check if slot has an adapter because adapters with WICs interfaces",
"# must be inserted by default in the router and cannot be rem... | Uninstalls a WIC adapter from this router.
:param wic_slot_number: WIC slot number | [
"Uninstalls",
"a",
"WIC",
"adapter",
"from",
"this",
"router",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L1193-L1224 |
226,487 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.get_slot_nio_bindings | def get_slot_nio_bindings(self, slot_number):
"""
Returns slot NIO bindings.
:param slot_number: slot number
:returns: list of NIO bindings
"""
nio_bindings = yield from self._hypervisor.send('vm slot_nio_bindings "{name}" {slot_number}'.format(name=self._name,
slot_number=slot_number))
return nio_bindings | python | def get_slot_nio_bindings(self, slot_number):
"""
Returns slot NIO bindings.
:param slot_number: slot number
:returns: list of NIO bindings
"""
nio_bindings = yield from self._hypervisor.send('vm slot_nio_bindings "{name}" {slot_number}'.format(name=self._name,
slot_number=slot_number))
return nio_bindings | [
"def",
"get_slot_nio_bindings",
"(",
"self",
",",
"slot_number",
")",
":",
"nio_bindings",
"=",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm slot_nio_bindings \"{name}\" {slot_number}'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",... | Returns slot NIO bindings.
:param slot_number: slot number
:returns: list of NIO bindings | [
"Returns",
"slot",
"NIO",
"bindings",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L1227-L1238 |
226,488 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.slot_add_nio_binding | def slot_add_nio_binding(self, slot_number, port_number, nio):
"""
Adds a slot NIO binding.
:param slot_number: slot number
:param port_number: port number
:param nio: NIO instance to add to the slot/port
"""
try:
adapter = self._slots[slot_number]
except IndexError:
raise DynamipsError('Slot {slot_number} does not exist on router "{name}"'.format(name=self._name,
slot_number=slot_number))
if adapter is None:
raise DynamipsError("Adapter is missing in slot {slot_number}".format(slot_number=slot_number))
if not adapter.port_exists(port_number):
raise DynamipsError("Port {port_number} does not exist in adapter {adapter}".format(adapter=adapter,
port_number=port_number))
try:
yield from self._hypervisor.send('vm slot_add_nio_binding "{name}" {slot_number} {port_number} {nio}'.format(name=self._name,
slot_number=slot_number,
port_number=port_number,
nio=nio))
except DynamipsError:
# in case of error try to remove and add the nio binding
yield from self._hypervisor.send('vm slot_remove_nio_binding "{name}" {slot_number} {port_number}'.format(name=self._name,
slot_number=slot_number,
port_number=port_number))
yield from self._hypervisor.send('vm slot_add_nio_binding "{name}" {slot_number} {port_number} {nio}'.format(name=self._name,
slot_number=slot_number,
port_number=port_number,
nio=nio))
log.info('Router "{name}" [{id}]: NIO {nio_name} bound to port {slot_number}/{port_number}'.format(name=self._name,
id=self._id,
nio_name=nio.name,
slot_number=slot_number,
port_number=port_number))
yield from self.slot_enable_nio(slot_number, port_number)
adapter.add_nio(port_number, nio) | python | def slot_add_nio_binding(self, slot_number, port_number, nio):
"""
Adds a slot NIO binding.
:param slot_number: slot number
:param port_number: port number
:param nio: NIO instance to add to the slot/port
"""
try:
adapter = self._slots[slot_number]
except IndexError:
raise DynamipsError('Slot {slot_number} does not exist on router "{name}"'.format(name=self._name,
slot_number=slot_number))
if adapter is None:
raise DynamipsError("Adapter is missing in slot {slot_number}".format(slot_number=slot_number))
if not adapter.port_exists(port_number):
raise DynamipsError("Port {port_number} does not exist in adapter {adapter}".format(adapter=adapter,
port_number=port_number))
try:
yield from self._hypervisor.send('vm slot_add_nio_binding "{name}" {slot_number} {port_number} {nio}'.format(name=self._name,
slot_number=slot_number,
port_number=port_number,
nio=nio))
except DynamipsError:
# in case of error try to remove and add the nio binding
yield from self._hypervisor.send('vm slot_remove_nio_binding "{name}" {slot_number} {port_number}'.format(name=self._name,
slot_number=slot_number,
port_number=port_number))
yield from self._hypervisor.send('vm slot_add_nio_binding "{name}" {slot_number} {port_number} {nio}'.format(name=self._name,
slot_number=slot_number,
port_number=port_number,
nio=nio))
log.info('Router "{name}" [{id}]: NIO {nio_name} bound to port {slot_number}/{port_number}'.format(name=self._name,
id=self._id,
nio_name=nio.name,
slot_number=slot_number,
port_number=port_number))
yield from self.slot_enable_nio(slot_number, port_number)
adapter.add_nio(port_number, nio) | [
"def",
"slot_add_nio_binding",
"(",
"self",
",",
"slot_number",
",",
"port_number",
",",
"nio",
")",
":",
"try",
":",
"adapter",
"=",
"self",
".",
"_slots",
"[",
"slot_number",
"]",
"except",
"IndexError",
":",
"raise",
"DynamipsError",
"(",
"'Slot {slot_numbe... | Adds a slot NIO binding.
:param slot_number: slot number
:param port_number: port number
:param nio: NIO instance to add to the slot/port | [
"Adds",
"a",
"slot",
"NIO",
"binding",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L1241-L1285 |
226,489 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.slot_remove_nio_binding | def slot_remove_nio_binding(self, slot_number, port_number):
"""
Removes a slot NIO binding.
:param slot_number: slot number
:param port_number: port number
:returns: removed NIO instance
"""
try:
adapter = self._slots[slot_number]
except IndexError:
raise DynamipsError('Slot {slot_number} does not exist on router "{name}"'.format(name=self._name,
slot_number=slot_number))
if adapter is None:
raise DynamipsError("Adapter is missing in slot {slot_number}".format(slot_number=slot_number))
if not adapter.port_exists(port_number):
raise DynamipsError("Port {port_number} does not exist in adapter {adapter}".format(adapter=adapter,
port_number=port_number))
yield from self.slot_disable_nio(slot_number, port_number)
yield from self._hypervisor.send('vm slot_remove_nio_binding "{name}" {slot_number} {port_number}'.format(name=self._name,
slot_number=slot_number,
port_number=port_number))
nio = adapter.get_nio(port_number)
if nio is None:
return
yield from nio.close()
adapter.remove_nio(port_number)
log.info('Router "{name}" [{id}]: NIO {nio_name} removed from port {slot_number}/{port_number}'.format(name=self._name,
id=self._id,
nio_name=nio.name,
slot_number=slot_number,
port_number=port_number))
return nio | python | def slot_remove_nio_binding(self, slot_number, port_number):
"""
Removes a slot NIO binding.
:param slot_number: slot number
:param port_number: port number
:returns: removed NIO instance
"""
try:
adapter = self._slots[slot_number]
except IndexError:
raise DynamipsError('Slot {slot_number} does not exist on router "{name}"'.format(name=self._name,
slot_number=slot_number))
if adapter is None:
raise DynamipsError("Adapter is missing in slot {slot_number}".format(slot_number=slot_number))
if not adapter.port_exists(port_number):
raise DynamipsError("Port {port_number} does not exist in adapter {adapter}".format(adapter=adapter,
port_number=port_number))
yield from self.slot_disable_nio(slot_number, port_number)
yield from self._hypervisor.send('vm slot_remove_nio_binding "{name}" {slot_number} {port_number}'.format(name=self._name,
slot_number=slot_number,
port_number=port_number))
nio = adapter.get_nio(port_number)
if nio is None:
return
yield from nio.close()
adapter.remove_nio(port_number)
log.info('Router "{name}" [{id}]: NIO {nio_name} removed from port {slot_number}/{port_number}'.format(name=self._name,
id=self._id,
nio_name=nio.name,
slot_number=slot_number,
port_number=port_number))
return nio | [
"def",
"slot_remove_nio_binding",
"(",
"self",
",",
"slot_number",
",",
"port_number",
")",
":",
"try",
":",
"adapter",
"=",
"self",
".",
"_slots",
"[",
"slot_number",
"]",
"except",
"IndexError",
":",
"raise",
"DynamipsError",
"(",
"'Slot {slot_number} does not e... | Removes a slot NIO binding.
:param slot_number: slot number
:param port_number: port number
:returns: removed NIO instance | [
"Removes",
"a",
"slot",
"NIO",
"binding",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L1299-L1339 |
226,490 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.slot_enable_nio | def slot_enable_nio(self, slot_number, port_number):
"""
Enables a slot NIO binding.
:param slot_number: slot number
:param port_number: port number
"""
is_running = yield from self.is_running()
if is_running: # running router
yield from self._hypervisor.send('vm slot_enable_nio "{name}" {slot_number} {port_number}'.format(name=self._name,
slot_number=slot_number,
port_number=port_number))
log.info('Router "{name}" [{id}]: NIO enabled on port {slot_number}/{port_number}'.format(name=self._name,
id=self._id,
slot_number=slot_number,
port_number=port_number)) | python | def slot_enable_nio(self, slot_number, port_number):
"""
Enables a slot NIO binding.
:param slot_number: slot number
:param port_number: port number
"""
is_running = yield from self.is_running()
if is_running: # running router
yield from self._hypervisor.send('vm slot_enable_nio "{name}" {slot_number} {port_number}'.format(name=self._name,
slot_number=slot_number,
port_number=port_number))
log.info('Router "{name}" [{id}]: NIO enabled on port {slot_number}/{port_number}'.format(name=self._name,
id=self._id,
slot_number=slot_number,
port_number=port_number)) | [
"def",
"slot_enable_nio",
"(",
"self",
",",
"slot_number",
",",
"port_number",
")",
":",
"is_running",
"=",
"yield",
"from",
"self",
".",
"is_running",
"(",
")",
"if",
"is_running",
":",
"# running router",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"... | Enables a slot NIO binding.
:param slot_number: slot number
:param port_number: port number | [
"Enables",
"a",
"slot",
"NIO",
"binding",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L1342-L1359 |
226,491 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/router.py | Router.set_name | def set_name(self, new_name):
"""
Renames this router.
:param new_name: new name string
"""
# change the hostname in the startup-config
if os.path.isfile(self.startup_config_path):
try:
with open(self.startup_config_path, "r+", encoding="utf-8", errors="replace") as f:
old_config = f.read()
new_config = re.sub(r"^hostname .+$", "hostname " + new_name, old_config, flags=re.MULTILINE)
f.seek(0)
f.write(new_config)
except OSError as e:
raise DynamipsError("Could not amend the configuration {}: {}".format(self.startup_config_path, e))
# change the hostname in the private-config
if os.path.isfile(self.private_config_path):
try:
with open(self.private_config_path, "r+", encoding="utf-8", errors="replace") as f:
old_config = f.read()
new_config = old_config.replace(self.name, new_name)
f.seek(0)
f.write(new_config)
except OSError as e:
raise DynamipsError("Could not amend the configuration {}: {}".format(self.private_config_path, e))
yield from self._hypervisor.send('vm rename "{name}" "{new_name}"'.format(name=self._name, new_name=new_name))
log.info('Router "{name}" [{id}]: renamed to "{new_name}"'.format(name=self._name, id=self._id, new_name=new_name))
self._name = new_name | python | def set_name(self, new_name):
"""
Renames this router.
:param new_name: new name string
"""
# change the hostname in the startup-config
if os.path.isfile(self.startup_config_path):
try:
with open(self.startup_config_path, "r+", encoding="utf-8", errors="replace") as f:
old_config = f.read()
new_config = re.sub(r"^hostname .+$", "hostname " + new_name, old_config, flags=re.MULTILINE)
f.seek(0)
f.write(new_config)
except OSError as e:
raise DynamipsError("Could not amend the configuration {}: {}".format(self.startup_config_path, e))
# change the hostname in the private-config
if os.path.isfile(self.private_config_path):
try:
with open(self.private_config_path, "r+", encoding="utf-8", errors="replace") as f:
old_config = f.read()
new_config = old_config.replace(self.name, new_name)
f.seek(0)
f.write(new_config)
except OSError as e:
raise DynamipsError("Could not amend the configuration {}: {}".format(self.private_config_path, e))
yield from self._hypervisor.send('vm rename "{name}" "{new_name}"'.format(name=self._name, new_name=new_name))
log.info('Router "{name}" [{id}]: renamed to "{new_name}"'.format(name=self._name, id=self._id, new_name=new_name))
self._name = new_name | [
"def",
"set_name",
"(",
"self",
",",
"new_name",
")",
":",
"# change the hostname in the startup-config",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"startup_config_path",
")",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"startup_config_p... | Renames this router.
:param new_name: new name string | [
"Renames",
"this",
"router",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/router.py#L1495-L1526 |
226,492 | GNS3/gns3-server | gns3server/utils/__init__.py | parse_version | def parse_version(version):
"""
Return a comparable tuple from a version string. We try to force tuple to semver with version like 1.2.0
Replace pkg_resources.parse_version which now display a warning when use for comparing version with tuple
:returns: Version string as comparable tuple
"""
release_type_found = False
version_infos = re.split('(\.|[a-z]+)', version)
version = []
for info in version_infos:
if info == '.' or len(info) == 0:
continue
try:
info = int(info)
# We pad with zero to compare only on string
# This avoid issue when comparing version with different length
version.append("%06d" % (info,))
except ValueError:
# Force to a version with three number
if len(version) == 1:
version.append("00000")
if len(version) == 2:
version.append("000000")
# We want rc to be at lower level than dev version
if info == 'rc':
info = 'c'
version.append(info)
release_type_found = True
if release_type_found is False:
# Force to a version with three number
if len(version) == 1:
version.append("00000")
if len(version) == 2:
version.append("000000")
version.append("final")
return tuple(version) | python | def parse_version(version):
"""
Return a comparable tuple from a version string. We try to force tuple to semver with version like 1.2.0
Replace pkg_resources.parse_version which now display a warning when use for comparing version with tuple
:returns: Version string as comparable tuple
"""
release_type_found = False
version_infos = re.split('(\.|[a-z]+)', version)
version = []
for info in version_infos:
if info == '.' or len(info) == 0:
continue
try:
info = int(info)
# We pad with zero to compare only on string
# This avoid issue when comparing version with different length
version.append("%06d" % (info,))
except ValueError:
# Force to a version with three number
if len(version) == 1:
version.append("00000")
if len(version) == 2:
version.append("000000")
# We want rc to be at lower level than dev version
if info == 'rc':
info = 'c'
version.append(info)
release_type_found = True
if release_type_found is False:
# Force to a version with three number
if len(version) == 1:
version.append("00000")
if len(version) == 2:
version.append("000000")
version.append("final")
return tuple(version) | [
"def",
"parse_version",
"(",
"version",
")",
":",
"release_type_found",
"=",
"False",
"version_infos",
"=",
"re",
".",
"split",
"(",
"'(\\.|[a-z]+)'",
",",
"version",
")",
"version",
"=",
"[",
"]",
"for",
"info",
"in",
"version_infos",
":",
"if",
"info",
"... | Return a comparable tuple from a version string. We try to force tuple to semver with version like 1.2.0
Replace pkg_resources.parse_version which now display a warning when use for comparing version with tuple
:returns: Version string as comparable tuple | [
"Return",
"a",
"comparable",
"tuple",
"from",
"a",
"version",
"string",
".",
"We",
"try",
"to",
"force",
"tuple",
"to",
"semver",
"with",
"version",
"like",
"1",
".",
"2",
".",
"0"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/__init__.py#L52-L90 |
226,493 | GNS3/gns3-server | gns3server/controller/gns3vm/virtualbox_gns3_vm.py | VirtualBoxGNS3VM._look_for_interface | def _look_for_interface(self, network_backend):
"""
Look for an interface with a specific network backend.
:returns: interface number or -1 if none is found
"""
result = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"])
interface = -1
for info in result.splitlines():
if '=' in info:
name, value = info.split('=', 1)
if name.startswith("nic") and value.strip('"') == network_backend:
try:
interface = int(name[3:])
break
except ValueError:
continue
return interface | python | def _look_for_interface(self, network_backend):
"""
Look for an interface with a specific network backend.
:returns: interface number or -1 if none is found
"""
result = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"])
interface = -1
for info in result.splitlines():
if '=' in info:
name, value = info.split('=', 1)
if name.startswith("nic") and value.strip('"') == network_backend:
try:
interface = int(name[3:])
break
except ValueError:
continue
return interface | [
"def",
"_look_for_interface",
"(",
"self",
",",
"network_backend",
")",
":",
"result",
"=",
"yield",
"from",
"self",
".",
"_execute",
"(",
"\"showvminfo\"",
",",
"[",
"self",
".",
"_vmname",
",",
"\"--machinereadable\"",
"]",
")",
"interface",
"=",
"-",
"1",... | Look for an interface with a specific network backend.
:returns: interface number or -1 if none is found | [
"Look",
"for",
"an",
"interface",
"with",
"a",
"specific",
"network",
"backend",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/virtualbox_gns3_vm.py#L68-L86 |
226,494 | GNS3/gns3-server | gns3server/controller/gns3vm/virtualbox_gns3_vm.py | VirtualBoxGNS3VM._look_for_vboxnet | def _look_for_vboxnet(self, interface_number):
"""
Look for the VirtualBox network name associated with a host only interface.
:returns: None or vboxnet name
"""
result = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"])
for info in result.splitlines():
if '=' in info:
name, value = info.split('=', 1)
if name == "hostonlyadapter{}".format(interface_number):
return value.strip('"')
return None | python | def _look_for_vboxnet(self, interface_number):
"""
Look for the VirtualBox network name associated with a host only interface.
:returns: None or vboxnet name
"""
result = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"])
for info in result.splitlines():
if '=' in info:
name, value = info.split('=', 1)
if name == "hostonlyadapter{}".format(interface_number):
return value.strip('"')
return None | [
"def",
"_look_for_vboxnet",
"(",
"self",
",",
"interface_number",
")",
":",
"result",
"=",
"yield",
"from",
"self",
".",
"_execute",
"(",
"\"showvminfo\"",
",",
"[",
"self",
".",
"_vmname",
",",
"\"--machinereadable\"",
"]",
")",
"for",
"info",
"in",
"result... | Look for the VirtualBox network name associated with a host only interface.
:returns: None or vboxnet name | [
"Look",
"for",
"the",
"VirtualBox",
"network",
"name",
"associated",
"with",
"a",
"host",
"only",
"interface",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/virtualbox_gns3_vm.py#L89-L102 |
226,495 | GNS3/gns3-server | gns3server/controller/gns3vm/virtualbox_gns3_vm.py | VirtualBoxGNS3VM._check_dhcp_server | def _check_dhcp_server(self, vboxnet):
"""
Check if the DHCP server associated with a vboxnet is enabled.
:param vboxnet: vboxnet name
:returns: boolean
"""
properties = yield from self._execute("list", ["dhcpservers"])
flag_dhcp_server_found = False
for prop in properties.splitlines():
try:
name, value = prop.split(':', 1)
except ValueError:
continue
if name.strip() == "NetworkName" and value.strip().endswith(vboxnet):
flag_dhcp_server_found = True
if flag_dhcp_server_found and name.strip() == "Enabled":
if value.strip() == "Yes":
return True
return False | python | def _check_dhcp_server(self, vboxnet):
"""
Check if the DHCP server associated with a vboxnet is enabled.
:param vboxnet: vboxnet name
:returns: boolean
"""
properties = yield from self._execute("list", ["dhcpservers"])
flag_dhcp_server_found = False
for prop in properties.splitlines():
try:
name, value = prop.split(':', 1)
except ValueError:
continue
if name.strip() == "NetworkName" and value.strip().endswith(vboxnet):
flag_dhcp_server_found = True
if flag_dhcp_server_found and name.strip() == "Enabled":
if value.strip() == "Yes":
return True
return False | [
"def",
"_check_dhcp_server",
"(",
"self",
",",
"vboxnet",
")",
":",
"properties",
"=",
"yield",
"from",
"self",
".",
"_execute",
"(",
"\"list\"",
",",
"[",
"\"dhcpservers\"",
"]",
")",
"flag_dhcp_server_found",
"=",
"False",
"for",
"prop",
"in",
"properties",
... | Check if the DHCP server associated with a vboxnet is enabled.
:param vboxnet: vboxnet name
:returns: boolean | [
"Check",
"if",
"the",
"DHCP",
"server",
"associated",
"with",
"a",
"vboxnet",
"is",
"enabled",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/virtualbox_gns3_vm.py#L105-L126 |
226,496 | GNS3/gns3-server | gns3server/controller/gns3vm/virtualbox_gns3_vm.py | VirtualBoxGNS3VM._check_vbox_port_forwarding | def _check_vbox_port_forwarding(self):
"""
Checks if the NAT port forwarding rule exists.
:returns: boolean
"""
result = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"])
for info in result.splitlines():
if '=' in info:
name, value = info.split('=', 1)
if name.startswith("Forwarding") and value.strip('"').startswith("GNS3VM"):
return True
return False | python | def _check_vbox_port_forwarding(self):
"""
Checks if the NAT port forwarding rule exists.
:returns: boolean
"""
result = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"])
for info in result.splitlines():
if '=' in info:
name, value = info.split('=', 1)
if name.startswith("Forwarding") and value.strip('"').startswith("GNS3VM"):
return True
return False | [
"def",
"_check_vbox_port_forwarding",
"(",
"self",
")",
":",
"result",
"=",
"yield",
"from",
"self",
".",
"_execute",
"(",
"\"showvminfo\"",
",",
"[",
"self",
".",
"_vmname",
",",
"\"--machinereadable\"",
"]",
")",
"for",
"info",
"in",
"result",
".",
"splitl... | Checks if the NAT port forwarding rule exists.
:returns: boolean | [
"Checks",
"if",
"the",
"NAT",
"port",
"forwarding",
"rule",
"exists",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/virtualbox_gns3_vm.py#L129-L142 |
226,497 | GNS3/gns3-server | gns3server/controller/gns3vm/virtualbox_gns3_vm.py | VirtualBoxGNS3VM.start | def start(self):
"""
Start the GNS3 VM.
"""
# get a NAT interface number
nat_interface_number = yield from self._look_for_interface("nat")
if nat_interface_number < 0:
raise GNS3VMError("The GNS3 VM: {} must have a NAT interface configured in order to start".format(self.vmname))
hostonly_interface_number = yield from self._look_for_interface("hostonly")
if hostonly_interface_number < 0:
raise GNS3VMError("The GNS3 VM: {} must have a host only interface configured in order to start".format(self.vmname))
vboxnet = yield from self._look_for_vboxnet(hostonly_interface_number)
if vboxnet is None:
raise GNS3VMError("VirtualBox host-only network could not be found for interface {} on GNS3 VM".format(hostonly_interface_number))
if not (yield from self._check_dhcp_server(vboxnet)):
raise GNS3VMError("DHCP must be enabled on VirtualBox host-only network: {} for GNS3 VM".format(vboxnet))
vm_state = yield from self._get_state()
log.info('"{}" state is {}'.format(self._vmname, vm_state))
if vm_state == "poweroff":
yield from self.set_vcpus(self.vcpus)
yield from self.set_ram(self.ram)
if vm_state in ("poweroff", "saved"):
# start the VM if it is not running
args = [self._vmname]
if self._headless:
args.extend(["--type", "headless"])
yield from self._execute("startvm", args)
elif vm_state == "paused":
args = [self._vmname, "resume"]
yield from self._execute("controlvm", args)
ip_address = "127.0.0.1"
try:
# get a random port on localhost
with socket.socket() as s:
s.bind((ip_address, 0))
api_port = s.getsockname()[1]
except OSError as e:
raise GNS3VMError("Error while getting random port: {}".format(e))
if (yield from self._check_vbox_port_forwarding()):
# delete the GNS3VM NAT port forwarding rule if it exists
log.info("Removing GNS3VM NAT port forwarding rule from interface {}".format(nat_interface_number))
yield from self._execute("controlvm", [self._vmname, "natpf{}".format(nat_interface_number), "delete", "GNS3VM"])
# add a GNS3VM NAT port forwarding rule to redirect 127.0.0.1 with random port to port 3080 in the VM
log.info("Adding GNS3VM NAT port forwarding rule with port {} to interface {}".format(api_port, nat_interface_number))
yield from self._execute("controlvm", [self._vmname, "natpf{}".format(nat_interface_number),
"GNS3VM,tcp,{},{},,3080".format(ip_address, api_port)])
self.ip_address = yield from self._get_ip(hostonly_interface_number, api_port)
self.port = 3080
log.info("GNS3 VM has been started with IP {}".format(self.ip_address))
self.running = True | python | def start(self):
"""
Start the GNS3 VM.
"""
# get a NAT interface number
nat_interface_number = yield from self._look_for_interface("nat")
if nat_interface_number < 0:
raise GNS3VMError("The GNS3 VM: {} must have a NAT interface configured in order to start".format(self.vmname))
hostonly_interface_number = yield from self._look_for_interface("hostonly")
if hostonly_interface_number < 0:
raise GNS3VMError("The GNS3 VM: {} must have a host only interface configured in order to start".format(self.vmname))
vboxnet = yield from self._look_for_vboxnet(hostonly_interface_number)
if vboxnet is None:
raise GNS3VMError("VirtualBox host-only network could not be found for interface {} on GNS3 VM".format(hostonly_interface_number))
if not (yield from self._check_dhcp_server(vboxnet)):
raise GNS3VMError("DHCP must be enabled on VirtualBox host-only network: {} for GNS3 VM".format(vboxnet))
vm_state = yield from self._get_state()
log.info('"{}" state is {}'.format(self._vmname, vm_state))
if vm_state == "poweroff":
yield from self.set_vcpus(self.vcpus)
yield from self.set_ram(self.ram)
if vm_state in ("poweroff", "saved"):
# start the VM if it is not running
args = [self._vmname]
if self._headless:
args.extend(["--type", "headless"])
yield from self._execute("startvm", args)
elif vm_state == "paused":
args = [self._vmname, "resume"]
yield from self._execute("controlvm", args)
ip_address = "127.0.0.1"
try:
# get a random port on localhost
with socket.socket() as s:
s.bind((ip_address, 0))
api_port = s.getsockname()[1]
except OSError as e:
raise GNS3VMError("Error while getting random port: {}".format(e))
if (yield from self._check_vbox_port_forwarding()):
# delete the GNS3VM NAT port forwarding rule if it exists
log.info("Removing GNS3VM NAT port forwarding rule from interface {}".format(nat_interface_number))
yield from self._execute("controlvm", [self._vmname, "natpf{}".format(nat_interface_number), "delete", "GNS3VM"])
# add a GNS3VM NAT port forwarding rule to redirect 127.0.0.1 with random port to port 3080 in the VM
log.info("Adding GNS3VM NAT port forwarding rule with port {} to interface {}".format(api_port, nat_interface_number))
yield from self._execute("controlvm", [self._vmname, "natpf{}".format(nat_interface_number),
"GNS3VM,tcp,{},{},,3080".format(ip_address, api_port)])
self.ip_address = yield from self._get_ip(hostonly_interface_number, api_port)
self.port = 3080
log.info("GNS3 VM has been started with IP {}".format(self.ip_address))
self.running = True | [
"def",
"start",
"(",
"self",
")",
":",
"# get a NAT interface number",
"nat_interface_number",
"=",
"yield",
"from",
"self",
".",
"_look_for_interface",
"(",
"\"nat\"",
")",
"if",
"nat_interface_number",
"<",
"0",
":",
"raise",
"GNS3VMError",
"(",
"\"The GNS3 VM: {}... | Start the GNS3 VM. | [
"Start",
"the",
"GNS3",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/virtualbox_gns3_vm.py#L153-L212 |
226,498 | GNS3/gns3-server | gns3server/controller/gns3vm/virtualbox_gns3_vm.py | VirtualBoxGNS3VM._get_ip | def _get_ip(self, hostonly_interface_number, api_port):
"""
Get the IP from VirtualBox.
Due to VirtualBox limitation the only way is to send request each
second to a GNS3 endpoint in order to get the list of the interfaces and
their IP and after that match it with VirtualBox host only.
"""
remaining_try = 300
while remaining_try > 0:
json_data = None
session = aiohttp.ClientSession()
try:
resp = None
resp = yield from session.get('http://127.0.0.1:{}/v2/compute/network/interfaces'.format(api_port))
except (OSError, aiohttp.ClientError, TimeoutError, asyncio.TimeoutError):
pass
if resp:
if resp.status < 300:
try:
json_data = yield from resp.json()
except ValueError:
pass
resp.close()
session.close()
if json_data:
for interface in json_data:
if "name" in interface and interface["name"] == "eth{}".format(hostonly_interface_number - 1):
if "ip_address" in interface and len(interface["ip_address"]) > 0:
return interface["ip_address"]
remaining_try -= 1
yield from asyncio.sleep(1)
raise GNS3VMError("Could not get the GNS3 VM ip make sure the VM receive an IP from VirtualBox") | python | def _get_ip(self, hostonly_interface_number, api_port):
"""
Get the IP from VirtualBox.
Due to VirtualBox limitation the only way is to send request each
second to a GNS3 endpoint in order to get the list of the interfaces and
their IP and after that match it with VirtualBox host only.
"""
remaining_try = 300
while remaining_try > 0:
json_data = None
session = aiohttp.ClientSession()
try:
resp = None
resp = yield from session.get('http://127.0.0.1:{}/v2/compute/network/interfaces'.format(api_port))
except (OSError, aiohttp.ClientError, TimeoutError, asyncio.TimeoutError):
pass
if resp:
if resp.status < 300:
try:
json_data = yield from resp.json()
except ValueError:
pass
resp.close()
session.close()
if json_data:
for interface in json_data:
if "name" in interface and interface["name"] == "eth{}".format(hostonly_interface_number - 1):
if "ip_address" in interface and len(interface["ip_address"]) > 0:
return interface["ip_address"]
remaining_try -= 1
yield from asyncio.sleep(1)
raise GNS3VMError("Could not get the GNS3 VM ip make sure the VM receive an IP from VirtualBox") | [
"def",
"_get_ip",
"(",
"self",
",",
"hostonly_interface_number",
",",
"api_port",
")",
":",
"remaining_try",
"=",
"300",
"while",
"remaining_try",
">",
"0",
":",
"json_data",
"=",
"None",
"session",
"=",
"aiohttp",
".",
"ClientSession",
"(",
")",
"try",
":",... | Get the IP from VirtualBox.
Due to VirtualBox limitation the only way is to send request each
second to a GNS3 endpoint in order to get the list of the interfaces and
their IP and after that match it with VirtualBox host only. | [
"Get",
"the",
"IP",
"from",
"VirtualBox",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/virtualbox_gns3_vm.py#L215-L250 |
226,499 | GNS3/gns3-server | gns3server/controller/gns3vm/virtualbox_gns3_vm.py | VirtualBoxGNS3VM.stop | def stop(self):
"""
Stops the GNS3 VM.
"""
vm_state = yield from self._get_state()
if vm_state == "poweroff":
self.running = False
return
yield from self._execute("controlvm", [self._vmname, "acpipowerbutton"], timeout=3)
trial = 120
while True:
try:
vm_state = yield from self._get_state()
# During a small amount of time the command will fail
except GNS3VMError:
vm_state = "running"
if vm_state == "poweroff":
break
trial -= 1
if trial == 0:
yield from self._execute("controlvm", [self._vmname, "poweroff"], timeout=3)
break
yield from asyncio.sleep(1)
log.info("GNS3 VM has been stopped")
self.running = False | python | def stop(self):
"""
Stops the GNS3 VM.
"""
vm_state = yield from self._get_state()
if vm_state == "poweroff":
self.running = False
return
yield from self._execute("controlvm", [self._vmname, "acpipowerbutton"], timeout=3)
trial = 120
while True:
try:
vm_state = yield from self._get_state()
# During a small amount of time the command will fail
except GNS3VMError:
vm_state = "running"
if vm_state == "poweroff":
break
trial -= 1
if trial == 0:
yield from self._execute("controlvm", [self._vmname, "poweroff"], timeout=3)
break
yield from asyncio.sleep(1)
log.info("GNS3 VM has been stopped")
self.running = False | [
"def",
"stop",
"(",
"self",
")",
":",
"vm_state",
"=",
"yield",
"from",
"self",
".",
"_get_state",
"(",
")",
"if",
"vm_state",
"==",
"\"poweroff\"",
":",
"self",
".",
"running",
"=",
"False",
"return",
"yield",
"from",
"self",
".",
"_execute",
"(",
"\"... | Stops the GNS3 VM. | [
"Stops",
"the",
"GNS3",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/virtualbox_gns3_vm.py#L263-L290 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.