repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
GNS3/gns3-server | gns3server/controller/__init__.py | Controller.add_project | def add_project(self, project_id=None, name=None, **kwargs):
"""
Creates a project or returns an existing project
:param project_id: Project ID
:param name: Project name
:param kwargs: See the documentation of Project
"""
if project_id not in self._projects:
for project in self._projects.values():
if name and project.name == name:
raise aiohttp.web.HTTPConflict(text='Project name "{}" already exists'.format(name))
project = Project(project_id=project_id, controller=self, name=name, **kwargs)
self._projects[project.id] = project
return self._projects[project.id]
return self._projects[project_id] | python | def add_project(self, project_id=None, name=None, **kwargs):
"""
Creates a project or returns an existing project
:param project_id: Project ID
:param name: Project name
:param kwargs: See the documentation of Project
"""
if project_id not in self._projects:
for project in self._projects.values():
if name and project.name == name:
raise aiohttp.web.HTTPConflict(text='Project name "{}" already exists'.format(name))
project = Project(project_id=project_id, controller=self, name=name, **kwargs)
self._projects[project.id] = project
return self._projects[project.id]
return self._projects[project_id] | [
"def",
"add_project",
"(",
"self",
",",
"project_id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"project_id",
"not",
"in",
"self",
".",
"_projects",
":",
"for",
"project",
"in",
"self",
".",
"_projects",
".",
"va... | Creates a project or returns an existing project
:param project_id: Project ID
:param name: Project name
:param kwargs: See the documentation of Project | [
"Creates",
"a",
"project",
"or",
"returns",
"an",
"existing",
"project"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/__init__.py#L515-L531 | train | 221,500 |
GNS3/gns3-server | gns3server/controller/__init__.py | Controller.load_project | def load_project(self, path, load=True):
"""
Load a project from a .gns3
:param path: Path of the .gns3
:param load: Load the topology
"""
topo_data = load_topology(path)
topo_data.pop("topology")
topo_data.pop("version")
topo_data.pop("revision")
topo_data.pop("type")
if topo_data["project_id"] in self._projects:
project = self._projects[topo_data["project_id"]]
else:
project = yield from self.add_project(path=os.path.dirname(path), status="closed", filename=os.path.basename(path), **topo_data)
if load or project.auto_open:
yield from project.open()
return project | python | def load_project(self, path, load=True):
"""
Load a project from a .gns3
:param path: Path of the .gns3
:param load: Load the topology
"""
topo_data = load_topology(path)
topo_data.pop("topology")
topo_data.pop("version")
topo_data.pop("revision")
topo_data.pop("type")
if topo_data["project_id"] in self._projects:
project = self._projects[topo_data["project_id"]]
else:
project = yield from self.add_project(path=os.path.dirname(path), status="closed", filename=os.path.basename(path), **topo_data)
if load or project.auto_open:
yield from project.open()
return project | [
"def",
"load_project",
"(",
"self",
",",
"path",
",",
"load",
"=",
"True",
")",
":",
"topo_data",
"=",
"load_topology",
"(",
"path",
")",
"topo_data",
".",
"pop",
"(",
"\"topology\"",
")",
"topo_data",
".",
"pop",
"(",
"\"version\"",
")",
"topo_data",
".... | Load a project from a .gns3
:param path: Path of the .gns3
:param load: Load the topology | [
"Load",
"a",
"project",
"from",
"a",
".",
"gns3"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/__init__.py#L558-L577 | train | 221,501 |
GNS3/gns3-server | gns3server/controller/__init__.py | Controller._project_auto_open | def _project_auto_open(self):
"""
Auto open the project with auto open enable
"""
for project in self._projects.values():
if project.auto_open:
yield from project.open() | python | def _project_auto_open(self):
"""
Auto open the project with auto open enable
"""
for project in self._projects.values():
if project.auto_open:
yield from project.open() | [
"def",
"_project_auto_open",
"(",
"self",
")",
":",
"for",
"project",
"in",
"self",
".",
"_projects",
".",
"values",
"(",
")",
":",
"if",
"project",
".",
"auto_open",
":",
"yield",
"from",
"project",
".",
"open",
"(",
")"
] | Auto open the project with auto open enable | [
"Auto",
"open",
"the",
"project",
"with",
"auto",
"open",
"enable"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/__init__.py#L580-L586 | train | 221,502 |
GNS3/gns3-server | gns3server/controller/__init__.py | Controller.get_free_project_name | def get_free_project_name(self, base_name):
"""
Generate a free project name base on the base name
"""
names = [p.name for p in self._projects.values()]
if base_name not in names:
return base_name
i = 1
projects_path = self.projects_directory()
while True:
new_name = "{}-{}".format(base_name, i)
if new_name not in names and not os.path.exists(os.path.join(projects_path, new_name)):
break
i += 1
if i > 1000000:
raise aiohttp.web.HTTPConflict(text="A project name could not be allocated (node limit reached?)")
return new_name | python | def get_free_project_name(self, base_name):
"""
Generate a free project name base on the base name
"""
names = [p.name for p in self._projects.values()]
if base_name not in names:
return base_name
i = 1
projects_path = self.projects_directory()
while True:
new_name = "{}-{}".format(base_name, i)
if new_name not in names and not os.path.exists(os.path.join(projects_path, new_name)):
break
i += 1
if i > 1000000:
raise aiohttp.web.HTTPConflict(text="A project name could not be allocated (node limit reached?)")
return new_name | [
"def",
"get_free_project_name",
"(",
"self",
",",
"base_name",
")",
":",
"names",
"=",
"[",
"p",
".",
"name",
"for",
"p",
"in",
"self",
".",
"_projects",
".",
"values",
"(",
")",
"]",
"if",
"base_name",
"not",
"in",
"names",
":",
"return",
"base_name",... | Generate a free project name base on the base name | [
"Generate",
"a",
"free",
"project",
"name",
"base",
"on",
"the",
"base",
"name"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/__init__.py#L588-L606 | train | 221,503 |
GNS3/gns3-server | gns3server/controller/__init__.py | Controller.instance | def instance():
"""
Singleton to return only on instance of Controller.
:returns: instance of Controller
"""
if not hasattr(Controller, '_instance') or Controller._instance is None:
Controller._instance = Controller()
return Controller._instance | python | def instance():
"""
Singleton to return only on instance of Controller.
:returns: instance of Controller
"""
if not hasattr(Controller, '_instance') or Controller._instance is None:
Controller._instance = Controller()
return Controller._instance | [
"def",
"instance",
"(",
")",
":",
"if",
"not",
"hasattr",
"(",
"Controller",
",",
"'_instance'",
")",
"or",
"Controller",
".",
"_instance",
"is",
"None",
":",
"Controller",
".",
"_instance",
"=",
"Controller",
"(",
")",
"return",
"Controller",
".",
"_insta... | Singleton to return only on instance of Controller.
:returns: instance of Controller | [
"Singleton",
"to",
"return",
"only",
"on",
"instance",
"of",
"Controller",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/__init__.py#L634-L643 | train | 221,504 |
GNS3/gns3-server | gns3server/controller/__init__.py | Controller.autoidlepc | def autoidlepc(self, compute_id, platform, image, ram):
"""
Compute and IDLE PC value for an image
:param compute_id: ID of the compute where the idlepc operation need to run
:param platform: Platform type
:param image: Image to use
:param ram: amount of RAM to use
"""
compute = self.get_compute(compute_id)
for project in list(self._projects.values()):
if project.name == "AUTOIDLEPC":
yield from project.delete()
self.remove_project(project)
project = yield from self.add_project(name="AUTOIDLEPC")
node = yield from project.add_node(compute, "AUTOIDLEPC", str(uuid.uuid4()), node_type="dynamips", platform=platform, image=image, ram=ram)
res = yield from node.dynamips_auto_idlepc()
yield from project.delete()
self.remove_project(project)
return res | python | def autoidlepc(self, compute_id, platform, image, ram):
"""
Compute and IDLE PC value for an image
:param compute_id: ID of the compute where the idlepc operation need to run
:param platform: Platform type
:param image: Image to use
:param ram: amount of RAM to use
"""
compute = self.get_compute(compute_id)
for project in list(self._projects.values()):
if project.name == "AUTOIDLEPC":
yield from project.delete()
self.remove_project(project)
project = yield from self.add_project(name="AUTOIDLEPC")
node = yield from project.add_node(compute, "AUTOIDLEPC", str(uuid.uuid4()), node_type="dynamips", platform=platform, image=image, ram=ram)
res = yield from node.dynamips_auto_idlepc()
yield from project.delete()
self.remove_project(project)
return res | [
"def",
"autoidlepc",
"(",
"self",
",",
"compute_id",
",",
"platform",
",",
"image",
",",
"ram",
")",
":",
"compute",
"=",
"self",
".",
"get_compute",
"(",
"compute_id",
")",
"for",
"project",
"in",
"list",
"(",
"self",
".",
"_projects",
".",
"values",
... | Compute and IDLE PC value for an image
:param compute_id: ID of the compute where the idlepc operation need to run
:param platform: Platform type
:param image: Image to use
:param ram: amount of RAM to use | [
"Compute",
"and",
"IDLE",
"PC",
"value",
"for",
"an",
"image"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/__init__.py#L646-L665 | train | 221,505 |
GNS3/gns3-server | gns3server/compute/virtualbox/virtualbox_vm.py | VirtualBoxVM._control_vm | def _control_vm(self, params):
"""
Change setting in this VM when running.
:param params: params to use with sub-command controlvm
:returns: result of the command.
"""
args = shlex.split(params)
result = yield from self.manager.execute("controlvm", [self._vmname] + args)
return result | python | def _control_vm(self, params):
"""
Change setting in this VM when running.
:param params: params to use with sub-command controlvm
:returns: result of the command.
"""
args = shlex.split(params)
result = yield from self.manager.execute("controlvm", [self._vmname] + args)
return result | [
"def",
"_control_vm",
"(",
"self",
",",
"params",
")",
":",
"args",
"=",
"shlex",
".",
"split",
"(",
"params",
")",
"result",
"=",
"yield",
"from",
"self",
".",
"manager",
".",
"execute",
"(",
"\"controlvm\"",
",",
"[",
"self",
".",
"_vmname",
"]",
"... | Change setting in this VM when running.
:param params: params to use with sub-command controlvm
:returns: result of the command. | [
"Change",
"setting",
"in",
"this",
"VM",
"when",
"running",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/virtualbox/virtualbox_vm.py#L129-L140 | train | 221,506 |
GNS3/gns3-server | gns3server/compute/virtualbox/virtualbox_vm.py | VirtualBoxVM._patch_vm_uuid | def _patch_vm_uuid(self):
"""
Fix the VM uuid in the case of linked clone
"""
if os.path.exists(self._linked_vbox_file()):
try:
tree = ET.parse(self._linked_vbox_file())
except ET.ParseError:
raise VirtualBoxError("Cannot modify VirtualBox linked nodes file. "
"File {} is corrupted.".format(self._linked_vbox_file()))
machine = tree.getroot().find("{http://www.virtualbox.org/}Machine")
if machine is not None and machine.get("uuid") != "{" + self.id + "}":
for image in tree.getroot().findall("{http://www.virtualbox.org/}Image"):
currentSnapshot = machine.get("currentSnapshot")
if currentSnapshot:
newSnapshot = re.sub("\{.*\}", "{" + str(uuid.uuid4()) + "}", currentSnapshot)
shutil.move(os.path.join(self.working_dir, self._vmname, "Snapshots", currentSnapshot) + ".vdi",
os.path.join(self.working_dir, self._vmname, "Snapshots", newSnapshot) + ".vdi")
image.set("uuid", newSnapshot)
machine.set("uuid", "{" + self.id + "}")
tree.write(self._linked_vbox_file()) | python | def _patch_vm_uuid(self):
"""
Fix the VM uuid in the case of linked clone
"""
if os.path.exists(self._linked_vbox_file()):
try:
tree = ET.parse(self._linked_vbox_file())
except ET.ParseError:
raise VirtualBoxError("Cannot modify VirtualBox linked nodes file. "
"File {} is corrupted.".format(self._linked_vbox_file()))
machine = tree.getroot().find("{http://www.virtualbox.org/}Machine")
if machine is not None and machine.get("uuid") != "{" + self.id + "}":
for image in tree.getroot().findall("{http://www.virtualbox.org/}Image"):
currentSnapshot = machine.get("currentSnapshot")
if currentSnapshot:
newSnapshot = re.sub("\{.*\}", "{" + str(uuid.uuid4()) + "}", currentSnapshot)
shutil.move(os.path.join(self.working_dir, self._vmname, "Snapshots", currentSnapshot) + ".vdi",
os.path.join(self.working_dir, self._vmname, "Snapshots", newSnapshot) + ".vdi")
image.set("uuid", newSnapshot)
machine.set("uuid", "{" + self.id + "}")
tree.write(self._linked_vbox_file()) | [
"def",
"_patch_vm_uuid",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_linked_vbox_file",
"(",
")",
")",
":",
"try",
":",
"tree",
"=",
"ET",
".",
"parse",
"(",
"self",
".",
"_linked_vbox_file",
"(",
")",
")",
"e... | Fix the VM uuid in the case of linked clone | [
"Fix",
"the",
"VM",
"uuid",
"in",
"the",
"case",
"of",
"linked",
"clone"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/virtualbox/virtualbox_vm.py#L210-L233 | train | 221,507 |
GNS3/gns3-server | gns3server/compute/virtualbox/virtualbox_vm.py | VirtualBoxVM.start | def start(self):
"""
Starts this VirtualBox VM.
"""
if self.status == "started":
return
# resume the VM if it is paused
vm_state = yield from self._get_vm_state()
if vm_state == "paused":
yield from self.resume()
return
# VM must be powered off to start it
if vm_state != "poweroff":
raise VirtualBoxError("VirtualBox VM not powered off")
yield from self._set_network_options()
yield from self._set_serial_console()
# check if there is enough RAM to run
self.check_available_ram(self.ram)
args = [self._vmname]
if self._headless:
args.extend(["--type", "headless"])
result = yield from self.manager.execute("startvm", args)
self.status = "started"
log.info("VirtualBox VM '{name}' [{id}] started".format(name=self.name, id=self.id))
log.debug("Start result: {}".format(result))
# add a guest property to let the VM know about the GNS3 name
yield from self.manager.execute("guestproperty", ["set", self._vmname, "NameInGNS3", self.name])
# add a guest property to let the VM know about the GNS3 project directory
yield from self.manager.execute("guestproperty", ["set", self._vmname, "ProjectDirInGNS3", self.working_dir])
yield from self._start_ubridge()
for adapter_number in range(0, self._adapters):
nio = self._ethernet_adapters[adapter_number].get_nio(0)
if nio:
yield from self.add_ubridge_udp_connection("VBOX-{}-{}".format(self._id, adapter_number),
self._local_udp_tunnels[adapter_number][1],
nio)
yield from self._start_console()
if (yield from self.check_hw_virtualization()):
self._hw_virtualization = True | python | def start(self):
"""
Starts this VirtualBox VM.
"""
if self.status == "started":
return
# resume the VM if it is paused
vm_state = yield from self._get_vm_state()
if vm_state == "paused":
yield from self.resume()
return
# VM must be powered off to start it
if vm_state != "poweroff":
raise VirtualBoxError("VirtualBox VM not powered off")
yield from self._set_network_options()
yield from self._set_serial_console()
# check if there is enough RAM to run
self.check_available_ram(self.ram)
args = [self._vmname]
if self._headless:
args.extend(["--type", "headless"])
result = yield from self.manager.execute("startvm", args)
self.status = "started"
log.info("VirtualBox VM '{name}' [{id}] started".format(name=self.name, id=self.id))
log.debug("Start result: {}".format(result))
# add a guest property to let the VM know about the GNS3 name
yield from self.manager.execute("guestproperty", ["set", self._vmname, "NameInGNS3", self.name])
# add a guest property to let the VM know about the GNS3 project directory
yield from self.manager.execute("guestproperty", ["set", self._vmname, "ProjectDirInGNS3", self.working_dir])
yield from self._start_ubridge()
for adapter_number in range(0, self._adapters):
nio = self._ethernet_adapters[adapter_number].get_nio(0)
if nio:
yield from self.add_ubridge_udp_connection("VBOX-{}-{}".format(self._id, adapter_number),
self._local_udp_tunnels[adapter_number][1],
nio)
yield from self._start_console()
if (yield from self.check_hw_virtualization()):
self._hw_virtualization = True | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"status",
"==",
"\"started\"",
":",
"return",
"# resume the VM if it is paused",
"vm_state",
"=",
"yield",
"from",
"self",
".",
"_get_vm_state",
"(",
")",
"if",
"vm_state",
"==",
"\"paused\"",
":",
"y... | Starts this VirtualBox VM. | [
"Starts",
"this",
"VirtualBox",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/virtualbox/virtualbox_vm.py#L249-L297 | train | 221,508 |
GNS3/gns3-server | gns3server/compute/virtualbox/virtualbox_vm.py | VirtualBoxVM.stop | def stop(self):
"""
Stops this VirtualBox VM.
"""
self._hw_virtualization = False
yield from self._stop_ubridge()
yield from self._stop_remote_console()
vm_state = yield from self._get_vm_state()
if vm_state == "running" or vm_state == "paused" or vm_state == "stuck":
if self.acpi_shutdown:
# use ACPI to shutdown the VM
result = yield from self._control_vm("acpipowerbutton")
trial = 0
while True:
vm_state = yield from self._get_vm_state()
if vm_state == "poweroff":
break
yield from asyncio.sleep(1)
trial += 1
if trial >= 120:
yield from self._control_vm("poweroff")
break
self.status = "stopped"
log.debug("ACPI shutdown result: {}".format(result))
else:
# power off the VM
result = yield from self._control_vm("poweroff")
self.status = "stopped"
log.debug("Stop result: {}".format(result))
log.info("VirtualBox VM '{name}' [{id}] stopped".format(name=self.name, id=self.id))
yield from asyncio.sleep(0.5) # give some time for VirtualBox to unlock the VM
try:
# deactivate the first serial port
yield from self._modify_vm("--uart1 off")
except VirtualBoxError as e:
log.warn("Could not deactivate the first serial port: {}".format(e))
for adapter_number in range(0, self._adapters):
nio = self._ethernet_adapters[adapter_number].get_nio(0)
if nio:
yield from self._modify_vm("--nictrace{} off".format(adapter_number + 1))
yield from self._modify_vm("--cableconnected{} off".format(adapter_number + 1))
yield from self._modify_vm("--nic{} null".format(adapter_number + 1))
yield from super().stop() | python | def stop(self):
"""
Stops this VirtualBox VM.
"""
self._hw_virtualization = False
yield from self._stop_ubridge()
yield from self._stop_remote_console()
vm_state = yield from self._get_vm_state()
if vm_state == "running" or vm_state == "paused" or vm_state == "stuck":
if self.acpi_shutdown:
# use ACPI to shutdown the VM
result = yield from self._control_vm("acpipowerbutton")
trial = 0
while True:
vm_state = yield from self._get_vm_state()
if vm_state == "poweroff":
break
yield from asyncio.sleep(1)
trial += 1
if trial >= 120:
yield from self._control_vm("poweroff")
break
self.status = "stopped"
log.debug("ACPI shutdown result: {}".format(result))
else:
# power off the VM
result = yield from self._control_vm("poweroff")
self.status = "stopped"
log.debug("Stop result: {}".format(result))
log.info("VirtualBox VM '{name}' [{id}] stopped".format(name=self.name, id=self.id))
yield from asyncio.sleep(0.5) # give some time for VirtualBox to unlock the VM
try:
# deactivate the first serial port
yield from self._modify_vm("--uart1 off")
except VirtualBoxError as e:
log.warn("Could not deactivate the first serial port: {}".format(e))
for adapter_number in range(0, self._adapters):
nio = self._ethernet_adapters[adapter_number].get_nio(0)
if nio:
yield from self._modify_vm("--nictrace{} off".format(adapter_number + 1))
yield from self._modify_vm("--cableconnected{} off".format(adapter_number + 1))
yield from self._modify_vm("--nic{} null".format(adapter_number + 1))
yield from super().stop() | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"_hw_virtualization",
"=",
"False",
"yield",
"from",
"self",
".",
"_stop_ubridge",
"(",
")",
"yield",
"from",
"self",
".",
"_stop_remote_console",
"(",
")",
"vm_state",
"=",
"yield",
"from",
"self",
".",
... | Stops this VirtualBox VM. | [
"Stops",
"this",
"VirtualBox",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/virtualbox/virtualbox_vm.py#L300-L345 | train | 221,509 |
GNS3/gns3-server | gns3server/compute/virtualbox/virtualbox_vm.py | VirtualBoxVM.suspend | def suspend(self):
"""
Suspends this VirtualBox VM.
"""
vm_state = yield from self._get_vm_state()
if vm_state == "running":
yield from self._control_vm("pause")
self.status = "suspended"
log.info("VirtualBox VM '{name}' [{id}] suspended".format(name=self.name, id=self.id))
else:
log.warn("VirtualBox VM '{name}' [{id}] cannot be suspended, current state: {state}".format(name=self.name,
id=self.id,
state=vm_state)) | python | def suspend(self):
"""
Suspends this VirtualBox VM.
"""
vm_state = yield from self._get_vm_state()
if vm_state == "running":
yield from self._control_vm("pause")
self.status = "suspended"
log.info("VirtualBox VM '{name}' [{id}] suspended".format(name=self.name, id=self.id))
else:
log.warn("VirtualBox VM '{name}' [{id}] cannot be suspended, current state: {state}".format(name=self.name,
id=self.id,
state=vm_state)) | [
"def",
"suspend",
"(",
"self",
")",
":",
"vm_state",
"=",
"yield",
"from",
"self",
".",
"_get_vm_state",
"(",
")",
"if",
"vm_state",
"==",
"\"running\"",
":",
"yield",
"from",
"self",
".",
"_control_vm",
"(",
"\"pause\"",
")",
"self",
".",
"status",
"=",... | Suspends this VirtualBox VM. | [
"Suspends",
"this",
"VirtualBox",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/virtualbox/virtualbox_vm.py#L348-L361 | train | 221,510 |
GNS3/gns3-server | gns3server/compute/virtualbox/virtualbox_vm.py | VirtualBoxVM.resume | def resume(self):
"""
Resumes this VirtualBox VM.
"""
yield from self._control_vm("resume")
self.status = "started"
log.info("VirtualBox VM '{name}' [{id}] resumed".format(name=self.name, id=self.id)) | python | def resume(self):
"""
Resumes this VirtualBox VM.
"""
yield from self._control_vm("resume")
self.status = "started"
log.info("VirtualBox VM '{name}' [{id}] resumed".format(name=self.name, id=self.id)) | [
"def",
"resume",
"(",
"self",
")",
":",
"yield",
"from",
"self",
".",
"_control_vm",
"(",
"\"resume\"",
")",
"self",
".",
"status",
"=",
"\"started\"",
"log",
".",
"info",
"(",
"\"VirtualBox VM '{name}' [{id}] resumed\"",
".",
"format",
"(",
"name",
"=",
"se... | Resumes this VirtualBox VM. | [
"Resumes",
"this",
"VirtualBox",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/virtualbox/virtualbox_vm.py#L364-L371 | train | 221,511 |
GNS3/gns3-server | gns3server/compute/virtualbox/virtualbox_vm.py | VirtualBoxVM.reload | def reload(self):
"""
Reloads this VirtualBox VM.
"""
result = yield from self._control_vm("reset")
log.info("VirtualBox VM '{name}' [{id}] reloaded".format(name=self.name, id=self.id))
log.debug("Reload result: {}".format(result)) | python | def reload(self):
"""
Reloads this VirtualBox VM.
"""
result = yield from self._control_vm("reset")
log.info("VirtualBox VM '{name}' [{id}] reloaded".format(name=self.name, id=self.id))
log.debug("Reload result: {}".format(result)) | [
"def",
"reload",
"(",
"self",
")",
":",
"result",
"=",
"yield",
"from",
"self",
".",
"_control_vm",
"(",
"\"reset\"",
")",
"log",
".",
"info",
"(",
"\"VirtualBox VM '{name}' [{id}] reloaded\"",
".",
"format",
"(",
"name",
"=",
"self",
".",
"name",
",",
"id... | Reloads this VirtualBox VM. | [
"Reloads",
"this",
"VirtualBox",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/virtualbox/virtualbox_vm.py#L374-L381 | train | 221,512 |
GNS3/gns3-server | gns3server/compute/virtualbox/virtualbox_vm.py | VirtualBoxVM._reattach_linked_hdds | def _reattach_linked_hdds(self):
"""
Reattach linked cloned hard disks.
"""
hdd_info_file = os.path.join(self.working_dir, self._vmname, "hdd_info.json")
try:
with open(hdd_info_file, "r", encoding="utf-8") as f:
hdd_table = json.load(f)
except (ValueError, OSError) as e:
# The VM has never be started
return
for hdd_info in hdd_table:
hdd_file = os.path.join(self.working_dir, self._vmname, "Snapshots", hdd_info["hdd"])
if os.path.exists(hdd_file):
log.info("VirtualBox VM '{name}' [{id}] attaching HDD {controller} {port} {device} {medium}".format(name=self.name,
id=self.id,
controller=hdd_info["controller"],
port=hdd_info["port"],
device=hdd_info["device"],
medium=hdd_file))
try:
yield from self._storage_attach('--storagectl "{}" --port {} --device {} --type hdd --medium "{}"'.format(hdd_info["controller"],
hdd_info["port"],
hdd_info["device"],
hdd_file))
except VirtualBoxError as e:
log.warn("VirtualBox VM '{name}' [{id}] error reattaching HDD {controller} {port} {device} {medium}: {error}".format(name=self.name,
id=self.id,
controller=hdd_info["controller"],
port=hdd_info["port"],
device=hdd_info["device"],
medium=hdd_file,
error=e))
continue | python | def _reattach_linked_hdds(self):
"""
Reattach linked cloned hard disks.
"""
hdd_info_file = os.path.join(self.working_dir, self._vmname, "hdd_info.json")
try:
with open(hdd_info_file, "r", encoding="utf-8") as f:
hdd_table = json.load(f)
except (ValueError, OSError) as e:
# The VM has never be started
return
for hdd_info in hdd_table:
hdd_file = os.path.join(self.working_dir, self._vmname, "Snapshots", hdd_info["hdd"])
if os.path.exists(hdd_file):
log.info("VirtualBox VM '{name}' [{id}] attaching HDD {controller} {port} {device} {medium}".format(name=self.name,
id=self.id,
controller=hdd_info["controller"],
port=hdd_info["port"],
device=hdd_info["device"],
medium=hdd_file))
try:
yield from self._storage_attach('--storagectl "{}" --port {} --device {} --type hdd --medium "{}"'.format(hdd_info["controller"],
hdd_info["port"],
hdd_info["device"],
hdd_file))
except VirtualBoxError as e:
log.warn("VirtualBox VM '{name}' [{id}] error reattaching HDD {controller} {port} {device} {medium}: {error}".format(name=self.name,
id=self.id,
controller=hdd_info["controller"],
port=hdd_info["port"],
device=hdd_info["device"],
medium=hdd_file,
error=e))
continue | [
"def",
"_reattach_linked_hdds",
"(",
"self",
")",
":",
"hdd_info_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"working_dir",
",",
"self",
".",
"_vmname",
",",
"\"hdd_info.json\"",
")",
"try",
":",
"with",
"open",
"(",
"hdd_info_file",
",",... | Reattach linked cloned hard disks. | [
"Reattach",
"linked",
"cloned",
"hard",
"disks",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/virtualbox/virtualbox_vm.py#L398-L435 | train | 221,513 |
GNS3/gns3-server | gns3server/compute/virtualbox/virtualbox_vm.py | VirtualBoxVM.save_linked_hdds_info | def save_linked_hdds_info(self):
"""
Save linked cloned hard disks information.
:returns: disk table information
"""
hdd_table = []
if self.linked_clone:
if os.path.exists(self.working_dir):
hdd_files = yield from self._get_all_hdd_files()
vm_info = yield from self._get_vm_info()
for entry, value in vm_info.items():
match = re.search("^([\s\w]+)\-(\d)\-(\d)$", entry) # match Controller-PortNumber-DeviceNumber entry
if match:
controller = match.group(1)
port = match.group(2)
device = match.group(3)
if value in hdd_files and os.path.exists(os.path.join(self.working_dir, self._vmname, "Snapshots", os.path.basename(value))):
log.info("VirtualBox VM '{name}' [{id}] detaching HDD {controller} {port} {device}".format(name=self.name,
id=self.id,
controller=controller,
port=port,
device=device))
hdd_table.append(
{
"hdd": os.path.basename(value),
"controller": controller,
"port": port,
"device": device,
}
)
if hdd_table:
try:
hdd_info_file = os.path.join(self.working_dir, self._vmname, "hdd_info.json")
with open(hdd_info_file, "w", encoding="utf-8") as f:
json.dump(hdd_table, f, indent=4)
except OSError as e:
log.warning("VirtualBox VM '{name}' [{id}] could not write HHD info file: {error}".format(name=self.name,
id=self.id,
error=e.strerror))
return hdd_table | python | def save_linked_hdds_info(self):
"""
Save linked cloned hard disks information.
:returns: disk table information
"""
hdd_table = []
if self.linked_clone:
if os.path.exists(self.working_dir):
hdd_files = yield from self._get_all_hdd_files()
vm_info = yield from self._get_vm_info()
for entry, value in vm_info.items():
match = re.search("^([\s\w]+)\-(\d)\-(\d)$", entry) # match Controller-PortNumber-DeviceNumber entry
if match:
controller = match.group(1)
port = match.group(2)
device = match.group(3)
if value in hdd_files and os.path.exists(os.path.join(self.working_dir, self._vmname, "Snapshots", os.path.basename(value))):
log.info("VirtualBox VM '{name}' [{id}] detaching HDD {controller} {port} {device}".format(name=self.name,
id=self.id,
controller=controller,
port=port,
device=device))
hdd_table.append(
{
"hdd": os.path.basename(value),
"controller": controller,
"port": port,
"device": device,
}
)
if hdd_table:
try:
hdd_info_file = os.path.join(self.working_dir, self._vmname, "hdd_info.json")
with open(hdd_info_file, "w", encoding="utf-8") as f:
json.dump(hdd_table, f, indent=4)
except OSError as e:
log.warning("VirtualBox VM '{name}' [{id}] could not write HHD info file: {error}".format(name=self.name,
id=self.id,
error=e.strerror))
return hdd_table | [
"def",
"save_linked_hdds_info",
"(",
"self",
")",
":",
"hdd_table",
"=",
"[",
"]",
"if",
"self",
".",
"linked_clone",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"working_dir",
")",
":",
"hdd_files",
"=",
"yield",
"from",
"self",
"."... | Save linked cloned hard disks information.
:returns: disk table information | [
"Save",
"linked",
"cloned",
"hard",
"disks",
"information",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/virtualbox/virtualbox_vm.py#L438-L481 | train | 221,514 |
GNS3/gns3-server | gns3server/compute/virtualbox/virtualbox_vm.py | VirtualBoxVM.close | def close(self):
"""
Closes this VirtualBox VM.
"""
if self._closed:
# VM is already closed
return
if not (yield from super().close()):
return False
log.debug("VirtualBox VM '{name}' [{id}] is closing".format(name=self.name, id=self.id))
if self._console:
self._manager.port_manager.release_tcp_port(self._console, self._project)
self._console = None
for adapter in self._ethernet_adapters.values():
if adapter is not None:
for nio in adapter.ports.values():
if nio and isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
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 = {}
self.acpi_shutdown = False
yield from self.stop()
if self.linked_clone:
hdd_table = yield from self.save_linked_hdds_info()
for hdd in hdd_table.copy():
log.info("VirtualBox VM '{name}' [{id}] detaching HDD {controller} {port} {device}".format(name=self.name,
id=self.id,
controller=hdd["controller"],
port=hdd["port"],
device=hdd["device"]))
try:
yield from self._storage_attach('--storagectl "{}" --port {} --device {} --type hdd --medium none'.format(hdd["controller"],
hdd["port"],
hdd["device"]))
except VirtualBoxError as e:
log.warn("VirtualBox VM '{name}' [{id}] error detaching HDD {controller} {port} {device}: {error}".format(name=self.name,
id=self.id,
controller=hdd["controller"],
port=hdd["port"],
device=hdd["device"],
error=e))
continue
log.info("VirtualBox VM '{name}' [{id}] unregistering".format(name=self.name, id=self.id))
yield from self.manager.execute("unregistervm", [self._name])
log.info("VirtualBox VM '{name}' [{id}] closed".format(name=self.name, id=self.id))
self._closed = True | python | def close(self):
"""
Closes this VirtualBox VM.
"""
if self._closed:
# VM is already closed
return
if not (yield from super().close()):
return False
log.debug("VirtualBox VM '{name}' [{id}] is closing".format(name=self.name, id=self.id))
if self._console:
self._manager.port_manager.release_tcp_port(self._console, self._project)
self._console = None
for adapter in self._ethernet_adapters.values():
if adapter is not None:
for nio in adapter.ports.values():
if nio and isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
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 = {}
self.acpi_shutdown = False
yield from self.stop()
if self.linked_clone:
hdd_table = yield from self.save_linked_hdds_info()
for hdd in hdd_table.copy():
log.info("VirtualBox VM '{name}' [{id}] detaching HDD {controller} {port} {device}".format(name=self.name,
id=self.id,
controller=hdd["controller"],
port=hdd["port"],
device=hdd["device"]))
try:
yield from self._storage_attach('--storagectl "{}" --port {} --device {} --type hdd --medium none'.format(hdd["controller"],
hdd["port"],
hdd["device"]))
except VirtualBoxError as e:
log.warn("VirtualBox VM '{name}' [{id}] error detaching HDD {controller} {port} {device}: {error}".format(name=self.name,
id=self.id,
controller=hdd["controller"],
port=hdd["port"],
device=hdd["device"],
error=e))
continue
log.info("VirtualBox VM '{name}' [{id}] unregistering".format(name=self.name, id=self.id))
yield from self.manager.execute("unregistervm", [self._name])
log.info("VirtualBox VM '{name}' [{id}] closed".format(name=self.name, id=self.id))
self._closed = True | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_closed",
":",
"# VM is already closed",
"return",
"if",
"not",
"(",
"yield",
"from",
"super",
"(",
")",
".",
"close",
"(",
")",
")",
":",
"return",
"False",
"log",
".",
"debug",
"(",
"\"Virt... | Closes this VirtualBox VM. | [
"Closes",
"this",
"VirtualBox",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/virtualbox/virtualbox_vm.py#L484-L540 | train | 221,515 |
GNS3/gns3-server | gns3server/compute/virtualbox/virtualbox_vm.py | VirtualBoxVM.set_ram | def set_ram(self, ram):
"""
Set the amount of RAM allocated to this VirtualBox VM.
:param ram: amount RAM in MB (integer)
"""
if ram == 0:
return
yield from self._modify_vm('--memory {}'.format(ram))
log.info("VirtualBox VM '{name}' [{id}] has set amount of RAM to {ram}".format(name=self.name, id=self.id, ram=ram))
self._ram = ram | python | def set_ram(self, ram):
"""
Set the amount of RAM allocated to this VirtualBox VM.
:param ram: amount RAM in MB (integer)
"""
if ram == 0:
return
yield from self._modify_vm('--memory {}'.format(ram))
log.info("VirtualBox VM '{name}' [{id}] has set amount of RAM to {ram}".format(name=self.name, id=self.id, ram=ram))
self._ram = ram | [
"def",
"set_ram",
"(",
"self",
",",
"ram",
")",
":",
"if",
"ram",
"==",
"0",
":",
"return",
"yield",
"from",
"self",
".",
"_modify_vm",
"(",
"'--memory {}'",
".",
"format",
"(",
"ram",
")",
")",
"log",
".",
"info",
"(",
"\"VirtualBox VM '{name}' [{id}] h... | Set the amount of RAM allocated to this VirtualBox VM.
:param ram: amount RAM in MB (integer) | [
"Set",
"the",
"amount",
"of",
"RAM",
"allocated",
"to",
"this",
"VirtualBox",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/virtualbox/virtualbox_vm.py#L601-L614 | train | 221,516 |
GNS3/gns3-server | gns3server/compute/virtualbox/virtualbox_vm.py | VirtualBoxVM.set_vmname | def set_vmname(self, vmname):
"""
Renames the VirtualBox VM.
:param vmname: VirtualBox VM name
"""
if vmname == self._vmname:
return
if self.linked_clone:
if self.status == "started":
raise VirtualBoxError("You can't change the name of running VM {}".format(self._name))
# We can't rename a VM to name that already exists
vms = yield from self.manager.list_vms(allow_clone=True)
if vmname in [vm["vmname"] for vm in vms]:
raise VirtualBoxError("You can't change the name to {} it's already use in VirtualBox".format(vmname))
yield from self._modify_vm('--name "{}"'.format(vmname))
log.info("VirtualBox VM '{name}' [{id}] has set the VM name to '{vmname}'".format(name=self.name, id=self.id, vmname=vmname))
self._vmname = vmname | python | def set_vmname(self, vmname):
"""
Renames the VirtualBox VM.
:param vmname: VirtualBox VM name
"""
if vmname == self._vmname:
return
if self.linked_clone:
if self.status == "started":
raise VirtualBoxError("You can't change the name of running VM {}".format(self._name))
# We can't rename a VM to name that already exists
vms = yield from self.manager.list_vms(allow_clone=True)
if vmname in [vm["vmname"] for vm in vms]:
raise VirtualBoxError("You can't change the name to {} it's already use in VirtualBox".format(vmname))
yield from self._modify_vm('--name "{}"'.format(vmname))
log.info("VirtualBox VM '{name}' [{id}] has set the VM name to '{vmname}'".format(name=self.name, id=self.id, vmname=vmname))
self._vmname = vmname | [
"def",
"set_vmname",
"(",
"self",
",",
"vmname",
")",
":",
"if",
"vmname",
"==",
"self",
".",
"_vmname",
":",
"return",
"if",
"self",
".",
"linked_clone",
":",
"if",
"self",
".",
"status",
"==",
"\"started\"",
":",
"raise",
"VirtualBoxError",
"(",
"\"You... | Renames the VirtualBox VM.
:param vmname: VirtualBox VM name | [
"Renames",
"the",
"VirtualBox",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/virtualbox/virtualbox_vm.py#L627-L647 | train | 221,517 |
GNS3/gns3-server | gns3server/compute/virtualbox/virtualbox_vm.py | VirtualBoxVM.set_adapters | def set_adapters(self, adapters):
"""
Sets the number of Ethernet adapters for this VirtualBox VM instance.
:param adapters: number of adapters
"""
# check for the maximum adapters supported by the VM
vm_info = yield from self._get_vm_info()
chipset = "piix3" # default chipset for VirtualBox VMs
self._maximum_adapters = 8 # default maximum network adapter count for PIIX3 chipset
if "chipset" in vm_info:
chipset = vm_info["chipset"]
max_adapter_string = "Maximum {} Network Adapter count".format(chipset.upper())
if max_adapter_string in self._system_properties:
try:
self._maximum_adapters = int(self._system_properties[max_adapter_string])
except ValueError:
log.error("Could not convert system property to integer: {} = {}".format(max_adapter_string, self._system_properties[max_adapter_string]))
else:
log.warning("Could not find system property '{}' for chipset {}".format(max_adapter_string, chipset))
log.info("VirtualBox VM '{name}' [{id}] can have a maximum of {max} network adapters for chipset {chipset}".format(name=self.name,
id=self.id,
max=self._maximum_adapters,
chipset=chipset.upper()))
if adapters > self._maximum_adapters:
raise VirtualBoxError("The configured {} chipset limits the VM to {} network adapters. The chipset can be changed outside GNS3 in the VirtualBox VM settings.".format(chipset.upper(),
self._maximum_adapters))
self._ethernet_adapters.clear()
for adapter_number in range(0, adapters):
self._ethernet_adapters[adapter_number] = EthernetAdapter()
self._adapters = len(self._ethernet_adapters)
log.info("VirtualBox VM '{name}' [{id}] has changed the number of Ethernet adapters to {adapters}".format(name=self.name,
id=self.id,
adapters=adapters)) | python | def set_adapters(self, adapters):
"""
Sets the number of Ethernet adapters for this VirtualBox VM instance.
:param adapters: number of adapters
"""
# check for the maximum adapters supported by the VM
vm_info = yield from self._get_vm_info()
chipset = "piix3" # default chipset for VirtualBox VMs
self._maximum_adapters = 8 # default maximum network adapter count for PIIX3 chipset
if "chipset" in vm_info:
chipset = vm_info["chipset"]
max_adapter_string = "Maximum {} Network Adapter count".format(chipset.upper())
if max_adapter_string in self._system_properties:
try:
self._maximum_adapters = int(self._system_properties[max_adapter_string])
except ValueError:
log.error("Could not convert system property to integer: {} = {}".format(max_adapter_string, self._system_properties[max_adapter_string]))
else:
log.warning("Could not find system property '{}' for chipset {}".format(max_adapter_string, chipset))
log.info("VirtualBox VM '{name}' [{id}] can have a maximum of {max} network adapters for chipset {chipset}".format(name=self.name,
id=self.id,
max=self._maximum_adapters,
chipset=chipset.upper()))
if adapters > self._maximum_adapters:
raise VirtualBoxError("The configured {} chipset limits the VM to {} network adapters. The chipset can be changed outside GNS3 in the VirtualBox VM settings.".format(chipset.upper(),
self._maximum_adapters))
self._ethernet_adapters.clear()
for adapter_number in range(0, adapters):
self._ethernet_adapters[adapter_number] = EthernetAdapter()
self._adapters = len(self._ethernet_adapters)
log.info("VirtualBox VM '{name}' [{id}] has changed the number of Ethernet adapters to {adapters}".format(name=self.name,
id=self.id,
adapters=adapters)) | [
"def",
"set_adapters",
"(",
"self",
",",
"adapters",
")",
":",
"# check for the maximum adapters supported by the VM",
"vm_info",
"=",
"yield",
"from",
"self",
".",
"_get_vm_info",
"(",
")",
"chipset",
"=",
"\"piix3\"",
"# default chipset for VirtualBox VMs",
"self",
".... | Sets the number of Ethernet adapters for this VirtualBox VM instance.
:param adapters: number of adapters | [
"Sets",
"the",
"number",
"of",
"Ethernet",
"adapters",
"for",
"this",
"VirtualBox",
"VM",
"instance",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/virtualbox/virtualbox_vm.py#L660-L697 | train | 221,518 |
GNS3/gns3-server | gns3server/compute/virtualbox/virtualbox_vm.py | VirtualBoxVM._get_vm_info | def _get_vm_info(self):
"""
Returns this VM info.
:returns: dict of info
"""
vm_info = {}
results = yield from self.manager.execute("showvminfo", [self._vmname, "--machinereadable"])
for info in results:
try:
name, value = info.split('=', 1)
except ValueError:
continue
vm_info[name.strip('"')] = value.strip('"')
return vm_info | python | def _get_vm_info(self):
"""
Returns this VM info.
:returns: dict of info
"""
vm_info = {}
results = yield from self.manager.execute("showvminfo", [self._vmname, "--machinereadable"])
for info in results:
try:
name, value = info.split('=', 1)
except ValueError:
continue
vm_info[name.strip('"')] = value.strip('"')
return vm_info | [
"def",
"_get_vm_info",
"(",
"self",
")",
":",
"vm_info",
"=",
"{",
"}",
"results",
"=",
"yield",
"from",
"self",
".",
"manager",
".",
"execute",
"(",
"\"showvminfo\"",
",",
"[",
"self",
".",
"_vmname",
",",
"\"--machinereadable\"",
"]",
")",
"for",
"info... | Returns this VM info.
:returns: dict of info | [
"Returns",
"this",
"VM",
"info",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/virtualbox/virtualbox_vm.py#L747-L762 | train | 221,519 |
GNS3/gns3-server | gns3server/compute/virtualbox/virtualbox_vm.py | VirtualBoxVM._storage_attach | def _storage_attach(self, params):
"""
Change storage medium in this VM.
:param params: params to use with sub-command storageattach
"""
args = shlex.split(params)
yield from self.manager.execute("storageattach", [self._vmname] + args) | python | def _storage_attach(self, params):
"""
Change storage medium in this VM.
:param params: params to use with sub-command storageattach
"""
args = shlex.split(params)
yield from self.manager.execute("storageattach", [self._vmname] + args) | [
"def",
"_storage_attach",
"(",
"self",
",",
"params",
")",
":",
"args",
"=",
"shlex",
".",
"split",
"(",
"params",
")",
"yield",
"from",
"self",
".",
"manager",
".",
"execute",
"(",
"\"storageattach\"",
",",
"[",
"self",
".",
"_vmname",
"]",
"+",
"args... | Change storage medium in this VM.
:param params: params to use with sub-command storageattach | [
"Change",
"storage",
"medium",
"in",
"this",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/virtualbox/virtualbox_vm.py#L796-L804 | train | 221,520 |
GNS3/gns3-server | gns3server/compute/virtualbox/virtualbox_vm.py | VirtualBoxVM._get_nic_attachements | def _get_nic_attachements(self, maximum_adapters):
"""
Returns NIC attachements.
:param maximum_adapters: maximum number of supported adapters
:returns: list of adapters with their Attachment setting (NAT, bridged etc.)
"""
nics = []
vm_info = yield from self._get_vm_info()
for adapter_number in range(0, maximum_adapters):
entry = "nic{}".format(adapter_number + 1)
if entry in vm_info:
value = vm_info[entry]
nics.append(value.lower())
else:
nics.append(None)
return nics | python | def _get_nic_attachements(self, maximum_adapters):
"""
Returns NIC attachements.
:param maximum_adapters: maximum number of supported adapters
:returns: list of adapters with their Attachment setting (NAT, bridged etc.)
"""
nics = []
vm_info = yield from self._get_vm_info()
for adapter_number in range(0, maximum_adapters):
entry = "nic{}".format(adapter_number + 1)
if entry in vm_info:
value = vm_info[entry]
nics.append(value.lower())
else:
nics.append(None)
return nics | [
"def",
"_get_nic_attachements",
"(",
"self",
",",
"maximum_adapters",
")",
":",
"nics",
"=",
"[",
"]",
"vm_info",
"=",
"yield",
"from",
"self",
".",
"_get_vm_info",
"(",
")",
"for",
"adapter_number",
"in",
"range",
"(",
"0",
",",
"maximum_adapters",
")",
"... | Returns NIC attachements.
:param maximum_adapters: maximum number of supported adapters
:returns: list of adapters with their Attachment setting (NAT, bridged etc.) | [
"Returns",
"NIC",
"attachements",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/virtualbox/virtualbox_vm.py#L807-L824 | train | 221,521 |
GNS3/gns3-server | gns3server/compute/virtualbox/virtualbox_vm.py | VirtualBoxVM._create_linked_clone | def _create_linked_clone(self):
"""
Creates a new linked clone.
"""
gns3_snapshot_exists = False
vm_info = yield from self._get_vm_info()
for entry, value in vm_info.items():
if entry.startswith("SnapshotName") and value == "GNS3 Linked Base for clones":
gns3_snapshot_exists = True
if not gns3_snapshot_exists:
result = yield from self.manager.execute("snapshot", [self._vmname, "take", "GNS3 Linked Base for clones"])
log.debug("GNS3 snapshot created: {}".format(result))
args = [self._vmname,
"--snapshot",
"GNS3 Linked Base for clones",
"--options",
"link",
"--name",
self.name,
"--basefolder",
self.working_dir,
"--register"]
result = yield from self.manager.execute("clonevm", args)
log.debug("VirtualBox VM: {} cloned".format(result))
self._vmname = self._name
yield from self.manager.execute("setextradata", [self._vmname, "GNS3/Clone", "yes"])
# We create a reset snapshot in order to simplify life of user who want to rollback their VM
# Warning: Do not document this it's seem buggy we keep it because Raizo students use it.
try:
args = [self._vmname, "take", "reset"]
result = yield from self.manager.execute("snapshot", args)
log.debug("Snapshot 'reset' created: {}".format(result))
# It seem sometimes this failed due to internal race condition of Vbox
# we have no real explanation of this.
except VirtualBoxError:
log.warn("Snapshot 'reset' not created")
os.makedirs(os.path.join(self.working_dir, self._vmname), exist_ok=True) | python | def _create_linked_clone(self):
"""
Creates a new linked clone.
"""
gns3_snapshot_exists = False
vm_info = yield from self._get_vm_info()
for entry, value in vm_info.items():
if entry.startswith("SnapshotName") and value == "GNS3 Linked Base for clones":
gns3_snapshot_exists = True
if not gns3_snapshot_exists:
result = yield from self.manager.execute("snapshot", [self._vmname, "take", "GNS3 Linked Base for clones"])
log.debug("GNS3 snapshot created: {}".format(result))
args = [self._vmname,
"--snapshot",
"GNS3 Linked Base for clones",
"--options",
"link",
"--name",
self.name,
"--basefolder",
self.working_dir,
"--register"]
result = yield from self.manager.execute("clonevm", args)
log.debug("VirtualBox VM: {} cloned".format(result))
self._vmname = self._name
yield from self.manager.execute("setextradata", [self._vmname, "GNS3/Clone", "yes"])
# We create a reset snapshot in order to simplify life of user who want to rollback their VM
# Warning: Do not document this it's seem buggy we keep it because Raizo students use it.
try:
args = [self._vmname, "take", "reset"]
result = yield from self.manager.execute("snapshot", args)
log.debug("Snapshot 'reset' created: {}".format(result))
# It seem sometimes this failed due to internal race condition of Vbox
# we have no real explanation of this.
except VirtualBoxError:
log.warn("Snapshot 'reset' not created")
os.makedirs(os.path.join(self.working_dir, self._vmname), exist_ok=True) | [
"def",
"_create_linked_clone",
"(",
"self",
")",
":",
"gns3_snapshot_exists",
"=",
"False",
"vm_info",
"=",
"yield",
"from",
"self",
".",
"_get_vm_info",
"(",
")",
"for",
"entry",
",",
"value",
"in",
"vm_info",
".",
"items",
"(",
")",
":",
"if",
"entry",
... | Creates a new linked clone. | [
"Creates",
"a",
"new",
"linked",
"clone",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/virtualbox/virtualbox_vm.py#L890-L933 | train | 221,522 |
GNS3/gns3-server | gns3server/ubridge/hypervisor.py | Hypervisor._check_ubridge_version | def _check_ubridge_version(self, env=None):
"""
Checks if the ubridge executable version
"""
try:
output = yield from subprocess_check_output(self._path, "-v", cwd=self._working_dir, env=env)
match = re.search("ubridge version ([0-9a-z\.]+)", output)
if match:
self._version = match.group(1)
if sys.platform.startswith("win") or sys.platform.startswith("darwin"):
minimum_required_version = "0.9.12"
else:
# uBridge version 0.9.14 is required for packet filters
# to work for IOU nodes.
minimum_required_version = "0.9.14"
if parse_version(self._version) < parse_version(minimum_required_version):
raise UbridgeError("uBridge executable version must be >= {}".format(minimum_required_version))
else:
raise UbridgeError("Could not determine uBridge version for {}".format(self._path))
except (OSError, subprocess.SubprocessError) as e:
raise UbridgeError("Error while looking for uBridge version: {}".format(e)) | python | def _check_ubridge_version(self, env=None):
"""
Checks if the ubridge executable version
"""
try:
output = yield from subprocess_check_output(self._path, "-v", cwd=self._working_dir, env=env)
match = re.search("ubridge version ([0-9a-z\.]+)", output)
if match:
self._version = match.group(1)
if sys.platform.startswith("win") or sys.platform.startswith("darwin"):
minimum_required_version = "0.9.12"
else:
# uBridge version 0.9.14 is required for packet filters
# to work for IOU nodes.
minimum_required_version = "0.9.14"
if parse_version(self._version) < parse_version(minimum_required_version):
raise UbridgeError("uBridge executable version must be >= {}".format(minimum_required_version))
else:
raise UbridgeError("Could not determine uBridge version for {}".format(self._path))
except (OSError, subprocess.SubprocessError) as e:
raise UbridgeError("Error while looking for uBridge version: {}".format(e)) | [
"def",
"_check_ubridge_version",
"(",
"self",
",",
"env",
"=",
"None",
")",
":",
"try",
":",
"output",
"=",
"yield",
"from",
"subprocess_check_output",
"(",
"self",
".",
"_path",
",",
"\"-v\"",
",",
"cwd",
"=",
"self",
".",
"_working_dir",
",",
"env",
"=... | Checks if the ubridge executable version | [
"Checks",
"if",
"the",
"ubridge",
"executable",
"version"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/ubridge/hypervisor.py#L132-L152 | train | 221,523 |
GNS3/gns3-server | gns3server/ubridge/hypervisor.py | Hypervisor.start | def start(self):
"""
Starts the uBridge hypervisor process.
"""
env = os.environ.copy()
if sys.platform.startswith("win"):
# add the Npcap directory to $PATH to force uBridge to use npcap DLL instead of Winpcap (if installed)
system_root = os.path.join(os.path.expandvars("%SystemRoot%"), "System32", "Npcap")
if os.path.isdir(system_root):
env["PATH"] = system_root + ';' + env["PATH"]
yield from self._check_ubridge_version(env)
try:
command = self._build_command()
log.info("starting ubridge: {}".format(command))
self._stdout_file = os.path.join(self._working_dir, "ubridge.log")
log.info("logging to {}".format(self._stdout_file))
with open(self._stdout_file, "w", encoding="utf-8") as fd:
self._process = yield from asyncio.create_subprocess_exec(*command,
stdout=fd,
stderr=subprocess.STDOUT,
cwd=self._working_dir,
env=env)
log.info("ubridge started PID={}".format(self._process.pid))
except (OSError, PermissionError, subprocess.SubprocessError) as e:
ubridge_stdout = self.read_stdout()
log.error("Could not start ubridge: {}\n{}".format(e, ubridge_stdout))
raise UbridgeError("Could not start ubridge: {}\n{}".format(e, ubridge_stdout)) | python | def start(self):
"""
Starts the uBridge hypervisor process.
"""
env = os.environ.copy()
if sys.platform.startswith("win"):
# add the Npcap directory to $PATH to force uBridge to use npcap DLL instead of Winpcap (if installed)
system_root = os.path.join(os.path.expandvars("%SystemRoot%"), "System32", "Npcap")
if os.path.isdir(system_root):
env["PATH"] = system_root + ';' + env["PATH"]
yield from self._check_ubridge_version(env)
try:
command = self._build_command()
log.info("starting ubridge: {}".format(command))
self._stdout_file = os.path.join(self._working_dir, "ubridge.log")
log.info("logging to {}".format(self._stdout_file))
with open(self._stdout_file, "w", encoding="utf-8") as fd:
self._process = yield from asyncio.create_subprocess_exec(*command,
stdout=fd,
stderr=subprocess.STDOUT,
cwd=self._working_dir,
env=env)
log.info("ubridge started PID={}".format(self._process.pid))
except (OSError, PermissionError, subprocess.SubprocessError) as e:
ubridge_stdout = self.read_stdout()
log.error("Could not start ubridge: {}\n{}".format(e, ubridge_stdout))
raise UbridgeError("Could not start ubridge: {}\n{}".format(e, ubridge_stdout)) | [
"def",
"start",
"(",
"self",
")",
":",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"# add the Npcap directory to $PATH to force uBridge to use npcap DLL instead of Winpcap (if in... | Starts the uBridge hypervisor process. | [
"Starts",
"the",
"uBridge",
"hypervisor",
"process",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/ubridge/hypervisor.py#L155-L183 | train | 221,524 |
GNS3/gns3-server | gns3server/compute/vmware/__init__.py | VMware.find_vmrun | def find_vmrun(self):
"""
Searches for vmrun.
:returns: path to vmrun
"""
# look for vmrun
vmrun_path = self.config.get_section_config("VMware").get("vmrun_path")
if not vmrun_path:
if sys.platform.startswith("win"):
vmrun_path = shutil.which("vmrun")
if vmrun_path is None:
# look for vmrun.exe using the VMware Workstation directory listed in the registry
vmrun_path = self._find_vmrun_registry(r"SOFTWARE\Wow6432Node\VMware, Inc.\VMware Workstation")
if vmrun_path is None:
# look for vmrun.exe using the VIX directory listed in the registry
vmrun_path = self._find_vmrun_registry(r"SOFTWARE\Wow6432Node\VMware, Inc.\VMware VIX")
elif sys.platform.startswith("darwin"):
vmrun_path = "/Applications/VMware Fusion.app/Contents/Library/vmrun"
else:
vmrun_path = "vmrun"
if vmrun_path and not os.path.isabs(vmrun_path):
vmrun_path = shutil.which(vmrun_path)
if not vmrun_path:
raise VMwareError("Could not find VMware vmrun, please make sure it is installed")
if not os.path.isfile(vmrun_path):
raise VMwareError("vmrun {} is not accessible".format(vmrun_path))
if not os.access(vmrun_path, os.X_OK):
raise VMwareError("vmrun is not executable")
if os.path.basename(vmrun_path).lower() not in ["vmrun", "vmrun.exe"]:
raise VMwareError("Invalid vmrun executable name {}".format(os.path.basename(vmrun_path)))
self._vmrun_path = vmrun_path
return vmrun_path | python | def find_vmrun(self):
"""
Searches for vmrun.
:returns: path to vmrun
"""
# look for vmrun
vmrun_path = self.config.get_section_config("VMware").get("vmrun_path")
if not vmrun_path:
if sys.platform.startswith("win"):
vmrun_path = shutil.which("vmrun")
if vmrun_path is None:
# look for vmrun.exe using the VMware Workstation directory listed in the registry
vmrun_path = self._find_vmrun_registry(r"SOFTWARE\Wow6432Node\VMware, Inc.\VMware Workstation")
if vmrun_path is None:
# look for vmrun.exe using the VIX directory listed in the registry
vmrun_path = self._find_vmrun_registry(r"SOFTWARE\Wow6432Node\VMware, Inc.\VMware VIX")
elif sys.platform.startswith("darwin"):
vmrun_path = "/Applications/VMware Fusion.app/Contents/Library/vmrun"
else:
vmrun_path = "vmrun"
if vmrun_path and not os.path.isabs(vmrun_path):
vmrun_path = shutil.which(vmrun_path)
if not vmrun_path:
raise VMwareError("Could not find VMware vmrun, please make sure it is installed")
if not os.path.isfile(vmrun_path):
raise VMwareError("vmrun {} is not accessible".format(vmrun_path))
if not os.access(vmrun_path, os.X_OK):
raise VMwareError("vmrun is not executable")
if os.path.basename(vmrun_path).lower() not in ["vmrun", "vmrun.exe"]:
raise VMwareError("Invalid vmrun executable name {}".format(os.path.basename(vmrun_path)))
self._vmrun_path = vmrun_path
return vmrun_path | [
"def",
"find_vmrun",
"(",
"self",
")",
":",
"# look for vmrun",
"vmrun_path",
"=",
"self",
".",
"config",
".",
"get_section_config",
"(",
"\"VMware\"",
")",
".",
"get",
"(",
"\"vmrun_path\"",
")",
"if",
"not",
"vmrun_path",
":",
"if",
"sys",
".",
"platform",... | Searches for vmrun.
:returns: path to vmrun | [
"Searches",
"for",
"vmrun",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/__init__.py#L87-L123 | train | 221,525 |
GNS3/gns3-server | gns3server/compute/vmware/__init__.py | VMware._check_vmware_player_requirements | def _check_vmware_player_requirements(self, player_version):
"""
Check minimum requirements to use VMware Player.
VIX 1.13 was the release for Player 6.
VIX 1.14 was the release for Player 7.
VIX 1.15 was the release for Workstation Player 12.
:param player_version: VMware Player major version.
"""
player_version = int(player_version)
if player_version < 6:
raise VMwareError("Using VMware Player requires version 6 or above")
elif player_version == 6:
yield from self.check_vmrun_version(minimum_required_version="1.13.0")
elif player_version == 7:
yield from self.check_vmrun_version(minimum_required_version="1.14.0")
elif player_version >= 12:
yield from self.check_vmrun_version(minimum_required_version="1.15.0")
self._host_type = "player" | python | def _check_vmware_player_requirements(self, player_version):
"""
Check minimum requirements to use VMware Player.
VIX 1.13 was the release for Player 6.
VIX 1.14 was the release for Player 7.
VIX 1.15 was the release for Workstation Player 12.
:param player_version: VMware Player major version.
"""
player_version = int(player_version)
if player_version < 6:
raise VMwareError("Using VMware Player requires version 6 or above")
elif player_version == 6:
yield from self.check_vmrun_version(minimum_required_version="1.13.0")
elif player_version == 7:
yield from self.check_vmrun_version(minimum_required_version="1.14.0")
elif player_version >= 12:
yield from self.check_vmrun_version(minimum_required_version="1.15.0")
self._host_type = "player" | [
"def",
"_check_vmware_player_requirements",
"(",
"self",
",",
"player_version",
")",
":",
"player_version",
"=",
"int",
"(",
"player_version",
")",
"if",
"player_version",
"<",
"6",
":",
"raise",
"VMwareError",
"(",
"\"Using VMware Player requires version 6 or above\"",
... | Check minimum requirements to use VMware Player.
VIX 1.13 was the release for Player 6.
VIX 1.14 was the release for Player 7.
VIX 1.15 was the release for Workstation Player 12.
:param player_version: VMware Player major version. | [
"Check",
"minimum",
"requirements",
"to",
"use",
"VMware",
"Player",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/__init__.py#L144-L164 | train | 221,526 |
GNS3/gns3-server | gns3server/compute/vmware/__init__.py | VMware._check_vmware_workstation_requirements | def _check_vmware_workstation_requirements(self, ws_version):
"""
Check minimum requirements to use VMware Workstation.
VIX 1.13 was the release for Workstation 10.
VIX 1.14 was the release for Workstation 11.
VIX 1.15 was the release for Workstation Pro 12.
:param ws_version: VMware Workstation major version.
"""
ws_version = int(ws_version)
if ws_version < 10:
raise VMwareError("Using VMware Workstation requires version 10 or above")
elif ws_version == 10:
yield from self.check_vmrun_version(minimum_required_version="1.13.0")
elif ws_version == 11:
yield from self.check_vmrun_version(minimum_required_version="1.14.0")
elif ws_version >= 12:
yield from self.check_vmrun_version(minimum_required_version="1.15.0")
self._host_type = "ws" | python | def _check_vmware_workstation_requirements(self, ws_version):
"""
Check minimum requirements to use VMware Workstation.
VIX 1.13 was the release for Workstation 10.
VIX 1.14 was the release for Workstation 11.
VIX 1.15 was the release for Workstation Pro 12.
:param ws_version: VMware Workstation major version.
"""
ws_version = int(ws_version)
if ws_version < 10:
raise VMwareError("Using VMware Workstation requires version 10 or above")
elif ws_version == 10:
yield from self.check_vmrun_version(minimum_required_version="1.13.0")
elif ws_version == 11:
yield from self.check_vmrun_version(minimum_required_version="1.14.0")
elif ws_version >= 12:
yield from self.check_vmrun_version(minimum_required_version="1.15.0")
self._host_type = "ws" | [
"def",
"_check_vmware_workstation_requirements",
"(",
"self",
",",
"ws_version",
")",
":",
"ws_version",
"=",
"int",
"(",
"ws_version",
")",
"if",
"ws_version",
"<",
"10",
":",
"raise",
"VMwareError",
"(",
"\"Using VMware Workstation requires version 10 or above\"",
")"... | Check minimum requirements to use VMware Workstation.
VIX 1.13 was the release for Workstation 10.
VIX 1.14 was the release for Workstation 11.
VIX 1.15 was the release for Workstation Pro 12.
:param ws_version: VMware Workstation major version. | [
"Check",
"minimum",
"requirements",
"to",
"use",
"VMware",
"Workstation",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/__init__.py#L167-L187 | train | 221,527 |
GNS3/gns3-server | gns3server/compute/vmware/__init__.py | VMware.check_vmware_version | def check_vmware_version(self):
"""
Check VMware version
"""
if sys.platform.startswith("win"):
# look for vmrun.exe using the directory listed in the registry
ws_version = self._find_vmware_version_registry(r"SOFTWARE\Wow6432Node\VMware, Inc.\VMware Workstation")
if ws_version is None:
player_version = self._find_vmware_version_registry(r"SOFTWARE\Wow6432Node\VMware, Inc.\VMware Player")
if player_version:
log.debug("VMware Player version {} detected".format(player_version))
yield from self._check_vmware_player_requirements(player_version)
else:
log.warning("Could not find VMware version")
self._host_type = "ws"
else:
log.debug("VMware Workstation version {} detected".format(ws_version))
yield from self._check_vmware_workstation_requirements(ws_version)
else:
if sys.platform.startswith("darwin"):
if not os.path.isdir("/Applications/VMware Fusion.app"):
raise VMwareError("VMware Fusion is not installed in the standard location /Applications/VMware Fusion.app")
self._host_type = "fusion"
return # FIXME: no version checking on Mac OS X but we support all versions of fusion
vmware_path = VMware._get_linux_vmware_binary()
if vmware_path is None:
raise VMwareError("VMware is not installed (vmware or vmplayer executable could not be found in $PATH)")
try:
output = yield from subprocess_check_output(vmware_path, "-v")
match = re.search("VMware Workstation ([0-9]+)\.", output)
version = None
if match:
# VMware Workstation has been detected
version = match.group(1)
log.debug("VMware Workstation version {} detected".format(version))
yield from self._check_vmware_workstation_requirements(version)
match = re.search("VMware Player ([0-9]+)\.", output)
if match:
# VMware Player has been detected
version = match.group(1)
log.debug("VMware Player version {} detected".format(version))
yield from self._check_vmware_player_requirements(version)
if version is None:
log.warning("Could not find VMware version. Output of VMware: {}".format(output))
raise VMwareError("Could not find VMware version. Output of VMware: {}".format(output))
except (OSError, subprocess.SubprocessError) as e:
log.error("Error while looking for the VMware version: {}".format(e))
raise VMwareError("Error while looking for the VMware version: {}".format(e)) | python | def check_vmware_version(self):
"""
Check VMware version
"""
if sys.platform.startswith("win"):
# look for vmrun.exe using the directory listed in the registry
ws_version = self._find_vmware_version_registry(r"SOFTWARE\Wow6432Node\VMware, Inc.\VMware Workstation")
if ws_version is None:
player_version = self._find_vmware_version_registry(r"SOFTWARE\Wow6432Node\VMware, Inc.\VMware Player")
if player_version:
log.debug("VMware Player version {} detected".format(player_version))
yield from self._check_vmware_player_requirements(player_version)
else:
log.warning("Could not find VMware version")
self._host_type = "ws"
else:
log.debug("VMware Workstation version {} detected".format(ws_version))
yield from self._check_vmware_workstation_requirements(ws_version)
else:
if sys.platform.startswith("darwin"):
if not os.path.isdir("/Applications/VMware Fusion.app"):
raise VMwareError("VMware Fusion is not installed in the standard location /Applications/VMware Fusion.app")
self._host_type = "fusion"
return # FIXME: no version checking on Mac OS X but we support all versions of fusion
vmware_path = VMware._get_linux_vmware_binary()
if vmware_path is None:
raise VMwareError("VMware is not installed (vmware or vmplayer executable could not be found in $PATH)")
try:
output = yield from subprocess_check_output(vmware_path, "-v")
match = re.search("VMware Workstation ([0-9]+)\.", output)
version = None
if match:
# VMware Workstation has been detected
version = match.group(1)
log.debug("VMware Workstation version {} detected".format(version))
yield from self._check_vmware_workstation_requirements(version)
match = re.search("VMware Player ([0-9]+)\.", output)
if match:
# VMware Player has been detected
version = match.group(1)
log.debug("VMware Player version {} detected".format(version))
yield from self._check_vmware_player_requirements(version)
if version is None:
log.warning("Could not find VMware version. Output of VMware: {}".format(output))
raise VMwareError("Could not find VMware version. Output of VMware: {}".format(output))
except (OSError, subprocess.SubprocessError) as e:
log.error("Error while looking for the VMware version: {}".format(e))
raise VMwareError("Error while looking for the VMware version: {}".format(e)) | [
"def",
"check_vmware_version",
"(",
"self",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"# look for vmrun.exe using the directory listed in the registry",
"ws_version",
"=",
"self",
".",
"_find_vmware_version_registry",
"(",
"r\"... | Check VMware version | [
"Check",
"VMware",
"version"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/__init__.py#L190-L240 | train | 221,528 |
GNS3/gns3-server | gns3server/compute/vmware/__init__.py | VMware.check_vmrun_version | def check_vmrun_version(self, minimum_required_version="1.13.0"):
"""
Checks the vmrun version.
VMware VIX library version must be at least >= 1.13 by default
VIX 1.13 was the release for VMware Fusion 6, Workstation 10, and Player 6.
VIX 1.14 was the release for VMware Fusion 7, Workstation 11 and Player 7.
VIX 1.15 was the release for VMware Fusion 8, Workstation Pro 12 and Workstation Player 12.
:param required_version: required vmrun version number
"""
vmrun_path = self.vmrun_path
if not vmrun_path:
vmrun_path = self.find_vmrun()
try:
output = yield from subprocess_check_output(vmrun_path)
match = re.search("vmrun version ([0-9\.]+)", output)
version = None
if match:
version = match.group(1)
log.debug("VMware vmrun version {} detected, minimum required: {}".format(version, minimum_required_version))
if parse_version(version) < parse_version(minimum_required_version):
raise VMwareError("VMware vmrun executable version must be >= version {}".format(minimum_required_version))
if version is None:
log.warning("Could not find VMware vmrun version. Output: {}".format(output))
raise VMwareError("Could not find VMware vmrun version. Output: {}".format(output))
except (OSError, subprocess.SubprocessError) as e:
log.error("Error while looking for the VMware vmrun version: {}".format(e))
raise VMwareError("Error while looking for the VMware vmrun version: {}".format(e)) | python | def check_vmrun_version(self, minimum_required_version="1.13.0"):
"""
Checks the vmrun version.
VMware VIX library version must be at least >= 1.13 by default
VIX 1.13 was the release for VMware Fusion 6, Workstation 10, and Player 6.
VIX 1.14 was the release for VMware Fusion 7, Workstation 11 and Player 7.
VIX 1.15 was the release for VMware Fusion 8, Workstation Pro 12 and Workstation Player 12.
:param required_version: required vmrun version number
"""
vmrun_path = self.vmrun_path
if not vmrun_path:
vmrun_path = self.find_vmrun()
try:
output = yield from subprocess_check_output(vmrun_path)
match = re.search("vmrun version ([0-9\.]+)", output)
version = None
if match:
version = match.group(1)
log.debug("VMware vmrun version {} detected, minimum required: {}".format(version, minimum_required_version))
if parse_version(version) < parse_version(minimum_required_version):
raise VMwareError("VMware vmrun executable version must be >= version {}".format(minimum_required_version))
if version is None:
log.warning("Could not find VMware vmrun version. Output: {}".format(output))
raise VMwareError("Could not find VMware vmrun version. Output: {}".format(output))
except (OSError, subprocess.SubprocessError) as e:
log.error("Error while looking for the VMware vmrun version: {}".format(e))
raise VMwareError("Error while looking for the VMware vmrun version: {}".format(e)) | [
"def",
"check_vmrun_version",
"(",
"self",
",",
"minimum_required_version",
"=",
"\"1.13.0\"",
")",
":",
"vmrun_path",
"=",
"self",
".",
"vmrun_path",
"if",
"not",
"vmrun_path",
":",
"vmrun_path",
"=",
"self",
".",
"find_vmrun",
"(",
")",
"try",
":",
"output",... | Checks the vmrun version.
VMware VIX library version must be at least >= 1.13 by default
VIX 1.13 was the release for VMware Fusion 6, Workstation 10, and Player 6.
VIX 1.14 was the release for VMware Fusion 7, Workstation 11 and Player 7.
VIX 1.15 was the release for VMware Fusion 8, Workstation Pro 12 and Workstation Player 12.
:param required_version: required vmrun version number | [
"Checks",
"the",
"vmrun",
"version",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/__init__.py#L409-L439 | train | 221,529 |
GNS3/gns3-server | gns3server/compute/vmware/__init__.py | VMware.remove_from_vmware_inventory | def remove_from_vmware_inventory(self, vmx_path):
"""
Removes a linked clone from the VMware inventory file.
:param vmx_path: path of the linked clone VMX file
"""
with (yield from self._vmware_inventory_lock):
inventory_path = self.get_vmware_inventory_path()
if os.path.exists(inventory_path):
try:
inventory_pairs = self.parse_vmware_file(inventory_path)
except OSError as e:
log.warning('Could not read VMware inventory file "{}": {}'.format(inventory_path, e))
return
vmlist_entry = None
for name, value in inventory_pairs.items():
if value == vmx_path:
vmlist_entry = name.split(".", 1)[0]
break
if vmlist_entry is not None:
for name in inventory_pairs.copy().keys():
if name.startswith(vmlist_entry):
del inventory_pairs[name]
try:
self.write_vmware_file(inventory_path, inventory_pairs)
except OSError as e:
raise VMwareError('Could not write VMware inventory file "{}": {}'.format(inventory_path, e)) | python | def remove_from_vmware_inventory(self, vmx_path):
"""
Removes a linked clone from the VMware inventory file.
:param vmx_path: path of the linked clone VMX file
"""
with (yield from self._vmware_inventory_lock):
inventory_path = self.get_vmware_inventory_path()
if os.path.exists(inventory_path):
try:
inventory_pairs = self.parse_vmware_file(inventory_path)
except OSError as e:
log.warning('Could not read VMware inventory file "{}": {}'.format(inventory_path, e))
return
vmlist_entry = None
for name, value in inventory_pairs.items():
if value == vmx_path:
vmlist_entry = name.split(".", 1)[0]
break
if vmlist_entry is not None:
for name in inventory_pairs.copy().keys():
if name.startswith(vmlist_entry):
del inventory_pairs[name]
try:
self.write_vmware_file(inventory_path, inventory_pairs)
except OSError as e:
raise VMwareError('Could not write VMware inventory file "{}": {}'.format(inventory_path, e)) | [
"def",
"remove_from_vmware_inventory",
"(",
"self",
",",
"vmx_path",
")",
":",
"with",
"(",
"yield",
"from",
"self",
".",
"_vmware_inventory_lock",
")",
":",
"inventory_path",
"=",
"self",
".",
"get_vmware_inventory_path",
"(",
")",
"if",
"os",
".",
"path",
".... | Removes a linked clone from the VMware inventory file.
:param vmx_path: path of the linked clone VMX file | [
"Removes",
"a",
"linked",
"clone",
"from",
"the",
"VMware",
"inventory",
"file",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/__init__.py#L442-L472 | train | 221,530 |
GNS3/gns3-server | gns3server/compute/vmware/__init__.py | VMware.write_vmx_file | def write_vmx_file(path, pairs):
"""
Write a VMware VMX file.
:param path: path to the VMX file
:param pairs: settings to write
"""
encoding = "utf-8"
if ".encoding" in pairs:
file_encoding = pairs[".encoding"]
try:
codecs.lookup(file_encoding)
encoding = file_encoding
except LookupError:
log.warning("Invalid file encoding detected in '{}': {}".format(path, file_encoding))
with open(path, "w", encoding=encoding, errors="ignore") as f:
if sys.platform.startswith("linux"):
# write the shebang on the first line on Linux
vmware_path = VMware._get_linux_vmware_binary()
if vmware_path:
f.write("#!{}\n".format(vmware_path))
for key, value in pairs.items():
entry = '{} = "{}"\n'.format(key, value)
f.write(entry) | python | def write_vmx_file(path, pairs):
"""
Write a VMware VMX file.
:param path: path to the VMX file
:param pairs: settings to write
"""
encoding = "utf-8"
if ".encoding" in pairs:
file_encoding = pairs[".encoding"]
try:
codecs.lookup(file_encoding)
encoding = file_encoding
except LookupError:
log.warning("Invalid file encoding detected in '{}': {}".format(path, file_encoding))
with open(path, "w", encoding=encoding, errors="ignore") as f:
if sys.platform.startswith("linux"):
# write the shebang on the first line on Linux
vmware_path = VMware._get_linux_vmware_binary()
if vmware_path:
f.write("#!{}\n".format(vmware_path))
for key, value in pairs.items():
entry = '{} = "{}"\n'.format(key, value)
f.write(entry) | [
"def",
"write_vmx_file",
"(",
"path",
",",
"pairs",
")",
":",
"encoding",
"=",
"\"utf-8\"",
"if",
"\".encoding\"",
"in",
"pairs",
":",
"file_encoding",
"=",
"pairs",
"[",
"\".encoding\"",
"]",
"try",
":",
"codecs",
".",
"lookup",
"(",
"file_encoding",
")",
... | Write a VMware VMX file.
:param path: path to the VMX file
:param pairs: settings to write | [
"Write",
"a",
"VMware",
"VMX",
"file",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/__init__.py#L537-L561 | train | 221,531 |
GNS3/gns3-server | gns3server/compute/vmware/__init__.py | VMware._get_vms_from_inventory | def _get_vms_from_inventory(self, inventory_path):
"""
Searches for VMs by parsing a VMware inventory file.
:param inventory_path: path to the inventory file
:returns: list of VMs
"""
vm_entries = {}
vmware_vms = []
log.info('Searching for VMware VMs in inventory file "{}"'.format(inventory_path))
try:
pairs = self.parse_vmware_file(inventory_path)
for key, value in pairs.items():
if key.startswith("vmlist"):
try:
vm_entry, variable_name = key.split('.', 1)
except ValueError:
continue
if vm_entry not in vm_entries:
vm_entries[vm_entry] = {}
vm_entries[vm_entry][variable_name.strip()] = value
except OSError as e:
log.warning("Could not read VMware inventory file {}: {}".format(inventory_path, e))
for vm_settings in vm_entries.values():
if "displayname" in vm_settings and "config" in vm_settings:
if os.path.exists(vm_settings["config"]):
log.debug('Found VM named "{}" with VMX file "{}"'.format(vm_settings["displayname"], vm_settings["config"]))
vmware_vms.append({"vmname": vm_settings["displayname"], "vmx_path": vm_settings["config"]})
return vmware_vms | python | def _get_vms_from_inventory(self, inventory_path):
"""
Searches for VMs by parsing a VMware inventory file.
:param inventory_path: path to the inventory file
:returns: list of VMs
"""
vm_entries = {}
vmware_vms = []
log.info('Searching for VMware VMs in inventory file "{}"'.format(inventory_path))
try:
pairs = self.parse_vmware_file(inventory_path)
for key, value in pairs.items():
if key.startswith("vmlist"):
try:
vm_entry, variable_name = key.split('.', 1)
except ValueError:
continue
if vm_entry not in vm_entries:
vm_entries[vm_entry] = {}
vm_entries[vm_entry][variable_name.strip()] = value
except OSError as e:
log.warning("Could not read VMware inventory file {}: {}".format(inventory_path, e))
for vm_settings in vm_entries.values():
if "displayname" in vm_settings and "config" in vm_settings:
if os.path.exists(vm_settings["config"]):
log.debug('Found VM named "{}" with VMX file "{}"'.format(vm_settings["displayname"], vm_settings["config"]))
vmware_vms.append({"vmname": vm_settings["displayname"], "vmx_path": vm_settings["config"]})
return vmware_vms | [
"def",
"_get_vms_from_inventory",
"(",
"self",
",",
"inventory_path",
")",
":",
"vm_entries",
"=",
"{",
"}",
"vmware_vms",
"=",
"[",
"]",
"log",
".",
"info",
"(",
"'Searching for VMware VMs in inventory file \"{}\"'",
".",
"format",
"(",
"inventory_path",
")",
")"... | Searches for VMs by parsing a VMware inventory file.
:param inventory_path: path to the inventory file
:returns: list of VMs | [
"Searches",
"for",
"VMs",
"by",
"parsing",
"a",
"VMware",
"inventory",
"file",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/__init__.py#L563-L594 | train | 221,532 |
GNS3/gns3-server | gns3server/compute/vmware/__init__.py | VMware._get_vms_from_directory | def _get_vms_from_directory(self, directory):
"""
Searches for VMs in a given directory.
:param directory: path to the directory
:returns: list of VMs
"""
vmware_vms = []
log.info('Searching for VMware VMs in directory "{}"'.format(directory))
for path, _, filenames in os.walk(directory):
for filename in filenames:
if os.path.splitext(filename)[1] == ".vmx":
vmx_path = os.path.join(path, filename)
log.debug('Reading VMware VMX file "{}"'.format(vmx_path))
try:
pairs = self.parse_vmware_file(vmx_path)
if "displayname" in pairs:
log.debug('Found VM named "{}"'.format(pairs["displayname"]))
vmware_vms.append({"vmname": pairs["displayname"], "vmx_path": vmx_path})
except OSError as e:
log.warning('Could not read VMware VMX file "{}": {}'.format(vmx_path, e))
continue
return vmware_vms | python | def _get_vms_from_directory(self, directory):
"""
Searches for VMs in a given directory.
:param directory: path to the directory
:returns: list of VMs
"""
vmware_vms = []
log.info('Searching for VMware VMs in directory "{}"'.format(directory))
for path, _, filenames in os.walk(directory):
for filename in filenames:
if os.path.splitext(filename)[1] == ".vmx":
vmx_path = os.path.join(path, filename)
log.debug('Reading VMware VMX file "{}"'.format(vmx_path))
try:
pairs = self.parse_vmware_file(vmx_path)
if "displayname" in pairs:
log.debug('Found VM named "{}"'.format(pairs["displayname"]))
vmware_vms.append({"vmname": pairs["displayname"], "vmx_path": vmx_path})
except OSError as e:
log.warning('Could not read VMware VMX file "{}": {}'.format(vmx_path, e))
continue
return vmware_vms | [
"def",
"_get_vms_from_directory",
"(",
"self",
",",
"directory",
")",
":",
"vmware_vms",
"=",
"[",
"]",
"log",
".",
"info",
"(",
"'Searching for VMware VMs in directory \"{}\"'",
".",
"format",
"(",
"directory",
")",
")",
"for",
"path",
",",
"_",
",",
"filenam... | Searches for VMs in a given directory.
:param directory: path to the directory
:returns: list of VMs | [
"Searches",
"for",
"VMs",
"in",
"a",
"given",
"directory",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/__init__.py#L596-L620 | train | 221,533 |
GNS3/gns3-server | gns3server/compute/vmware/__init__.py | VMware.get_vmware_inventory_path | def get_vmware_inventory_path():
"""
Returns VMware inventory file path.
:returns: path to the inventory file
"""
if sys.platform.startswith("win"):
return os.path.expandvars(r"%APPDATA%\Vmware\Inventory.vmls")
elif sys.platform.startswith("darwin"):
return os.path.expanduser("~/Library/Application Support/VMware Fusion/vmInventory")
else:
return os.path.expanduser("~/.vmware/inventory.vmls") | python | def get_vmware_inventory_path():
"""
Returns VMware inventory file path.
:returns: path to the inventory file
"""
if sys.platform.startswith("win"):
return os.path.expandvars(r"%APPDATA%\Vmware\Inventory.vmls")
elif sys.platform.startswith("darwin"):
return os.path.expanduser("~/Library/Application Support/VMware Fusion/vmInventory")
else:
return os.path.expanduser("~/.vmware/inventory.vmls") | [
"def",
"get_vmware_inventory_path",
"(",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"return",
"os",
".",
"path",
".",
"expandvars",
"(",
"r\"%APPDATA%\\Vmware\\Inventory.vmls\"",
")",
"elif",
"sys",
".",
"platform",
".... | Returns VMware inventory file path.
:returns: path to the inventory file | [
"Returns",
"VMware",
"inventory",
"file",
"path",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/__init__.py#L623-L635 | train | 221,534 |
GNS3/gns3-server | gns3server/compute/vmware/__init__.py | VMware.get_vmware_preferences_path | def get_vmware_preferences_path():
"""
Returns VMware preferences file path.
:returns: path to the preferences file
"""
if sys.platform.startswith("win"):
return os.path.expandvars(r"%APPDATA%\VMware\preferences.ini")
elif sys.platform.startswith("darwin"):
return os.path.expanduser("~/Library/Preferences/VMware Fusion/preferences")
else:
return os.path.expanduser("~/.vmware/preferences") | python | def get_vmware_preferences_path():
"""
Returns VMware preferences file path.
:returns: path to the preferences file
"""
if sys.platform.startswith("win"):
return os.path.expandvars(r"%APPDATA%\VMware\preferences.ini")
elif sys.platform.startswith("darwin"):
return os.path.expanduser("~/Library/Preferences/VMware Fusion/preferences")
else:
return os.path.expanduser("~/.vmware/preferences") | [
"def",
"get_vmware_preferences_path",
"(",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"return",
"os",
".",
"path",
".",
"expandvars",
"(",
"r\"%APPDATA%\\VMware\\preferences.ini\"",
")",
"elif",
"sys",
".",
"platform",
... | Returns VMware preferences file path.
:returns: path to the preferences file | [
"Returns",
"VMware",
"preferences",
"file",
"path",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/__init__.py#L638-L650 | train | 221,535 |
GNS3/gns3-server | gns3server/compute/vmware/__init__.py | VMware.get_vmware_default_vm_paths | def get_vmware_default_vm_paths():
"""
Returns VMware default VM directory paths.
:returns: path to the default VM directory
"""
if sys.platform.startswith("win"):
import ctypes
import ctypes.wintypes
path = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
ctypes.windll.shell32.SHGetFolderPathW(None, 5, None, 0, path)
documents_folder = path.value
return ['{}\My Virtual Machines'.format(documents_folder), '{}\Virtual Machines'.format(documents_folder)]
elif sys.platform.startswith("darwin"):
return [os.path.expanduser("~/Documents/Virtual Machines.localized")]
else:
return [os.path.expanduser("~/vmware")] | python | def get_vmware_default_vm_paths():
"""
Returns VMware default VM directory paths.
:returns: path to the default VM directory
"""
if sys.platform.startswith("win"):
import ctypes
import ctypes.wintypes
path = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
ctypes.windll.shell32.SHGetFolderPathW(None, 5, None, 0, path)
documents_folder = path.value
return ['{}\My Virtual Machines'.format(documents_folder), '{}\Virtual Machines'.format(documents_folder)]
elif sys.platform.startswith("darwin"):
return [os.path.expanduser("~/Documents/Virtual Machines.localized")]
else:
return [os.path.expanduser("~/vmware")] | [
"def",
"get_vmware_default_vm_paths",
"(",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"import",
"ctypes",
"import",
"ctypes",
".",
"wintypes",
"path",
"=",
"ctypes",
".",
"create_unicode_buffer",
"(",
"ctypes",
".",
... | Returns VMware default VM directory paths.
:returns: path to the default VM directory | [
"Returns",
"VMware",
"default",
"VM",
"directory",
"paths",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/__init__.py#L653-L670 | train | 221,536 |
GNS3/gns3-server | gns3server/compute/vmware/__init__.py | VMware.list_vms | def list_vms(self):
"""
Gets VMware VM list.
"""
# check for the right VMware version
yield from self.check_vmware_version()
vmware_vms = []
inventory_path = self.get_vmware_inventory_path()
if os.path.exists(inventory_path) and self.host_type != "player":
# inventory may exist for VMware player if VMware workstation has been previously installed
vmware_vms = self._get_vms_from_inventory(inventory_path)
if not vmware_vms:
# backup methods when no VMware inventory file exists or for VMware player which has no inventory file
vmware_preferences_path = self.get_vmware_preferences_path()
pairs = {}
if os.path.exists(vmware_preferences_path):
# the default vm path may be present in VMware preferences file.
try:
pairs = self.parse_vmware_file(vmware_preferences_path)
except OSError as e:
log.warning('Could not read VMware preferences file "{}": {}'.format(vmware_preferences_path, e))
if "prefvmx.defaultvmpath" in pairs:
default_vm_path = pairs["prefvmx.defaultvmpath"]
if not os.path.isdir(default_vm_path):
raise VMwareError('Could not find or access the default VM directory: "{default_vm_path}". Please change "prefvmx.defaultvmpath={default_vm_path}" in "{vmware_preferences_path}"'.format(default_vm_path=default_vm_path,
vmware_preferences_path=vmware_preferences_path))
vmware_vms = self._get_vms_from_directory(default_vm_path)
if not vmware_vms:
# the default vm path is not in the VMware preferences file or that directory is empty
# let's search the default locations for VMs
for default_vm_path in self.get_vmware_default_vm_paths():
if os.path.isdir(default_vm_path):
vmware_vms.extend(self._get_vms_from_directory(default_vm_path))
if not vmware_vms:
log.warning("Could not find any VMware VM in default locations")
# look for VMX paths in the preferences file in case not all VMs are in a default directory
for key, value in pairs.items():
m = re.match(r'pref.mruVM(\d+)\.filename', key)
if m:
display_name = "pref.mruVM{}.displayName".format(m.group(1))
if display_name in pairs:
found = False
for vmware_vm in vmware_vms:
if vmware_vm["vmname"] == display_name:
found = True
if found is False:
vmware_vms.append({"vmname": pairs[display_name], "vmx_path": value})
return vmware_vms | python | def list_vms(self):
"""
Gets VMware VM list.
"""
# check for the right VMware version
yield from self.check_vmware_version()
vmware_vms = []
inventory_path = self.get_vmware_inventory_path()
if os.path.exists(inventory_path) and self.host_type != "player":
# inventory may exist for VMware player if VMware workstation has been previously installed
vmware_vms = self._get_vms_from_inventory(inventory_path)
if not vmware_vms:
# backup methods when no VMware inventory file exists or for VMware player which has no inventory file
vmware_preferences_path = self.get_vmware_preferences_path()
pairs = {}
if os.path.exists(vmware_preferences_path):
# the default vm path may be present in VMware preferences file.
try:
pairs = self.parse_vmware_file(vmware_preferences_path)
except OSError as e:
log.warning('Could not read VMware preferences file "{}": {}'.format(vmware_preferences_path, e))
if "prefvmx.defaultvmpath" in pairs:
default_vm_path = pairs["prefvmx.defaultvmpath"]
if not os.path.isdir(default_vm_path):
raise VMwareError('Could not find or access the default VM directory: "{default_vm_path}". Please change "prefvmx.defaultvmpath={default_vm_path}" in "{vmware_preferences_path}"'.format(default_vm_path=default_vm_path,
vmware_preferences_path=vmware_preferences_path))
vmware_vms = self._get_vms_from_directory(default_vm_path)
if not vmware_vms:
# the default vm path is not in the VMware preferences file or that directory is empty
# let's search the default locations for VMs
for default_vm_path in self.get_vmware_default_vm_paths():
if os.path.isdir(default_vm_path):
vmware_vms.extend(self._get_vms_from_directory(default_vm_path))
if not vmware_vms:
log.warning("Could not find any VMware VM in default locations")
# look for VMX paths in the preferences file in case not all VMs are in a default directory
for key, value in pairs.items():
m = re.match(r'pref.mruVM(\d+)\.filename', key)
if m:
display_name = "pref.mruVM{}.displayName".format(m.group(1))
if display_name in pairs:
found = False
for vmware_vm in vmware_vms:
if vmware_vm["vmname"] == display_name:
found = True
if found is False:
vmware_vms.append({"vmname": pairs[display_name], "vmx_path": value})
return vmware_vms | [
"def",
"list_vms",
"(",
"self",
")",
":",
"# check for the right VMware version",
"yield",
"from",
"self",
".",
"check_vmware_version",
"(",
")",
"vmware_vms",
"=",
"[",
"]",
"inventory_path",
"=",
"self",
".",
"get_vmware_inventory_path",
"(",
")",
"if",
"os",
... | Gets VMware VM list. | [
"Gets",
"VMware",
"VM",
"list",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/__init__.py#L673-L724 | train | 221,537 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/atm_switch.py | ATMSwitch.remove_nio | def remove_nio(self, port_number):
"""
Removes the specified NIO as member of this ATM switch.
:param port_number: allocated port number
"""
if port_number not in self._nios:
raise DynamipsError("Port {} is not allocated".format(port_number))
# remove VCs mapped with the port
for source, destination in self._active_mappings.copy().items():
if len(source) == 3 and len(destination) == 3:
# remove the virtual channels mapped with this port/nio
source_port, source_vpi, source_vci = source
destination_port, destination_vpi, destination_vci = destination
if port_number == source_port:
log.info('ATM switch "{name}" [{id}]: unmapping VCC between port {source_port} VPI {source_vpi} VCI {source_vci} and port {destination_port} VPI {destination_vpi} VCI {destination_vci}'.format(name=self._name,
id=self._id,
source_port=source_port,
source_vpi=source_vpi,
source_vci=source_vci,
destination_port=destination_port,
destination_vpi=destination_vpi,
destination_vci=destination_vci))
yield from self.unmap_pvc(source_port, source_vpi, source_vci, destination_port, destination_vpi, destination_vci)
yield from self.unmap_pvc(destination_port, destination_vpi, destination_vci, source_port, source_vpi, source_vci)
else:
# remove the virtual paths mapped with this port/nio
source_port, source_vpi = source
destination_port, destination_vpi = destination
if port_number == source_port:
log.info('ATM switch "{name}" [{id}]: unmapping VPC between port {source_port} VPI {source_vpi} and port {destination_port} VPI {destination_vpi}'.format(name=self._name,
id=self._id,
source_port=source_port,
source_vpi=source_vpi,
destination_port=destination_port,
destination_vpi=destination_vpi))
yield from self.unmap_vp(source_port, source_vpi, destination_port, destination_vpi)
yield from self.unmap_vp(destination_port, destination_vpi, source_port, source_vpi)
nio = self._nios[port_number]
if isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
log.info('ATM switch "{name}" [{id}]: NIO {nio} removed from port {port}'.format(name=self._name,
id=self._id,
nio=nio,
port=port_number))
del self._nios[port_number]
return nio | python | def remove_nio(self, port_number):
"""
Removes the specified NIO as member of this ATM switch.
:param port_number: allocated port number
"""
if port_number not in self._nios:
raise DynamipsError("Port {} is not allocated".format(port_number))
# remove VCs mapped with the port
for source, destination in self._active_mappings.copy().items():
if len(source) == 3 and len(destination) == 3:
# remove the virtual channels mapped with this port/nio
source_port, source_vpi, source_vci = source
destination_port, destination_vpi, destination_vci = destination
if port_number == source_port:
log.info('ATM switch "{name}" [{id}]: unmapping VCC between port {source_port} VPI {source_vpi} VCI {source_vci} and port {destination_port} VPI {destination_vpi} VCI {destination_vci}'.format(name=self._name,
id=self._id,
source_port=source_port,
source_vpi=source_vpi,
source_vci=source_vci,
destination_port=destination_port,
destination_vpi=destination_vpi,
destination_vci=destination_vci))
yield from self.unmap_pvc(source_port, source_vpi, source_vci, destination_port, destination_vpi, destination_vci)
yield from self.unmap_pvc(destination_port, destination_vpi, destination_vci, source_port, source_vpi, source_vci)
else:
# remove the virtual paths mapped with this port/nio
source_port, source_vpi = source
destination_port, destination_vpi = destination
if port_number == source_port:
log.info('ATM switch "{name}" [{id}]: unmapping VPC between port {source_port} VPI {source_vpi} and port {destination_port} VPI {destination_vpi}'.format(name=self._name,
id=self._id,
source_port=source_port,
source_vpi=source_vpi,
destination_port=destination_port,
destination_vpi=destination_vpi))
yield from self.unmap_vp(source_port, source_vpi, destination_port, destination_vpi)
yield from self.unmap_vp(destination_port, destination_vpi, source_port, source_vpi)
nio = self._nios[port_number]
if isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
log.info('ATM switch "{name}" [{id}]: NIO {nio} removed from port {port}'.format(name=self._name,
id=self._id,
nio=nio,
port=port_number))
del self._nios[port_number]
return nio | [
"def",
"remove_nio",
"(",
"self",
",",
"port_number",
")",
":",
"if",
"port_number",
"not",
"in",
"self",
".",
"_nios",
":",
"raise",
"DynamipsError",
"(",
"\"Port {} is not allocated\"",
".",
"format",
"(",
"port_number",
")",
")",
"# remove VCs mapped with the p... | Removes the specified NIO as member of this ATM switch.
:param port_number: allocated port number | [
"Removes",
"the",
"specified",
"NIO",
"as",
"member",
"of",
"this",
"ATM",
"switch",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/atm_switch.py#L180-L230 | train | 221,538 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/atm_switch.py | ATMSwitch.map_vp | def map_vp(self, port1, vpi1, port2, vpi2):
"""
Creates a new Virtual Path connection.
:param port1: input port
:param vpi1: input vpi
:param port2: output port
:param vpi2: output vpi
"""
if port1 not in self._nios:
return
if port2 not in self._nios:
return
nio1 = self._nios[port1]
nio2 = self._nios[port2]
yield from self._hypervisor.send('atmsw create_vpc "{name}" {input_nio} {input_vpi} {output_nio} {output_vpi}'.format(name=self._name,
input_nio=nio1,
input_vpi=vpi1,
output_nio=nio2,
output_vpi=vpi2))
log.info('ATM switch "{name}" [{id}]: VPC from port {port1} VPI {vpi1} to port {port2} VPI {vpi2} created'.format(name=self._name,
id=self._id,
port1=port1,
vpi1=vpi1,
port2=port2,
vpi2=vpi2))
self._active_mappings[(port1, vpi1)] = (port2, vpi2) | python | def map_vp(self, port1, vpi1, port2, vpi2):
"""
Creates a new Virtual Path connection.
:param port1: input port
:param vpi1: input vpi
:param port2: output port
:param vpi2: output vpi
"""
if port1 not in self._nios:
return
if port2 not in self._nios:
return
nio1 = self._nios[port1]
nio2 = self._nios[port2]
yield from self._hypervisor.send('atmsw create_vpc "{name}" {input_nio} {input_vpi} {output_nio} {output_vpi}'.format(name=self._name,
input_nio=nio1,
input_vpi=vpi1,
output_nio=nio2,
output_vpi=vpi2))
log.info('ATM switch "{name}" [{id}]: VPC from port {port1} VPI {vpi1} to port {port2} VPI {vpi2} created'.format(name=self._name,
id=self._id,
port1=port1,
vpi1=vpi1,
port2=port2,
vpi2=vpi2))
self._active_mappings[(port1, vpi1)] = (port2, vpi2) | [
"def",
"map_vp",
"(",
"self",
",",
"port1",
",",
"vpi1",
",",
"port2",
",",
"vpi2",
")",
":",
"if",
"port1",
"not",
"in",
"self",
".",
"_nios",
":",
"return",
"if",
"port2",
"not",
"in",
"self",
".",
"_nios",
":",
"return",
"nio1",
"=",
"self",
"... | Creates a new Virtual Path connection.
:param port1: input port
:param vpi1: input vpi
:param port2: output port
:param vpi2: output vpi | [
"Creates",
"a",
"new",
"Virtual",
"Path",
"connection",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/atm_switch.py#L279-L311 | train | 221,539 |
GNS3/gns3-server | gns3server/web/response.py | Response.file | def file(self, path, status=200, set_content_length=True):
"""
Return a file as a response
"""
ct, encoding = mimetypes.guess_type(path)
if not ct:
ct = 'application/octet-stream'
if encoding:
self.headers[aiohttp.hdrs.CONTENT_ENCODING] = encoding
self.content_type = ct
if set_content_length:
st = os.stat(path)
self.last_modified = st.st_mtime
self.headers[aiohttp.hdrs.CONTENT_LENGTH] = str(st.st_size)
else:
self.enable_chunked_encoding()
self.set_status(status)
try:
with open(path, 'rb') as fobj:
yield from self.prepare(self._request)
while True:
data = fobj.read(4096)
if not data:
break
yield from self.write(data)
yield from self.drain()
except FileNotFoundError:
raise aiohttp.web.HTTPNotFound()
except PermissionError:
raise aiohttp.web.HTTPForbidden() | python | def file(self, path, status=200, set_content_length=True):
"""
Return a file as a response
"""
ct, encoding = mimetypes.guess_type(path)
if not ct:
ct = 'application/octet-stream'
if encoding:
self.headers[aiohttp.hdrs.CONTENT_ENCODING] = encoding
self.content_type = ct
if set_content_length:
st = os.stat(path)
self.last_modified = st.st_mtime
self.headers[aiohttp.hdrs.CONTENT_LENGTH] = str(st.st_size)
else:
self.enable_chunked_encoding()
self.set_status(status)
try:
with open(path, 'rb') as fobj:
yield from self.prepare(self._request)
while True:
data = fobj.read(4096)
if not data:
break
yield from self.write(data)
yield from self.drain()
except FileNotFoundError:
raise aiohttp.web.HTTPNotFound()
except PermissionError:
raise aiohttp.web.HTTPForbidden() | [
"def",
"file",
"(",
"self",
",",
"path",
",",
"status",
"=",
"200",
",",
"set_content_length",
"=",
"True",
")",
":",
"ct",
",",
"encoding",
"=",
"mimetypes",
".",
"guess_type",
"(",
"path",
")",
"if",
"not",
"ct",
":",
"ct",
"=",
"'application/octet-s... | Return a file as a response | [
"Return",
"a",
"file",
"as",
"a",
"response"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/web/response.py#L116-L150 | train | 221,540 |
GNS3/gns3-server | gns3server/controller/snapshot.py | Snapshot.restore | def restore(self):
"""
Restore the snapshot
"""
yield from self._project.delete_on_computes()
# We don't send close notif to clients because the close / open dance is purely internal
yield from self._project.close(ignore_notification=True)
self._project.controller.notification.emit("snapshot.restored", self.__json__())
try:
if os.path.exists(os.path.join(self._project.path, "project-files")):
shutil.rmtree(os.path.join(self._project.path, "project-files"))
with open(self._path, "rb") as f:
project = yield from import_project(self._project.controller, self._project.id, f, location=self._project.path)
except (OSError, PermissionError) as e:
raise aiohttp.web.HTTPConflict(text=str(e))
yield from project.open()
return project | python | def restore(self):
"""
Restore the snapshot
"""
yield from self._project.delete_on_computes()
# We don't send close notif to clients because the close / open dance is purely internal
yield from self._project.close(ignore_notification=True)
self._project.controller.notification.emit("snapshot.restored", self.__json__())
try:
if os.path.exists(os.path.join(self._project.path, "project-files")):
shutil.rmtree(os.path.join(self._project.path, "project-files"))
with open(self._path, "rb") as f:
project = yield from import_project(self._project.controller, self._project.id, f, location=self._project.path)
except (OSError, PermissionError) as e:
raise aiohttp.web.HTTPConflict(text=str(e))
yield from project.open()
return project | [
"def",
"restore",
"(",
"self",
")",
":",
"yield",
"from",
"self",
".",
"_project",
".",
"delete_on_computes",
"(",
")",
"# We don't send close notif to clients because the close / open dance is purely internal",
"yield",
"from",
"self",
".",
"_project",
".",
"close",
"(... | Restore the snapshot | [
"Restore",
"the",
"snapshot"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/snapshot.py#L75-L92 | train | 221,541 |
GNS3/gns3-server | gns3server/utils/get_resource.py | get_resource | def get_resource(resource_name):
"""
Return a resource in current directory or in frozen package
"""
resource_path = None
if hasattr(sys, "frozen"):
resource_path = os.path.normpath(os.path.join(os.path.dirname(sys.executable), resource_name))
elif not hasattr(sys, "frozen") and pkg_resources.resource_exists("gns3server", resource_name):
resource_path = pkg_resources.resource_filename("gns3server", resource_name)
resource_path = os.path.normpath(resource_path)
return resource_path | python | def get_resource(resource_name):
"""
Return a resource in current directory or in frozen package
"""
resource_path = None
if hasattr(sys, "frozen"):
resource_path = os.path.normpath(os.path.join(os.path.dirname(sys.executable), resource_name))
elif not hasattr(sys, "frozen") and pkg_resources.resource_exists("gns3server", resource_name):
resource_path = pkg_resources.resource_filename("gns3server", resource_name)
resource_path = os.path.normpath(resource_path)
return resource_path | [
"def",
"get_resource",
"(",
"resource_name",
")",
":",
"resource_path",
"=",
"None",
"if",
"hasattr",
"(",
"sys",
",",
"\"frozen\"",
")",
":",
"resource_path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
"."... | Return a resource in current directory or in frozen package | [
"Return",
"a",
"resource",
"in",
"current",
"directory",
"or",
"in",
"frozen",
"package"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/get_resource.py#L46-L57 | train | 221,542 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM._nvram_changed | def _nvram_changed(self, path):
"""
Called when the NVRAM file has changed
"""
log.debug("NVRAM changed: {}".format(path))
self.save_configs()
self.updated() | python | def _nvram_changed(self, path):
"""
Called when the NVRAM file has changed
"""
log.debug("NVRAM changed: {}".format(path))
self.save_configs()
self.updated() | [
"def",
"_nvram_changed",
"(",
"self",
",",
"path",
")",
":",
"log",
".",
"debug",
"(",
"\"NVRAM changed: {}\"",
".",
"format",
"(",
"path",
")",
")",
"self",
".",
"save_configs",
"(",
")",
"self",
".",
"updated",
"(",
")"
] | Called when the NVRAM file has changed | [
"Called",
"when",
"the",
"NVRAM",
"file",
"has",
"changed"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L95-L101 | train | 221,543 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM.close | def close(self):
"""
Closes this IOU VM.
"""
if not (yield from super().close()):
return False
adapters = self._ethernet_adapters + self._serial_adapters
for adapter in adapters:
if adapter is not None:
for nio in adapter.ports.values():
if nio and isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
yield from self.stop() | python | def close(self):
"""
Closes this IOU VM.
"""
if not (yield from super().close()):
return False
adapters = self._ethernet_adapters + self._serial_adapters
for adapter in adapters:
if adapter is not None:
for nio in adapter.ports.values():
if nio and isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
yield from self.stop() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"(",
"yield",
"from",
"super",
"(",
")",
".",
"close",
"(",
")",
")",
":",
"return",
"False",
"adapters",
"=",
"self",
".",
"_ethernet_adapters",
"+",
"self",
".",
"_serial_adapters",
"for",
"adapter"... | Closes this IOU VM. | [
"Closes",
"this",
"IOU",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L104-L119 | train | 221,544 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM.path | def path(self, path):
"""
Path of the IOU executable.
:param path: path to the IOU image executable
"""
self._path = self.manager.get_abs_image_path(path)
log.info('IOU "{name}" [{id}]: IOU image updated to "{path}"'.format(name=self._name, id=self._id, path=self._path)) | python | def path(self, path):
"""
Path of the IOU executable.
:param path: path to the IOU image executable
"""
self._path = self.manager.get_abs_image_path(path)
log.info('IOU "{name}" [{id}]: IOU image updated to "{path}"'.format(name=self._name, id=self._id, path=self._path)) | [
"def",
"path",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"_path",
"=",
"self",
".",
"manager",
".",
"get_abs_image_path",
"(",
"path",
")",
"log",
".",
"info",
"(",
"'IOU \"{name}\" [{id}]: IOU image updated to \"{path}\"'",
".",
"format",
"(",
"name",
... | Path of the IOU executable.
:param path: path to the IOU image executable | [
"Path",
"of",
"the",
"IOU",
"executable",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L132-L140 | train | 221,545 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM.use_default_iou_values | def use_default_iou_values(self, state):
"""
Sets if this device uses the default IOU image values.
:param state: boolean
"""
self._use_default_iou_values = state
if state:
log.info('IOU "{name}" [{id}]: uses the default IOU image values'.format(name=self._name, id=self._id))
else:
log.info('IOU "{name}" [{id}]: does not use the default IOU image values'.format(name=self._name, id=self._id)) | python | def use_default_iou_values(self, state):
"""
Sets if this device uses the default IOU image values.
:param state: boolean
"""
self._use_default_iou_values = state
if state:
log.info('IOU "{name}" [{id}]: uses the default IOU image values'.format(name=self._name, id=self._id))
else:
log.info('IOU "{name}" [{id}]: does not use the default IOU image values'.format(name=self._name, id=self._id)) | [
"def",
"use_default_iou_values",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"_use_default_iou_values",
"=",
"state",
"if",
"state",
":",
"log",
".",
"info",
"(",
"'IOU \"{name}\" [{id}]: uses the default IOU image values'",
".",
"format",
"(",
"name",
"=",
... | Sets if this device uses the default IOU image values.
:param state: boolean | [
"Sets",
"if",
"this",
"device",
"uses",
"the",
"default",
"IOU",
"image",
"values",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L153-L164 | train | 221,546 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM.update_default_iou_values | def update_default_iou_values(self):
"""
Finds the default RAM and NVRAM values for the IOU image.
"""
try:
output = yield from gns3server.utils.asyncio.subprocess_check_output(self._path, "-h", cwd=self.working_dir, stderr=True)
match = re.search("-n <n>\s+Size of nvram in Kb \(default ([0-9]+)KB\)", output)
if match:
self.nvram = int(match.group(1))
match = re.search("-m <n>\s+Megabytes of router memory \(default ([0-9]+)MB\)", output)
if match:
self.ram = int(match.group(1))
except (ValueError, OSError, subprocess.SubprocessError) as e:
log.warning("could not find default RAM and NVRAM values for {}: {}".format(os.path.basename(self._path), e)) | python | def update_default_iou_values(self):
"""
Finds the default RAM and NVRAM values for the IOU image.
"""
try:
output = yield from gns3server.utils.asyncio.subprocess_check_output(self._path, "-h", cwd=self.working_dir, stderr=True)
match = re.search("-n <n>\s+Size of nvram in Kb \(default ([0-9]+)KB\)", output)
if match:
self.nvram = int(match.group(1))
match = re.search("-m <n>\s+Megabytes of router memory \(default ([0-9]+)MB\)", output)
if match:
self.ram = int(match.group(1))
except (ValueError, OSError, subprocess.SubprocessError) as e:
log.warning("could not find default RAM and NVRAM values for {}: {}".format(os.path.basename(self._path), e)) | [
"def",
"update_default_iou_values",
"(",
"self",
")",
":",
"try",
":",
"output",
"=",
"yield",
"from",
"gns3server",
".",
"utils",
".",
"asyncio",
".",
"subprocess_check_output",
"(",
"self",
".",
"_path",
",",
"\"-h\"",
",",
"cwd",
"=",
"self",
".",
"work... | Finds the default RAM and NVRAM values for the IOU image. | [
"Finds",
"the",
"default",
"RAM",
"and",
"NVRAM",
"values",
"for",
"the",
"IOU",
"image",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L167-L181 | train | 221,547 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM._check_requirements | def _check_requirements(self):
"""
Checks the IOU image.
"""
if not self._path:
raise IOUError("IOU image is not configured")
if not os.path.isfile(self._path) or not os.path.exists(self._path):
if os.path.islink(self._path):
raise IOUError("IOU image '{}' linked to '{}' is not accessible".format(self._path, os.path.realpath(self._path)))
else:
raise IOUError("IOU image '{}' is not accessible".format(self._path))
try:
with open(self._path, "rb") as f:
# read the first 7 bytes of the file.
elf_header_start = f.read(7)
except OSError as e:
raise IOUError("Cannot read ELF header for IOU image '{}': {}".format(self._path, e))
# IOU images must start with the ELF magic number, be 32-bit or 64-bit, little endian
# and have an ELF version of 1 normal IOS image are big endian!
if elf_header_start != b'\x7fELF\x01\x01\x01' and elf_header_start != b'\x7fELF\x02\x01\x01':
raise IOUError("'{}' is not a valid IOU image".format(self._path))
if not os.access(self._path, os.X_OK):
raise IOUError("IOU image '{}' is not executable".format(self._path)) | python | def _check_requirements(self):
"""
Checks the IOU image.
"""
if not self._path:
raise IOUError("IOU image is not configured")
if not os.path.isfile(self._path) or not os.path.exists(self._path):
if os.path.islink(self._path):
raise IOUError("IOU image '{}' linked to '{}' is not accessible".format(self._path, os.path.realpath(self._path)))
else:
raise IOUError("IOU image '{}' is not accessible".format(self._path))
try:
with open(self._path, "rb") as f:
# read the first 7 bytes of the file.
elf_header_start = f.read(7)
except OSError as e:
raise IOUError("Cannot read ELF header for IOU image '{}': {}".format(self._path, e))
# IOU images must start with the ELF magic number, be 32-bit or 64-bit, little endian
# and have an ELF version of 1 normal IOS image are big endian!
if elf_header_start != b'\x7fELF\x01\x01\x01' and elf_header_start != b'\x7fELF\x02\x01\x01':
raise IOUError("'{}' is not a valid IOU image".format(self._path))
if not os.access(self._path, os.X_OK):
raise IOUError("IOU image '{}' is not executable".format(self._path)) | [
"def",
"_check_requirements",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_path",
":",
"raise",
"IOUError",
"(",
"\"IOU image is not configured\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"_path",
")",
"or",
"not",
"os... | Checks the IOU image. | [
"Checks",
"the",
"IOU",
"image",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L188-L214 | train | 221,548 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM.iourc_path | def iourc_path(self):
"""
Returns the IOURC file path.
:returns: path to IOURC
"""
iourc_path = self._config().get("iourc_path")
if not iourc_path:
# look for the iourc file in the temporary dir.
path = os.path.join(self.temporary_directory, "iourc")
if os.path.exists(path):
return path
# look for the iourc file in the user home dir.
path = os.path.join(os.path.expanduser("~/"), ".iourc")
if os.path.exists(path):
return path
# look for the iourc file in the current working dir.
path = os.path.join(self.working_dir, "iourc")
if os.path.exists(path):
return path
return iourc_path | python | def iourc_path(self):
"""
Returns the IOURC file path.
:returns: path to IOURC
"""
iourc_path = self._config().get("iourc_path")
if not iourc_path:
# look for the iourc file in the temporary dir.
path = os.path.join(self.temporary_directory, "iourc")
if os.path.exists(path):
return path
# look for the iourc file in the user home dir.
path = os.path.join(os.path.expanduser("~/"), ".iourc")
if os.path.exists(path):
return path
# look for the iourc file in the current working dir.
path = os.path.join(self.working_dir, "iourc")
if os.path.exists(path):
return path
return iourc_path | [
"def",
"iourc_path",
"(",
"self",
")",
":",
"iourc_path",
"=",
"self",
".",
"_config",
"(",
")",
".",
"get",
"(",
"\"iourc_path\"",
")",
"if",
"not",
"iourc_path",
":",
"# look for the iourc file in the temporary dir.",
"path",
"=",
"os",
".",
"path",
".",
... | Returns the IOURC file path.
:returns: path to IOURC | [
"Returns",
"the",
"IOURC",
"file",
"path",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L241-L262 | train | 221,549 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM.name | def name(self, new_name):
"""
Sets the name of this IOU VM.
:param new_name: name
"""
if self.startup_config_file:
content = self.startup_config_content
content = re.sub(r"^hostname .+$", "hostname " + new_name, content, flags=re.MULTILINE)
self.startup_config_content = content
super(IOUVM, IOUVM).name.__set__(self, new_name) | python | def name(self, new_name):
"""
Sets the name of this IOU VM.
:param new_name: name
"""
if self.startup_config_file:
content = self.startup_config_content
content = re.sub(r"^hostname .+$", "hostname " + new_name, content, flags=re.MULTILINE)
self.startup_config_content = content
super(IOUVM, IOUVM).name.__set__(self, new_name) | [
"def",
"name",
"(",
"self",
",",
"new_name",
")",
":",
"if",
"self",
".",
"startup_config_file",
":",
"content",
"=",
"self",
".",
"startup_config_content",
"content",
"=",
"re",
".",
"sub",
"(",
"r\"^hostname .+$\"",
",",
"\"hostname \"",
"+",
"new_name",
"... | Sets the name of this IOU VM.
:param new_name: name | [
"Sets",
"the",
"name",
"of",
"this",
"IOU",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L320-L332 | train | 221,550 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM._library_check | def _library_check(self):
"""
Checks for missing shared library dependencies in the IOU image.
"""
try:
output = yield from gns3server.utils.asyncio.subprocess_check_output("ldd", self._path)
except (FileNotFoundError, subprocess.SubprocessError) as e:
log.warn("Could not determine the shared library dependencies for {}: {}".format(self._path, e))
return
p = re.compile("([\.\w]+)\s=>\s+not found")
missing_libs = p.findall(output)
if missing_libs:
raise IOUError("The following shared library dependencies cannot be found for IOU image {}: {}".format(self._path,
", ".join(missing_libs))) | python | def _library_check(self):
"""
Checks for missing shared library dependencies in the IOU image.
"""
try:
output = yield from gns3server.utils.asyncio.subprocess_check_output("ldd", self._path)
except (FileNotFoundError, subprocess.SubprocessError) as e:
log.warn("Could not determine the shared library dependencies for {}: {}".format(self._path, e))
return
p = re.compile("([\.\w]+)\s=>\s+not found")
missing_libs = p.findall(output)
if missing_libs:
raise IOUError("The following shared library dependencies cannot be found for IOU image {}: {}".format(self._path,
", ".join(missing_libs))) | [
"def",
"_library_check",
"(",
"self",
")",
":",
"try",
":",
"output",
"=",
"yield",
"from",
"gns3server",
".",
"utils",
".",
"asyncio",
".",
"subprocess_check_output",
"(",
"\"ldd\"",
",",
"self",
".",
"_path",
")",
"except",
"(",
"FileNotFoundError",
",",
... | Checks for missing shared library dependencies in the IOU image. | [
"Checks",
"for",
"missing",
"shared",
"library",
"dependencies",
"in",
"the",
"IOU",
"image",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L364-L379 | train | 221,551 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM._nvram_file | def _nvram_file(self):
"""
Path to the nvram file
"""
return os.path.join(self.working_dir, "nvram_{:05d}".format(self.application_id)) | python | def _nvram_file(self):
"""
Path to the nvram file
"""
return os.path.join(self.working_dir, "nvram_{:05d}".format(self.application_id)) | [
"def",
"_nvram_file",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"working_dir",
",",
"\"nvram_{:05d}\"",
".",
"format",
"(",
"self",
".",
"application_id",
")",
")"
] | Path to the nvram file | [
"Path",
"to",
"the",
"nvram",
"file"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L441-L445 | train | 221,552 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM._push_configs_to_nvram | def _push_configs_to_nvram(self):
"""
Push the startup-config and private-config content to the NVRAM.
"""
startup_config_content = self.startup_config_content
if startup_config_content:
nvram_file = self._nvram_file()
try:
if not os.path.exists(nvram_file):
open(nvram_file, "a").close()
nvram_content = None
else:
with open(nvram_file, "rb") as file:
nvram_content = file.read()
except OSError as e:
raise IOUError("Cannot read nvram file {}: {}".format(nvram_file, e))
startup_config_content = startup_config_content.encode("utf-8")
private_config_content = self.private_config_content
if private_config_content is not None:
private_config_content = private_config_content.encode("utf-8")
try:
nvram_content = nvram_import(nvram_content, startup_config_content, private_config_content, self.nvram)
except ValueError as e:
raise IOUError("Cannot push configs to nvram {}: {}".format(nvram_file, e))
try:
with open(nvram_file, "wb") as file:
file.write(nvram_content)
except OSError as e:
raise IOUError("Cannot write nvram file {}: {}".format(nvram_file, e)) | python | def _push_configs_to_nvram(self):
"""
Push the startup-config and private-config content to the NVRAM.
"""
startup_config_content = self.startup_config_content
if startup_config_content:
nvram_file = self._nvram_file()
try:
if not os.path.exists(nvram_file):
open(nvram_file, "a").close()
nvram_content = None
else:
with open(nvram_file, "rb") as file:
nvram_content = file.read()
except OSError as e:
raise IOUError("Cannot read nvram file {}: {}".format(nvram_file, e))
startup_config_content = startup_config_content.encode("utf-8")
private_config_content = self.private_config_content
if private_config_content is not None:
private_config_content = private_config_content.encode("utf-8")
try:
nvram_content = nvram_import(nvram_content, startup_config_content, private_config_content, self.nvram)
except ValueError as e:
raise IOUError("Cannot push configs to nvram {}: {}".format(nvram_file, e))
try:
with open(nvram_file, "wb") as file:
file.write(nvram_content)
except OSError as e:
raise IOUError("Cannot write nvram file {}: {}".format(nvram_file, e)) | [
"def",
"_push_configs_to_nvram",
"(",
"self",
")",
":",
"startup_config_content",
"=",
"self",
".",
"startup_config_content",
"if",
"startup_config_content",
":",
"nvram_file",
"=",
"self",
".",
"_nvram_file",
"(",
")",
"try",
":",
"if",
"not",
"os",
".",
"path"... | Push the startup-config and private-config content to the NVRAM. | [
"Push",
"the",
"startup",
"-",
"config",
"and",
"private",
"-",
"config",
"content",
"to",
"the",
"NVRAM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L447-L477 | train | 221,553 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM.start | def start(self):
"""
Starts the IOU process.
"""
self._check_requirements()
if not self.is_running():
yield from self._library_check()
try:
self._rename_nvram_file()
except OSError as e:
raise IOUError("Could not rename nvram files: {}".format(e))
iourc_path = self.iourc_path
if not iourc_path:
raise IOUError("Could not find an iourc file (IOU license)")
if not os.path.isfile(iourc_path):
raise IOUError("The iourc path '{}' is not a regular file".format(iourc_path))
yield from self._check_iou_licence()
yield from self._start_ubridge()
self._create_netmap_config()
if self.use_default_iou_values:
# make sure we have the default nvram amount to correctly push the configs
yield from self.update_default_iou_values()
self._push_configs_to_nvram()
# check if there is enough RAM to run
self.check_available_ram(self.ram)
self._nvram_watcher = FileWatcher(self._nvram_file(), self._nvram_changed, delay=2)
# created a environment variable pointing to the iourc file.
env = os.environ.copy()
if "IOURC" not in os.environ:
env["IOURC"] = iourc_path
command = yield from self._build_command()
try:
log.info("Starting IOU: {}".format(command))
self.command_line = ' '.join(command)
self._iou_process = yield from asyncio.create_subprocess_exec(
*command,
stdout=asyncio.subprocess.PIPE,
stdin=asyncio.subprocess.PIPE,
stderr=subprocess.STDOUT,
cwd=self.working_dir,
env=env)
log.info("IOU instance {} started PID={}".format(self._id, self._iou_process.pid))
self._started = True
self.status = "started"
callback = functools.partial(self._termination_callback, "IOU")
gns3server.utils.asyncio.monitor_process(self._iou_process, callback)
except FileNotFoundError as e:
raise IOUError("Could not start IOU: {}: 32-bit binary support is probably not installed".format(e))
except (OSError, subprocess.SubprocessError) as e:
iou_stdout = self.read_iou_stdout()
log.error("Could not start IOU {}: {}\n{}".format(self._path, e, iou_stdout))
raise IOUError("Could not start IOU {}: {}\n{}".format(self._path, e, iou_stdout))
server = AsyncioTelnetServer(reader=self._iou_process.stdout, writer=self._iou_process.stdin, binary=True, echo=True)
self._telnet_server = yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console)
# configure networking support
yield from self._networking() | python | def start(self):
"""
Starts the IOU process.
"""
self._check_requirements()
if not self.is_running():
yield from self._library_check()
try:
self._rename_nvram_file()
except OSError as e:
raise IOUError("Could not rename nvram files: {}".format(e))
iourc_path = self.iourc_path
if not iourc_path:
raise IOUError("Could not find an iourc file (IOU license)")
if not os.path.isfile(iourc_path):
raise IOUError("The iourc path '{}' is not a regular file".format(iourc_path))
yield from self._check_iou_licence()
yield from self._start_ubridge()
self._create_netmap_config()
if self.use_default_iou_values:
# make sure we have the default nvram amount to correctly push the configs
yield from self.update_default_iou_values()
self._push_configs_to_nvram()
# check if there is enough RAM to run
self.check_available_ram(self.ram)
self._nvram_watcher = FileWatcher(self._nvram_file(), self._nvram_changed, delay=2)
# created a environment variable pointing to the iourc file.
env = os.environ.copy()
if "IOURC" not in os.environ:
env["IOURC"] = iourc_path
command = yield from self._build_command()
try:
log.info("Starting IOU: {}".format(command))
self.command_line = ' '.join(command)
self._iou_process = yield from asyncio.create_subprocess_exec(
*command,
stdout=asyncio.subprocess.PIPE,
stdin=asyncio.subprocess.PIPE,
stderr=subprocess.STDOUT,
cwd=self.working_dir,
env=env)
log.info("IOU instance {} started PID={}".format(self._id, self._iou_process.pid))
self._started = True
self.status = "started"
callback = functools.partial(self._termination_callback, "IOU")
gns3server.utils.asyncio.monitor_process(self._iou_process, callback)
except FileNotFoundError as e:
raise IOUError("Could not start IOU: {}: 32-bit binary support is probably not installed".format(e))
except (OSError, subprocess.SubprocessError) as e:
iou_stdout = self.read_iou_stdout()
log.error("Could not start IOU {}: {}\n{}".format(self._path, e, iou_stdout))
raise IOUError("Could not start IOU {}: {}\n{}".format(self._path, e, iou_stdout))
server = AsyncioTelnetServer(reader=self._iou_process.stdout, writer=self._iou_process.stdin, binary=True, echo=True)
self._telnet_server = yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console)
# configure networking support
yield from self._networking() | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_check_requirements",
"(",
")",
"if",
"not",
"self",
".",
"is_running",
"(",
")",
":",
"yield",
"from",
"self",
".",
"_library_check",
"(",
")",
"try",
":",
"self",
".",
"_rename_nvram_file",
"(",
")... | Starts the IOU process. | [
"Starts",
"the",
"IOU",
"process",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L480-L547 | train | 221,554 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM._networking | def _networking(self):
"""
Configures the IOL bridge in uBridge.
"""
bridge_name = "IOL-BRIDGE-{}".format(self.application_id + 512)
try:
# delete any previous bridge if it exists
yield from self._ubridge_send("iol_bridge delete {name}".format(name=bridge_name))
except UbridgeError:
pass
yield from self._ubridge_send("iol_bridge create {name} {bridge_id}".format(name=bridge_name, bridge_id=self.application_id + 512))
bay_id = 0
for adapter in self._adapters:
unit_id = 0
for unit in adapter.ports.keys():
nio = adapter.get_nio(unit)
if nio and isinstance(nio, NIOUDP):
yield from self._ubridge_send("iol_bridge add_nio_udp {name} {iol_id} {bay} {unit} {lport} {rhost} {rport}".format(name=bridge_name,
iol_id=self.application_id,
bay=bay_id,
unit=unit_id,
lport=nio.lport,
rhost=nio.rhost,
rport=nio.rport))
if nio.capturing:
yield from self._ubridge_send('iol_bridge start_capture {name} "{output_file}" {data_link_type}'.format(name=bridge_name,
output_file=nio.pcap_output_file,
data_link_type=re.sub("^DLT_", "", nio.pcap_data_link_type)))
yield from self._ubridge_apply_filters(bay_id, unit_id, nio.filters)
unit_id += 1
bay_id += 1
yield from self._ubridge_send("iol_bridge start {name}".format(name=bridge_name)) | python | def _networking(self):
"""
Configures the IOL bridge in uBridge.
"""
bridge_name = "IOL-BRIDGE-{}".format(self.application_id + 512)
try:
# delete any previous bridge if it exists
yield from self._ubridge_send("iol_bridge delete {name}".format(name=bridge_name))
except UbridgeError:
pass
yield from self._ubridge_send("iol_bridge create {name} {bridge_id}".format(name=bridge_name, bridge_id=self.application_id + 512))
bay_id = 0
for adapter in self._adapters:
unit_id = 0
for unit in adapter.ports.keys():
nio = adapter.get_nio(unit)
if nio and isinstance(nio, NIOUDP):
yield from self._ubridge_send("iol_bridge add_nio_udp {name} {iol_id} {bay} {unit} {lport} {rhost} {rport}".format(name=bridge_name,
iol_id=self.application_id,
bay=bay_id,
unit=unit_id,
lport=nio.lport,
rhost=nio.rhost,
rport=nio.rport))
if nio.capturing:
yield from self._ubridge_send('iol_bridge start_capture {name} "{output_file}" {data_link_type}'.format(name=bridge_name,
output_file=nio.pcap_output_file,
data_link_type=re.sub("^DLT_", "", nio.pcap_data_link_type)))
yield from self._ubridge_apply_filters(bay_id, unit_id, nio.filters)
unit_id += 1
bay_id += 1
yield from self._ubridge_send("iol_bridge start {name}".format(name=bridge_name)) | [
"def",
"_networking",
"(",
"self",
")",
":",
"bridge_name",
"=",
"\"IOL-BRIDGE-{}\"",
".",
"format",
"(",
"self",
".",
"application_id",
"+",
"512",
")",
"try",
":",
"# delete any previous bridge if it exists",
"yield",
"from",
"self",
".",
"_ubridge_send",
"(",
... | Configures the IOL bridge in uBridge. | [
"Configures",
"the",
"IOL",
"bridge",
"in",
"uBridge",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L550-L585 | train | 221,555 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM._rename_nvram_file | def _rename_nvram_file(self):
"""
Before starting the VM, rename the nvram and vlan.dat files with the correct IOU application identifier.
"""
destination = self._nvram_file()
for file_path in glob.glob(os.path.join(glob.escape(self.working_dir), "nvram_*")):
shutil.move(file_path, destination)
destination = os.path.join(self.working_dir, "vlan.dat-{:05d}".format(self.application_id))
for file_path in glob.glob(os.path.join(glob.escape(self.working_dir), "vlan.dat-*")):
shutil.move(file_path, destination) | python | def _rename_nvram_file(self):
"""
Before starting the VM, rename the nvram and vlan.dat files with the correct IOU application identifier.
"""
destination = self._nvram_file()
for file_path in glob.glob(os.path.join(glob.escape(self.working_dir), "nvram_*")):
shutil.move(file_path, destination)
destination = os.path.join(self.working_dir, "vlan.dat-{:05d}".format(self.application_id))
for file_path in glob.glob(os.path.join(glob.escape(self.working_dir), "vlan.dat-*")):
shutil.move(file_path, destination) | [
"def",
"_rename_nvram_file",
"(",
"self",
")",
":",
"destination",
"=",
"self",
".",
"_nvram_file",
"(",
")",
"for",
"file_path",
"in",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"glob",
".",
"escape",
"(",
"self",
".",
"working_dir... | Before starting the VM, rename the nvram and vlan.dat files with the correct IOU application identifier. | [
"Before",
"starting",
"the",
"VM",
"rename",
"the",
"nvram",
"and",
"vlan",
".",
"dat",
"files",
"with",
"the",
"correct",
"IOU",
"application",
"identifier",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L608-L618 | train | 221,556 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM.stop | def stop(self):
"""
Stops the IOU process.
"""
yield from self._stop_ubridge()
if self._nvram_watcher:
self._nvram_watcher.close()
self._nvram_watcher = None
if self._telnet_server:
self._telnet_server.close()
self._telnet_server = None
if self.is_running():
self._terminate_process_iou()
if self._iou_process.returncode is None:
try:
yield from gns3server.utils.asyncio.wait_for_process_termination(self._iou_process, timeout=3)
except asyncio.TimeoutError:
if self._iou_process.returncode is None:
log.warning("IOU process {} is still running... killing it".format(self._iou_process.pid))
try:
self._iou_process.kill()
except ProcessLookupError:
pass
self._iou_process = None
self._started = False
self.save_configs() | python | def stop(self):
"""
Stops the IOU process.
"""
yield from self._stop_ubridge()
if self._nvram_watcher:
self._nvram_watcher.close()
self._nvram_watcher = None
if self._telnet_server:
self._telnet_server.close()
self._telnet_server = None
if self.is_running():
self._terminate_process_iou()
if self._iou_process.returncode is None:
try:
yield from gns3server.utils.asyncio.wait_for_process_termination(self._iou_process, timeout=3)
except asyncio.TimeoutError:
if self._iou_process.returncode is None:
log.warning("IOU process {} is still running... killing it".format(self._iou_process.pid))
try:
self._iou_process.kill()
except ProcessLookupError:
pass
self._iou_process = None
self._started = False
self.save_configs() | [
"def",
"stop",
"(",
"self",
")",
":",
"yield",
"from",
"self",
".",
"_stop_ubridge",
"(",
")",
"if",
"self",
".",
"_nvram_watcher",
":",
"self",
".",
"_nvram_watcher",
".",
"close",
"(",
")",
"self",
".",
"_nvram_watcher",
"=",
"None",
"if",
"self",
".... | Stops the IOU process. | [
"Stops",
"the",
"IOU",
"process",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L621-L650 | train | 221,557 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM._terminate_process_iou | def _terminate_process_iou(self):
"""
Terminate the IOU process if running
"""
if self._iou_process:
log.info('Stopping IOU process for IOU VM "{}" PID={}'.format(self.name, self._iou_process.pid))
try:
self._iou_process.terminate()
# Sometime the process can already be dead when we garbage collect
except ProcessLookupError:
pass
self._started = False
self.status = "stopped" | python | def _terminate_process_iou(self):
"""
Terminate the IOU process if running
"""
if self._iou_process:
log.info('Stopping IOU process for IOU VM "{}" PID={}'.format(self.name, self._iou_process.pid))
try:
self._iou_process.terminate()
# Sometime the process can already be dead when we garbage collect
except ProcessLookupError:
pass
self._started = False
self.status = "stopped" | [
"def",
"_terminate_process_iou",
"(",
"self",
")",
":",
"if",
"self",
".",
"_iou_process",
":",
"log",
".",
"info",
"(",
"'Stopping IOU process for IOU VM \"{}\" PID={}'",
".",
"format",
"(",
"self",
".",
"name",
",",
"self",
".",
"_iou_process",
".",
"pid",
"... | Terminate the IOU process if running | [
"Terminate",
"the",
"IOU",
"process",
"if",
"running"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L652-L665 | train | 221,558 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM._create_netmap_config | def _create_netmap_config(self):
"""
Creates the NETMAP file.
"""
netmap_path = os.path.join(self.working_dir, "NETMAP")
try:
with open(netmap_path, "w", encoding="utf-8") as f:
for bay in range(0, 16):
for unit in range(0, 4):
f.write("{ubridge_id}:{bay}/{unit}{iou_id:>5d}:{bay}/{unit}\n".format(ubridge_id=str(self.application_id + 512),
bay=bay,
unit=unit,
iou_id=self.application_id))
log.info("IOU {name} [id={id}]: NETMAP file created".format(name=self._name,
id=self._id))
except OSError as e:
raise IOUError("Could not create {}: {}".format(netmap_path, e)) | python | def _create_netmap_config(self):
"""
Creates the NETMAP file.
"""
netmap_path = os.path.join(self.working_dir, "NETMAP")
try:
with open(netmap_path, "w", encoding="utf-8") as f:
for bay in range(0, 16):
for unit in range(0, 4):
f.write("{ubridge_id}:{bay}/{unit}{iou_id:>5d}:{bay}/{unit}\n".format(ubridge_id=str(self.application_id + 512),
bay=bay,
unit=unit,
iou_id=self.application_id))
log.info("IOU {name} [id={id}]: NETMAP file created".format(name=self._name,
id=self._id))
except OSError as e:
raise IOUError("Could not create {}: {}".format(netmap_path, e)) | [
"def",
"_create_netmap_config",
"(",
"self",
")",
":",
"netmap_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"working_dir",
",",
"\"NETMAP\"",
")",
"try",
":",
"with",
"open",
"(",
"netmap_path",
",",
"\"w\"",
",",
"encoding",
"=",
"\"utf... | Creates the NETMAP file. | [
"Creates",
"the",
"NETMAP",
"file",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L687-L704 | train | 221,559 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM.read_iou_stdout | def read_iou_stdout(self):
"""
Reads the standard output of the IOU process.
Only use when the process has been stopped or has crashed.
"""
output = ""
if self._iou_stdout_file:
try:
with open(self._iou_stdout_file, "rb") as file:
output = file.read().decode("utf-8", errors="replace")
except OSError as e:
log.warn("could not read {}: {}".format(self._iou_stdout_file, e))
return output | python | def read_iou_stdout(self):
"""
Reads the standard output of the IOU process.
Only use when the process has been stopped or has crashed.
"""
output = ""
if self._iou_stdout_file:
try:
with open(self._iou_stdout_file, "rb") as file:
output = file.read().decode("utf-8", errors="replace")
except OSError as e:
log.warn("could not read {}: {}".format(self._iou_stdout_file, e))
return output | [
"def",
"read_iou_stdout",
"(",
"self",
")",
":",
"output",
"=",
"\"\"",
"if",
"self",
".",
"_iou_stdout_file",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"_iou_stdout_file",
",",
"\"rb\"",
")",
"as",
"file",
":",
"output",
"=",
"file",
".",
"re... | Reads the standard output of the IOU process.
Only use when the process has been stopped or has crashed. | [
"Reads",
"the",
"standard",
"output",
"of",
"the",
"IOU",
"process",
".",
"Only",
"use",
"when",
"the",
"process",
"has",
"been",
"stopped",
"or",
"has",
"crashed",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L756-L769 | train | 221,560 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM.ethernet_adapters | def ethernet_adapters(self, ethernet_adapters):
"""
Sets the number of Ethernet adapters for this IOU VM.
:param ethernet_adapters: number of adapters
"""
self._ethernet_adapters.clear()
for _ in range(0, ethernet_adapters):
self._ethernet_adapters.append(EthernetAdapter(interfaces=4))
log.info('IOU "{name}" [{id}]: number of Ethernet adapters changed to {adapters}'.format(name=self._name,
id=self._id,
adapters=len(self._ethernet_adapters)))
self._adapters = self._ethernet_adapters + self._serial_adapters | python | def ethernet_adapters(self, ethernet_adapters):
"""
Sets the number of Ethernet adapters for this IOU VM.
:param ethernet_adapters: number of adapters
"""
self._ethernet_adapters.clear()
for _ in range(0, ethernet_adapters):
self._ethernet_adapters.append(EthernetAdapter(interfaces=4))
log.info('IOU "{name}" [{id}]: number of Ethernet adapters changed to {adapters}'.format(name=self._name,
id=self._id,
adapters=len(self._ethernet_adapters)))
self._adapters = self._ethernet_adapters + self._serial_adapters | [
"def",
"ethernet_adapters",
"(",
"self",
",",
"ethernet_adapters",
")",
":",
"self",
".",
"_ethernet_adapters",
".",
"clear",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"0",
",",
"ethernet_adapters",
")",
":",
"self",
".",
"_ethernet_adapters",
".",
"append",... | Sets the number of Ethernet adapters for this IOU VM.
:param ethernet_adapters: number of adapters | [
"Sets",
"the",
"number",
"of",
"Ethernet",
"adapters",
"for",
"this",
"IOU",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L786-L801 | train | 221,561 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM.serial_adapters | def serial_adapters(self, serial_adapters):
"""
Sets the number of Serial adapters for this IOU VM.
:param serial_adapters: number of adapters
"""
self._serial_adapters.clear()
for _ in range(0, serial_adapters):
self._serial_adapters.append(SerialAdapter(interfaces=4))
log.info('IOU "{name}" [{id}]: number of Serial adapters changed to {adapters}'.format(name=self._name,
id=self._id,
adapters=len(self._serial_adapters)))
self._adapters = self._ethernet_adapters + self._serial_adapters | python | def serial_adapters(self, serial_adapters):
"""
Sets the number of Serial adapters for this IOU VM.
:param serial_adapters: number of adapters
"""
self._serial_adapters.clear()
for _ in range(0, serial_adapters):
self._serial_adapters.append(SerialAdapter(interfaces=4))
log.info('IOU "{name}" [{id}]: number of Serial adapters changed to {adapters}'.format(name=self._name,
id=self._id,
adapters=len(self._serial_adapters)))
self._adapters = self._ethernet_adapters + self._serial_adapters | [
"def",
"serial_adapters",
"(",
"self",
",",
"serial_adapters",
")",
":",
"self",
".",
"_serial_adapters",
".",
"clear",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"0",
",",
"serial_adapters",
")",
":",
"self",
".",
"_serial_adapters",
".",
"append",
"(",
... | Sets the number of Serial adapters for this IOU VM.
:param serial_adapters: number of adapters | [
"Sets",
"the",
"number",
"of",
"Serial",
"adapters",
"for",
"this",
"IOU",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L814-L829 | train | 221,562 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM.adapter_add_nio_binding | def adapter_add_nio_binding(self, adapter_number, port_number, nio):
"""
Adds a adapter NIO binding.
:param adapter_number: adapter number
:param port_number: port number
:param nio: NIO instance to add to the adapter/port
"""
try:
adapter = self._adapters[adapter_number]
except IndexError:
raise IOUError('Adapter {adapter_number} does not exist for IOU "{name}"'.format(name=self._name,
adapter_number=adapter_number))
if not adapter.port_exists(port_number):
raise IOUError("Port {port_number} does not exist in adapter {adapter}".format(adapter=adapter,
port_number=port_number))
adapter.add_nio(port_number, nio)
log.info('IOU "{name}" [{id}]: {nio} added to {adapter_number}/{port_number}'.format(name=self._name,
id=self._id,
nio=nio,
adapter_number=adapter_number,
port_number=port_number))
if self.ubridge:
bridge_name = "IOL-BRIDGE-{}".format(self.application_id + 512)
yield from self._ubridge_send("iol_bridge add_nio_udp {name} {iol_id} {bay} {unit} {lport} {rhost} {rport}".format(name=bridge_name,
iol_id=self.application_id,
bay=adapter_number,
unit=port_number,
lport=nio.lport,
rhost=nio.rhost,
rport=nio.rport))
yield from self._ubridge_apply_filters(adapter_number, port_number, nio.filters) | python | def adapter_add_nio_binding(self, adapter_number, port_number, nio):
"""
Adds a adapter NIO binding.
:param adapter_number: adapter number
:param port_number: port number
:param nio: NIO instance to add to the adapter/port
"""
try:
adapter = self._adapters[adapter_number]
except IndexError:
raise IOUError('Adapter {adapter_number} does not exist for IOU "{name}"'.format(name=self._name,
adapter_number=adapter_number))
if not adapter.port_exists(port_number):
raise IOUError("Port {port_number} does not exist in adapter {adapter}".format(adapter=adapter,
port_number=port_number))
adapter.add_nio(port_number, nio)
log.info('IOU "{name}" [{id}]: {nio} added to {adapter_number}/{port_number}'.format(name=self._name,
id=self._id,
nio=nio,
adapter_number=adapter_number,
port_number=port_number))
if self.ubridge:
bridge_name = "IOL-BRIDGE-{}".format(self.application_id + 512)
yield from self._ubridge_send("iol_bridge add_nio_udp {name} {iol_id} {bay} {unit} {lport} {rhost} {rport}".format(name=bridge_name,
iol_id=self.application_id,
bay=adapter_number,
unit=port_number,
lport=nio.lport,
rhost=nio.rhost,
rport=nio.rport))
yield from self._ubridge_apply_filters(adapter_number, port_number, nio.filters) | [
"def",
"adapter_add_nio_binding",
"(",
"self",
",",
"adapter_number",
",",
"port_number",
",",
"nio",
")",
":",
"try",
":",
"adapter",
"=",
"self",
".",
"_adapters",
"[",
"adapter_number",
"]",
"except",
"IndexError",
":",
"raise",
"IOUError",
"(",
"'Adapter {... | Adds a adapter NIO binding.
:param adapter_number: adapter number
:param port_number: port number
:param nio: NIO instance to add to the adapter/port | [
"Adds",
"a",
"adapter",
"NIO",
"binding",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L832-L867 | train | 221,563 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM._ubridge_apply_filters | def _ubridge_apply_filters(self, adapter_number, port_number, filters):
"""
Apply filter like rate limiting
:param adapter_number: adapter number
:param port_number: port number
:param filters: Array of filter dictionnary
"""
bridge_name = "IOL-BRIDGE-{}".format(self.application_id + 512)
location = '{bridge_name} {bay} {unit}'.format(
bridge_name=bridge_name,
bay=adapter_number,
unit=port_number)
yield from self._ubridge_send('iol_bridge reset_packet_filters ' + location)
for filter in self._build_filter_list(filters):
cmd = 'iol_bridge add_packet_filter {} {}'.format(
location,
filter)
yield from self._ubridge_send(cmd) | python | def _ubridge_apply_filters(self, adapter_number, port_number, filters):
"""
Apply filter like rate limiting
:param adapter_number: adapter number
:param port_number: port number
:param filters: Array of filter dictionnary
"""
bridge_name = "IOL-BRIDGE-{}".format(self.application_id + 512)
location = '{bridge_name} {bay} {unit}'.format(
bridge_name=bridge_name,
bay=adapter_number,
unit=port_number)
yield from self._ubridge_send('iol_bridge reset_packet_filters ' + location)
for filter in self._build_filter_list(filters):
cmd = 'iol_bridge add_packet_filter {} {}'.format(
location,
filter)
yield from self._ubridge_send(cmd) | [
"def",
"_ubridge_apply_filters",
"(",
"self",
",",
"adapter_number",
",",
"port_number",
",",
"filters",
")",
":",
"bridge_name",
"=",
"\"IOL-BRIDGE-{}\"",
".",
"format",
"(",
"self",
".",
"application_id",
"+",
"512",
")",
"location",
"=",
"'{bridge_name} {bay} {... | Apply filter like rate limiting
:param adapter_number: adapter number
:param port_number: port number
:param filters: Array of filter dictionnary | [
"Apply",
"filter",
"like",
"rate",
"limiting"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L883-L901 | train | 221,564 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM.l1_keepalives | def l1_keepalives(self, state):
"""
Enables or disables layer 1 keepalive messages.
:param state: boolean
"""
self._l1_keepalives = state
if state:
log.info('IOU "{name}" [{id}]: has activated layer 1 keepalive messages'.format(name=self._name, id=self._id))
else:
log.info('IOU "{name}" [{id}]: has deactivated layer 1 keepalive messages'.format(name=self._name, id=self._id)) | python | def l1_keepalives(self, state):
"""
Enables or disables layer 1 keepalive messages.
:param state: boolean
"""
self._l1_keepalives = state
if state:
log.info('IOU "{name}" [{id}]: has activated layer 1 keepalive messages'.format(name=self._name, id=self._id))
else:
log.info('IOU "{name}" [{id}]: has deactivated layer 1 keepalive messages'.format(name=self._name, id=self._id)) | [
"def",
"l1_keepalives",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"_l1_keepalives",
"=",
"state",
"if",
"state",
":",
"log",
".",
"info",
"(",
"'IOU \"{name}\" [{id}]: has activated layer 1 keepalive messages'",
".",
"format",
"(",
"name",
"=",
"self",
"... | Enables or disables layer 1 keepalive messages.
:param state: boolean | [
"Enables",
"or",
"disables",
"layer",
"1",
"keepalive",
"messages",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L952-L963 | train | 221,565 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM._enable_l1_keepalives | def _enable_l1_keepalives(self, command):
"""
Enables L1 keepalive messages if supported.
:param command: command line
"""
env = os.environ.copy()
if "IOURC" not in os.environ:
env["IOURC"] = self.iourc_path
try:
output = yield from gns3server.utils.asyncio.subprocess_check_output(self._path, "-h", cwd=self.working_dir, env=env, stderr=True)
if re.search("-l\s+Enable Layer 1 keepalive messages", output):
command.extend(["-l"])
else:
raise IOUError("layer 1 keepalive messages are not supported by {}".format(os.path.basename(self._path)))
except (OSError, subprocess.SubprocessError) as e:
log.warning("could not determine if layer 1 keepalive messages are supported by {}: {}".format(os.path.basename(self._path), e)) | python | def _enable_l1_keepalives(self, command):
"""
Enables L1 keepalive messages if supported.
:param command: command line
"""
env = os.environ.copy()
if "IOURC" not in os.environ:
env["IOURC"] = self.iourc_path
try:
output = yield from gns3server.utils.asyncio.subprocess_check_output(self._path, "-h", cwd=self.working_dir, env=env, stderr=True)
if re.search("-l\s+Enable Layer 1 keepalive messages", output):
command.extend(["-l"])
else:
raise IOUError("layer 1 keepalive messages are not supported by {}".format(os.path.basename(self._path)))
except (OSError, subprocess.SubprocessError) as e:
log.warning("could not determine if layer 1 keepalive messages are supported by {}: {}".format(os.path.basename(self._path), e)) | [
"def",
"_enable_l1_keepalives",
"(",
"self",
",",
"command",
")",
":",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"if",
"\"IOURC\"",
"not",
"in",
"os",
".",
"environ",
":",
"env",
"[",
"\"IOURC\"",
"]",
"=",
"self",
".",
"iourc_path",
"... | Enables L1 keepalive messages if supported.
:param command: command line | [
"Enables",
"L1",
"keepalive",
"messages",
"if",
"supported",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L966-L983 | train | 221,566 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM.startup_config_content | def startup_config_content(self):
"""
Returns the content of the current startup-config file.
"""
config_file = self.startup_config_file
if config_file is None:
return None
try:
with open(config_file, "rb") as f:
return f.read().decode("utf-8", errors="replace")
except OSError as e:
raise IOUError("Can't read startup-config file '{}': {}".format(config_file, e)) | python | def startup_config_content(self):
"""
Returns the content of the current startup-config file.
"""
config_file = self.startup_config_file
if config_file is None:
return None
try:
with open(config_file, "rb") as f:
return f.read().decode("utf-8", errors="replace")
except OSError as e:
raise IOUError("Can't read startup-config file '{}': {}".format(config_file, e)) | [
"def",
"startup_config_content",
"(",
"self",
")",
":",
"config_file",
"=",
"self",
".",
"startup_config_file",
"if",
"config_file",
"is",
"None",
":",
"return",
"None",
"try",
":",
"with",
"open",
"(",
"config_file",
",",
"\"rb\"",
")",
"as",
"f",
":",
"r... | Returns the content of the current startup-config file. | [
"Returns",
"the",
"content",
"of",
"the",
"current",
"startup",
"-",
"config",
"file",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L986-L999 | train | 221,567 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM.startup_config_content | def startup_config_content(self, startup_config):
"""
Update the startup config
:param startup_config: content of the startup configuration file
"""
try:
startup_config_path = os.path.join(self.working_dir, "startup-config.cfg")
if startup_config is None:
startup_config = ''
# We disallow erasing the startup config file
if len(startup_config) == 0 and os.path.exists(startup_config_path):
return
with open(startup_config_path, 'w+', encoding='utf-8') as f:
if len(startup_config) == 0:
f.write('')
else:
startup_config = startup_config.replace("%h", self._name)
f.write(startup_config)
vlan_file = os.path.join(self.working_dir, "vlan.dat-{:05d}".format(self.application_id))
if os.path.exists(vlan_file):
try:
os.remove(vlan_file)
except OSError as e:
log.error("Could not delete VLAN file '{}': {}".format(vlan_file, e))
except OSError as e:
raise IOUError("Can't write startup-config file '{}': {}".format(startup_config_path, e)) | python | def startup_config_content(self, startup_config):
"""
Update the startup config
:param startup_config: content of the startup configuration file
"""
try:
startup_config_path = os.path.join(self.working_dir, "startup-config.cfg")
if startup_config is None:
startup_config = ''
# We disallow erasing the startup config file
if len(startup_config) == 0 and os.path.exists(startup_config_path):
return
with open(startup_config_path, 'w+', encoding='utf-8') as f:
if len(startup_config) == 0:
f.write('')
else:
startup_config = startup_config.replace("%h", self._name)
f.write(startup_config)
vlan_file = os.path.join(self.working_dir, "vlan.dat-{:05d}".format(self.application_id))
if os.path.exists(vlan_file):
try:
os.remove(vlan_file)
except OSError as e:
log.error("Could not delete VLAN file '{}': {}".format(vlan_file, e))
except OSError as e:
raise IOUError("Can't write startup-config file '{}': {}".format(startup_config_path, e)) | [
"def",
"startup_config_content",
"(",
"self",
",",
"startup_config",
")",
":",
"try",
":",
"startup_config_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"working_dir",
",",
"\"startup-config.cfg\"",
")",
"if",
"startup_config",
"is",
"None",
":... | Update the startup config
:param startup_config: content of the startup configuration file | [
"Update",
"the",
"startup",
"config"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L1002-L1034 | train | 221,568 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM.private_config_content | def private_config_content(self):
"""
Returns the content of the current private-config file.
"""
config_file = self.private_config_file
if config_file is None:
return None
try:
with open(config_file, "rb") as f:
return f.read().decode("utf-8", errors="replace")
except OSError as e:
raise IOUError("Can't read private-config file '{}': {}".format(config_file, e)) | python | def private_config_content(self):
"""
Returns the content of the current private-config file.
"""
config_file = self.private_config_file
if config_file is None:
return None
try:
with open(config_file, "rb") as f:
return f.read().decode("utf-8", errors="replace")
except OSError as e:
raise IOUError("Can't read private-config file '{}': {}".format(config_file, e)) | [
"def",
"private_config_content",
"(",
"self",
")",
":",
"config_file",
"=",
"self",
".",
"private_config_file",
"if",
"config_file",
"is",
"None",
":",
"return",
"None",
"try",
":",
"with",
"open",
"(",
"config_file",
",",
"\"rb\"",
")",
"as",
"f",
":",
"r... | Returns the content of the current private-config file. | [
"Returns",
"the",
"content",
"of",
"the",
"current",
"private",
"-",
"config",
"file",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L1037-L1050 | train | 221,569 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM.private_config_content | def private_config_content(self, private_config):
"""
Update the private config
:param private_config: content of the private configuration file
"""
try:
private_config_path = os.path.join(self.working_dir, "private-config.cfg")
if private_config is None:
private_config = ''
# We disallow erasing the private config file
if len(private_config) == 0 and os.path.exists(private_config_path):
return
with open(private_config_path, 'w+', encoding='utf-8') as f:
if len(private_config) == 0:
f.write('')
else:
private_config = private_config.replace("%h", self._name)
f.write(private_config)
except OSError as e:
raise IOUError("Can't write private-config file '{}': {}".format(private_config_path, e)) | python | def private_config_content(self, private_config):
"""
Update the private config
:param private_config: content of the private configuration file
"""
try:
private_config_path = os.path.join(self.working_dir, "private-config.cfg")
if private_config is None:
private_config = ''
# We disallow erasing the private config file
if len(private_config) == 0 and os.path.exists(private_config_path):
return
with open(private_config_path, 'w+', encoding='utf-8') as f:
if len(private_config) == 0:
f.write('')
else:
private_config = private_config.replace("%h", self._name)
f.write(private_config)
except OSError as e:
raise IOUError("Can't write private-config file '{}': {}".format(private_config_path, e)) | [
"def",
"private_config_content",
"(",
"self",
",",
"private_config",
")",
":",
"try",
":",
"private_config_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"working_dir",
",",
"\"private-config.cfg\"",
")",
"if",
"private_config",
"is",
"None",
":... | Update the private config
:param private_config: content of the private configuration file | [
"Update",
"the",
"private",
"config"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L1053-L1077 | train | 221,570 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM.startup_config_file | def startup_config_file(self):
"""
Returns the startup-config file for this IOU VM.
:returns: path to config file. None if the file doesn't exist
"""
path = os.path.join(self.working_dir, 'startup-config.cfg')
if os.path.exists(path):
return path
else:
return None | python | def startup_config_file(self):
"""
Returns the startup-config file for this IOU VM.
:returns: path to config file. None if the file doesn't exist
"""
path = os.path.join(self.working_dir, 'startup-config.cfg')
if os.path.exists(path):
return path
else:
return None | [
"def",
"startup_config_file",
"(",
"self",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"working_dir",
",",
"'startup-config.cfg'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"path",
"else"... | Returns the startup-config file for this IOU VM.
:returns: path to config file. None if the file doesn't exist | [
"Returns",
"the",
"startup",
"-",
"config",
"file",
"for",
"this",
"IOU",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L1080-L1091 | train | 221,571 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM.private_config_file | def private_config_file(self):
"""
Returns the private-config file for this IOU VM.
:returns: path to config file. None if the file doesn't exist
"""
path = os.path.join(self.working_dir, 'private-config.cfg')
if os.path.exists(path):
return path
else:
return None | python | def private_config_file(self):
"""
Returns the private-config file for this IOU VM.
:returns: path to config file. None if the file doesn't exist
"""
path = os.path.join(self.working_dir, 'private-config.cfg')
if os.path.exists(path):
return path
else:
return None | [
"def",
"private_config_file",
"(",
"self",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"working_dir",
",",
"'private-config.cfg'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"path",
"else"... | Returns the private-config file for this IOU VM.
:returns: path to config file. None if the file doesn't exist | [
"Returns",
"the",
"private",
"-",
"config",
"file",
"for",
"this",
"IOU",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L1094-L1105 | train | 221,572 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM.relative_startup_config_file | def relative_startup_config_file(self):
"""
Returns the startup-config file relative to the project directory.
It's compatible with pre 1.3 projects.
:returns: path to startup-config file. None if the file doesn't exist
"""
path = os.path.join(self.working_dir, 'startup-config.cfg')
if os.path.exists(path):
return 'startup-config.cfg'
else:
return None | python | def relative_startup_config_file(self):
"""
Returns the startup-config file relative to the project directory.
It's compatible with pre 1.3 projects.
:returns: path to startup-config file. None if the file doesn't exist
"""
path = os.path.join(self.working_dir, 'startup-config.cfg')
if os.path.exists(path):
return 'startup-config.cfg'
else:
return None | [
"def",
"relative_startup_config_file",
"(",
"self",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"working_dir",
",",
"'startup-config.cfg'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"'start... | Returns the startup-config file relative to the project directory.
It's compatible with pre 1.3 projects.
:returns: path to startup-config file. None if the file doesn't exist | [
"Returns",
"the",
"startup",
"-",
"config",
"file",
"relative",
"to",
"the",
"project",
"directory",
".",
"It",
"s",
"compatible",
"with",
"pre",
"1",
".",
"3",
"projects",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L1108-L1120 | train | 221,573 |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | IOUVM.relative_private_config_file | def relative_private_config_file(self):
"""
Returns the private-config file relative to the project directory.
:returns: path to private-config file. None if the file doesn't exist
"""
path = os.path.join(self.working_dir, 'private-config.cfg')
if os.path.exists(path):
return 'private-config.cfg'
else:
return None | python | def relative_private_config_file(self):
"""
Returns the private-config file relative to the project directory.
:returns: path to private-config file. None if the file doesn't exist
"""
path = os.path.join(self.working_dir, 'private-config.cfg')
if os.path.exists(path):
return 'private-config.cfg'
else:
return None | [
"def",
"relative_private_config_file",
"(",
"self",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"working_dir",
",",
"'private-config.cfg'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"'priva... | Returns the private-config file relative to the project directory.
:returns: path to private-config file. None if the file doesn't exist | [
"Returns",
"the",
"private",
"-",
"config",
"file",
"relative",
"to",
"the",
"project",
"directory",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L1123-L1134 | train | 221,574 |
GNS3/gns3-server | gns3server/controller/drawing.py | Drawing.svg | def svg(self, value):
"""
Set SVG field value.
If the svg has embed base64 element we will extract them
to disk in order to avoid duplication of content
"""
if len(value) < 500:
self._svg = value
return
try:
root = ET.fromstring(value)
except ET.ParseError as e:
log.error("Can't parse SVG: {}".format(e))
return
# SVG is the default namespace no need to prefix it
ET.register_namespace('xmlns', "http://www.w3.org/2000/svg")
ET.register_namespace('xmlns:xlink', "http://www.w3.org/1999/xlink")
if len(root.findall("{http://www.w3.org/2000/svg}image")) == 1:
href = "{http://www.w3.org/1999/xlink}href"
elem = root.find("{http://www.w3.org/2000/svg}image")
if elem.get(href, "").startswith("data:image/"):
changed = True
data = elem.get(href, "")
extension = re.sub(r"[^a-z0-9]", "", data.split(";")[0].split("/")[1].lower())
data = base64.decodebytes(data.split(",", 1)[1].encode())
# We compute an hash of the image file to avoid duplication
filename = hashlib.md5(data).hexdigest() + "." + extension
elem.set(href, filename)
file_path = os.path.join(self._project.pictures_directory, filename)
if not os.path.exists(file_path):
with open(file_path, "wb") as f:
f.write(data)
value = filename
# We dump also large svg on disk to keep .gns3 small
if len(value) > 1000:
filename = hashlib.md5(value.encode()).hexdigest() + ".svg"
file_path = os.path.join(self._project.pictures_directory, filename)
if not os.path.exists(file_path):
with open(file_path, "w+", encoding="utf-8") as f:
f.write(value)
self._svg = filename
else:
self._svg = value | python | def svg(self, value):
"""
Set SVG field value.
If the svg has embed base64 element we will extract them
to disk in order to avoid duplication of content
"""
if len(value) < 500:
self._svg = value
return
try:
root = ET.fromstring(value)
except ET.ParseError as e:
log.error("Can't parse SVG: {}".format(e))
return
# SVG is the default namespace no need to prefix it
ET.register_namespace('xmlns', "http://www.w3.org/2000/svg")
ET.register_namespace('xmlns:xlink', "http://www.w3.org/1999/xlink")
if len(root.findall("{http://www.w3.org/2000/svg}image")) == 1:
href = "{http://www.w3.org/1999/xlink}href"
elem = root.find("{http://www.w3.org/2000/svg}image")
if elem.get(href, "").startswith("data:image/"):
changed = True
data = elem.get(href, "")
extension = re.sub(r"[^a-z0-9]", "", data.split(";")[0].split("/")[1].lower())
data = base64.decodebytes(data.split(",", 1)[1].encode())
# We compute an hash of the image file to avoid duplication
filename = hashlib.md5(data).hexdigest() + "." + extension
elem.set(href, filename)
file_path = os.path.join(self._project.pictures_directory, filename)
if not os.path.exists(file_path):
with open(file_path, "wb") as f:
f.write(data)
value = filename
# We dump also large svg on disk to keep .gns3 small
if len(value) > 1000:
filename = hashlib.md5(value.encode()).hexdigest() + ".svg"
file_path = os.path.join(self._project.pictures_directory, filename)
if not os.path.exists(file_path):
with open(file_path, "w+", encoding="utf-8") as f:
f.write(value)
self._svg = filename
else:
self._svg = value | [
"def",
"svg",
"(",
"self",
",",
"value",
")",
":",
"if",
"len",
"(",
"value",
")",
"<",
"500",
":",
"self",
".",
"_svg",
"=",
"value",
"return",
"try",
":",
"root",
"=",
"ET",
".",
"fromstring",
"(",
"value",
")",
"except",
"ET",
".",
"ParseError... | Set SVG field value.
If the svg has embed base64 element we will extract them
to disk in order to avoid duplication of content | [
"Set",
"SVG",
"field",
"value",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/drawing.py#L84-L134 | train | 221,575 |
GNS3/gns3-server | gns3server/controller/drawing.py | Drawing.update | def update(self, **kwargs):
"""
Update the drawing
:param kwargs: Drawing properties
"""
# Update node properties with additional elements
svg_changed = False
for prop in kwargs:
if prop == "drawing_id":
pass # No good reason to change a drawing_id
elif getattr(self, prop) != kwargs[prop]:
if prop == "svg":
# To avoid spamming client with large data we don't send the svg if the SVG didn't change
svg_changed = True
setattr(self, prop, kwargs[prop])
data = self.__json__()
if not svg_changed:
del data["svg"]
self._project.controller.notification.emit("drawing.updated", data)
self._project.dump() | python | def update(self, **kwargs):
"""
Update the drawing
:param kwargs: Drawing properties
"""
# Update node properties with additional elements
svg_changed = False
for prop in kwargs:
if prop == "drawing_id":
pass # No good reason to change a drawing_id
elif getattr(self, prop) != kwargs[prop]:
if prop == "svg":
# To avoid spamming client with large data we don't send the svg if the SVG didn't change
svg_changed = True
setattr(self, prop, kwargs[prop])
data = self.__json__()
if not svg_changed:
del data["svg"]
self._project.controller.notification.emit("drawing.updated", data)
self._project.dump() | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Update node properties with additional elements",
"svg_changed",
"=",
"False",
"for",
"prop",
"in",
"kwargs",
":",
"if",
"prop",
"==",
"\"drawing_id\"",
":",
"pass",
"# No good reason to change a dr... | Update the drawing
:param kwargs: Drawing properties | [
"Update",
"the",
"drawing"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/drawing.py#L169-L190 | train | 221,576 |
GNS3/gns3-server | gns3server/compute/vpcs/__init__.py | VPCS.create_node | def create_node(self, *args, **kwargs):
"""
Creates a new VPCS VM.
:returns: VPCSVM instance
"""
node = yield from super().create_node(*args, **kwargs)
self._free_mac_ids.setdefault(node.project.id, list(range(0, 255)))
try:
self._used_mac_ids[node.id] = self._free_mac_ids[node.project.id].pop(0)
except IndexError:
raise VPCSError("Cannot create a new VPCS VM (limit of 255 VMs reached on this host)")
return node | python | def create_node(self, *args, **kwargs):
"""
Creates a new VPCS VM.
:returns: VPCSVM instance
"""
node = yield from super().create_node(*args, **kwargs)
self._free_mac_ids.setdefault(node.project.id, list(range(0, 255)))
try:
self._used_mac_ids[node.id] = self._free_mac_ids[node.project.id].pop(0)
except IndexError:
raise VPCSError("Cannot create a new VPCS VM (limit of 255 VMs reached on this host)")
return node | [
"def",
"create_node",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"node",
"=",
"yield",
"from",
"super",
"(",
")",
".",
"create_node",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_free_mac_ids",
".",
"setdefa... | Creates a new VPCS VM.
:returns: VPCSVM instance | [
"Creates",
"a",
"new",
"VPCS",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/__init__.py#L41-L54 | train | 221,577 |
GNS3/gns3-server | gns3server/compute/vpcs/__init__.py | VPCS.close_node | def close_node(self, node_id, *args, **kwargs):
"""
Closes a VPCS VM.
:returns: VPCSVM instance
"""
node = self.get_node(node_id)
if node_id in self._used_mac_ids:
i = self._used_mac_ids[node_id]
self._free_mac_ids[node.project.id].insert(0, i)
del self._used_mac_ids[node_id]
yield from super().close_node(node_id, *args, **kwargs)
return node | python | def close_node(self, node_id, *args, **kwargs):
"""
Closes a VPCS VM.
:returns: VPCSVM instance
"""
node = self.get_node(node_id)
if node_id in self._used_mac_ids:
i = self._used_mac_ids[node_id]
self._free_mac_ids[node.project.id].insert(0, i)
del self._used_mac_ids[node_id]
yield from super().close_node(node_id, *args, **kwargs)
return node | [
"def",
"close_node",
"(",
"self",
",",
"node_id",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"node",
"=",
"self",
".",
"get_node",
"(",
"node_id",
")",
"if",
"node_id",
"in",
"self",
".",
"_used_mac_ids",
":",
"i",
"=",
"self",
".",
"_use... | Closes a VPCS VM.
:returns: VPCSVM instance | [
"Closes",
"a",
"VPCS",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/__init__.py#L57-L70 | train | 221,578 |
GNS3/gns3-server | gns3server/compute/dynamips/nios/nio.py | NIO.delete | def delete(self):
"""
Deletes this NIO.
"""
if self._input_filter or self._output_filter:
yield from self.unbind_filter("both")
yield from self._hypervisor.send("nio delete {}".format(self._name))
log.info("NIO {name} has been deleted".format(name=self._name)) | python | def delete(self):
"""
Deletes this NIO.
"""
if self._input_filter or self._output_filter:
yield from self.unbind_filter("both")
yield from self._hypervisor.send("nio delete {}".format(self._name))
log.info("NIO {name} has been deleted".format(name=self._name)) | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"_input_filter",
"or",
"self",
".",
"_output_filter",
":",
"yield",
"from",
"self",
".",
"unbind_filter",
"(",
"\"both\"",
")",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"\"n... | Deletes this NIO. | [
"Deletes",
"this",
"NIO",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L61-L69 | train | 221,579 |
GNS3/gns3-server | gns3server/compute/dynamips/nios/nio.py | NIO.rename | def rename(self, new_name):
"""
Renames this NIO
:param new_name: new NIO name
"""
yield from self._hypervisor.send("nio rename {name} {new_name}".format(name=self._name, new_name=new_name))
log.info("NIO {name} renamed to {new_name}".format(name=self._name, new_name=new_name))
self._name = new_name | python | def rename(self, new_name):
"""
Renames this NIO
:param new_name: new NIO name
"""
yield from self._hypervisor.send("nio rename {name} {new_name}".format(name=self._name, new_name=new_name))
log.info("NIO {name} renamed to {new_name}".format(name=self._name, new_name=new_name))
self._name = new_name | [
"def",
"rename",
"(",
"self",
",",
"new_name",
")",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"\"nio rename {name} {new_name}\"",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"new_name",
"=",
"new_name",
")",
")",
... | Renames this NIO
:param new_name: new NIO name | [
"Renames",
"this",
"NIO"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L72-L82 | train | 221,580 |
GNS3/gns3-server | gns3server/compute/dynamips/nios/nio.py | NIO.bind_filter | def bind_filter(self, direction, filter_name):
"""
Adds a packet filter to this NIO.
Filter "freq_drop" drops packets.
Filter "capture" captures packets.
:param direction: "in", "out" or "both"
:param filter_name: name of the filter to apply
"""
if direction not in self._dynamips_direction:
raise DynamipsError("Unknown direction {} to bind filter {}:".format(direction, filter_name))
dynamips_direction = self._dynamips_direction[direction]
yield from self._hypervisor.send("nio bind_filter {name} {direction} {filter}".format(name=self._name,
direction=dynamips_direction,
filter=filter_name))
if direction == "in":
self._input_filter = filter_name
elif direction == "out":
self._output_filter = filter_name
elif direction == "both":
self._input_filter = filter_name
self._output_filter = filter_name | python | def bind_filter(self, direction, filter_name):
"""
Adds a packet filter to this NIO.
Filter "freq_drop" drops packets.
Filter "capture" captures packets.
:param direction: "in", "out" or "both"
:param filter_name: name of the filter to apply
"""
if direction not in self._dynamips_direction:
raise DynamipsError("Unknown direction {} to bind filter {}:".format(direction, filter_name))
dynamips_direction = self._dynamips_direction[direction]
yield from self._hypervisor.send("nio bind_filter {name} {direction} {filter}".format(name=self._name,
direction=dynamips_direction,
filter=filter_name))
if direction == "in":
self._input_filter = filter_name
elif direction == "out":
self._output_filter = filter_name
elif direction == "both":
self._input_filter = filter_name
self._output_filter = filter_name | [
"def",
"bind_filter",
"(",
"self",
",",
"direction",
",",
"filter_name",
")",
":",
"if",
"direction",
"not",
"in",
"self",
".",
"_dynamips_direction",
":",
"raise",
"DynamipsError",
"(",
"\"Unknown direction {} to bind filter {}:\"",
".",
"format",
"(",
"direction",... | Adds a packet filter to this NIO.
Filter "freq_drop" drops packets.
Filter "capture" captures packets.
:param direction: "in", "out" or "both"
:param filter_name: name of the filter to apply | [
"Adds",
"a",
"packet",
"filter",
"to",
"this",
"NIO",
".",
"Filter",
"freq_drop",
"drops",
"packets",
".",
"Filter",
"capture",
"captures",
"packets",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L95-L119 | train | 221,581 |
GNS3/gns3-server | gns3server/compute/dynamips/nios/nio.py | NIO.unbind_filter | def unbind_filter(self, direction):
"""
Removes packet filter for this NIO.
:param direction: "in", "out" or "both"
"""
if direction not in self._dynamips_direction:
raise DynamipsError("Unknown direction {} to unbind filter:".format(direction))
dynamips_direction = self._dynamips_direction[direction]
yield from self._hypervisor.send("nio unbind_filter {name} {direction}".format(name=self._name,
direction=dynamips_direction))
if direction == "in":
self._input_filter = None
elif direction == "out":
self._output_filter = None
elif direction == "both":
self._input_filter = None
self._output_filter = None | python | def unbind_filter(self, direction):
"""
Removes packet filter for this NIO.
:param direction: "in", "out" or "both"
"""
if direction not in self._dynamips_direction:
raise DynamipsError("Unknown direction {} to unbind filter:".format(direction))
dynamips_direction = self._dynamips_direction[direction]
yield from self._hypervisor.send("nio unbind_filter {name} {direction}".format(name=self._name,
direction=dynamips_direction))
if direction == "in":
self._input_filter = None
elif direction == "out":
self._output_filter = None
elif direction == "both":
self._input_filter = None
self._output_filter = None | [
"def",
"unbind_filter",
"(",
"self",
",",
"direction",
")",
":",
"if",
"direction",
"not",
"in",
"self",
".",
"_dynamips_direction",
":",
"raise",
"DynamipsError",
"(",
"\"Unknown direction {} to unbind filter:\"",
".",
"format",
"(",
"direction",
")",
")",
"dynam... | Removes packet filter for this NIO.
:param direction: "in", "out" or "both" | [
"Removes",
"packet",
"filter",
"for",
"this",
"NIO",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L122-L142 | train | 221,582 |
GNS3/gns3-server | gns3server/compute/dynamips/nios/nio.py | NIO.setup_filter | def setup_filter(self, direction, options):
"""
Setups a packet filter bound with this NIO.
Filter "freq_drop" has 1 argument "<frequency>". It will drop
everything with a -1 frequency, drop every Nth packet with a
positive frequency, or drop nothing.
Filter "capture" has 2 arguments "<link_type_name> <output_file>".
It will capture packets to the target output file. The link type
name is a case-insensitive DLT_ name from the PCAP library
constants with the DLT_ part removed.See http://www.tcpdump.org/linktypes.html
for a list of all available DLT values.
:param direction: "in", "out" or "both"
:param options: options for the packet filter (string)
"""
if direction not in self._dynamips_direction:
raise DynamipsError("Unknown direction {} to setup filter:".format(direction))
dynamips_direction = self._dynamips_direction[direction]
yield from self._hypervisor.send("nio setup_filter {name} {direction} {options}".format(name=self._name,
direction=dynamips_direction,
options=options))
if direction == "in":
self._input_filter_options = options
elif direction == "out":
self._output_filter_options = options
elif direction == "both":
self._input_filter_options = options
self._output_filter_options = options | python | def setup_filter(self, direction, options):
"""
Setups a packet filter bound with this NIO.
Filter "freq_drop" has 1 argument "<frequency>". It will drop
everything with a -1 frequency, drop every Nth packet with a
positive frequency, or drop nothing.
Filter "capture" has 2 arguments "<link_type_name> <output_file>".
It will capture packets to the target output file. The link type
name is a case-insensitive DLT_ name from the PCAP library
constants with the DLT_ part removed.See http://www.tcpdump.org/linktypes.html
for a list of all available DLT values.
:param direction: "in", "out" or "both"
:param options: options for the packet filter (string)
"""
if direction not in self._dynamips_direction:
raise DynamipsError("Unknown direction {} to setup filter:".format(direction))
dynamips_direction = self._dynamips_direction[direction]
yield from self._hypervisor.send("nio setup_filter {name} {direction} {options}".format(name=self._name,
direction=dynamips_direction,
options=options))
if direction == "in":
self._input_filter_options = options
elif direction == "out":
self._output_filter_options = options
elif direction == "both":
self._input_filter_options = options
self._output_filter_options = options | [
"def",
"setup_filter",
"(",
"self",
",",
"direction",
",",
"options",
")",
":",
"if",
"direction",
"not",
"in",
"self",
".",
"_dynamips_direction",
":",
"raise",
"DynamipsError",
"(",
"\"Unknown direction {} to setup filter:\"",
".",
"format",
"(",
"direction",
")... | Setups a packet filter bound with this NIO.
Filter "freq_drop" has 1 argument "<frequency>". It will drop
everything with a -1 frequency, drop every Nth packet with a
positive frequency, or drop nothing.
Filter "capture" has 2 arguments "<link_type_name> <output_file>".
It will capture packets to the target output file. The link type
name is a case-insensitive DLT_ name from the PCAP library
constants with the DLT_ part removed.See http://www.tcpdump.org/linktypes.html
for a list of all available DLT values.
:param direction: "in", "out" or "both"
:param options: options for the packet filter (string) | [
"Setups",
"a",
"packet",
"filter",
"bound",
"with",
"this",
"NIO",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L145-L177 | train | 221,583 |
GNS3/gns3-server | gns3server/compute/dynamips/nios/nio.py | NIO.get_stats | def get_stats(self):
"""
Gets statistics for this NIO.
:returns: NIO statistics (string with packets in, packets out, bytes in, bytes out)
"""
stats = yield from self._hypervisor.send("nio get_stats {}".format(self._name))
return stats[0] | python | def get_stats(self):
"""
Gets statistics for this NIO.
:returns: NIO statistics (string with packets in, packets out, bytes in, bytes out)
"""
stats = yield from self._hypervisor.send("nio get_stats {}".format(self._name))
return stats[0] | [
"def",
"get_stats",
"(",
"self",
")",
":",
"stats",
"=",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"\"nio get_stats {}\"",
".",
"format",
"(",
"self",
".",
"_name",
")",
")",
"return",
"stats",
"[",
"0",
"]"
] | Gets statistics for this NIO.
:returns: NIO statistics (string with packets in, packets out, bytes in, bytes out) | [
"Gets",
"statistics",
"for",
"this",
"NIO",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L200-L208 | train | 221,584 |
GNS3/gns3-server | gns3server/compute/dynamips/nios/nio.py | NIO.set_bandwidth | def set_bandwidth(self, bandwidth):
"""
Sets bandwidth constraint.
:param bandwidth: bandwidth integer value (in Kb/s)
"""
yield from self._hypervisor.send("nio set_bandwidth {name} {bandwidth}".format(name=self._name, bandwidth=bandwidth))
self._bandwidth = bandwidth | python | def set_bandwidth(self, bandwidth):
"""
Sets bandwidth constraint.
:param bandwidth: bandwidth integer value (in Kb/s)
"""
yield from self._hypervisor.send("nio set_bandwidth {name} {bandwidth}".format(name=self._name, bandwidth=bandwidth))
self._bandwidth = bandwidth | [
"def",
"set_bandwidth",
"(",
"self",
",",
"bandwidth",
")",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"\"nio set_bandwidth {name} {bandwidth}\"",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"bandwidth",
"=",
"bandwidth... | Sets bandwidth constraint.
:param bandwidth: bandwidth integer value (in Kb/s) | [
"Sets",
"bandwidth",
"constraint",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nios/nio.py#L229-L237 | train | 221,585 |
GNS3/gns3-server | gns3server/controller/node.py | Node.create | def create(self):
"""
Create the node on the compute server
"""
data = self._node_data()
data["node_id"] = self._id
if self._node_type == "docker":
timeout = None
else:
timeout = 1200
trial = 0
while trial != 6:
try:
response = yield from self._compute.post("/projects/{}/{}/nodes".format(self._project.id, self._node_type), data=data, timeout=timeout)
except ComputeConflict as e:
if e.response.get("exception") == "ImageMissingError":
res = yield from self._upload_missing_image(self._node_type, e.response["image"])
if not res:
raise e
else:
raise e
else:
yield from self.parse_node_response(response.json)
return True
trial += 1 | python | def create(self):
"""
Create the node on the compute server
"""
data = self._node_data()
data["node_id"] = self._id
if self._node_type == "docker":
timeout = None
else:
timeout = 1200
trial = 0
while trial != 6:
try:
response = yield from self._compute.post("/projects/{}/{}/nodes".format(self._project.id, self._node_type), data=data, timeout=timeout)
except ComputeConflict as e:
if e.response.get("exception") == "ImageMissingError":
res = yield from self._upload_missing_image(self._node_type, e.response["image"])
if not res:
raise e
else:
raise e
else:
yield from self.parse_node_response(response.json)
return True
trial += 1 | [
"def",
"create",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"_node_data",
"(",
")",
"data",
"[",
"\"node_id\"",
"]",
"=",
"self",
".",
"_id",
"if",
"self",
".",
"_node_type",
"==",
"\"docker\"",
":",
"timeout",
"=",
"None",
"else",
":",
"timeou... | Create the node on the compute server | [
"Create",
"the",
"node",
"on",
"the",
"compute",
"server"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L326-L350 | train | 221,586 |
GNS3/gns3-server | gns3server/controller/node.py | Node.update | def update(self, **kwargs):
"""
Update the node on the compute server
:param kwargs: Node properties
"""
# When updating properties used only on controller we don't need to call the compute
update_compute = False
old_json = self.__json__()
compute_properties = None
# Update node properties with additional elements
for prop in kwargs:
if getattr(self, prop) != kwargs[prop]:
if prop not in self.CONTROLLER_ONLY_PROPERTIES:
update_compute = True
# We update properties on the compute and wait for the anwser from the compute node
if prop == "properties":
compute_properties = kwargs[prop]
else:
setattr(self, prop, kwargs[prop])
self._list_ports()
# We send notif only if object has changed
if old_json != self.__json__():
self.project.controller.notification.emit("node.updated", self.__json__())
if update_compute:
data = self._node_data(properties=compute_properties)
response = yield from self.put(None, data=data)
yield from self.parse_node_response(response.json)
self.project.dump() | python | def update(self, **kwargs):
"""
Update the node on the compute server
:param kwargs: Node properties
"""
# When updating properties used only on controller we don't need to call the compute
update_compute = False
old_json = self.__json__()
compute_properties = None
# Update node properties with additional elements
for prop in kwargs:
if getattr(self, prop) != kwargs[prop]:
if prop not in self.CONTROLLER_ONLY_PROPERTIES:
update_compute = True
# We update properties on the compute and wait for the anwser from the compute node
if prop == "properties":
compute_properties = kwargs[prop]
else:
setattr(self, prop, kwargs[prop])
self._list_ports()
# We send notif only if object has changed
if old_json != self.__json__():
self.project.controller.notification.emit("node.updated", self.__json__())
if update_compute:
data = self._node_data(properties=compute_properties)
response = yield from self.put(None, data=data)
yield from self.parse_node_response(response.json)
self.project.dump() | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# When updating properties used only on controller we don't need to call the compute",
"update_compute",
"=",
"False",
"old_json",
"=",
"self",
".",
"__json__",
"(",
")",
"compute_properties",
"=",
"None"... | Update the node on the compute server
:param kwargs: Node properties | [
"Update",
"the",
"node",
"on",
"the",
"compute",
"server"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L353-L386 | train | 221,587 |
GNS3/gns3-server | gns3server/controller/node.py | Node.parse_node_response | def parse_node_response(self, response):
"""
Update the object with the remote node object
"""
for key, value in response.items():
if key == "console":
self._console = value
elif key == "node_directory":
self._node_directory = value
elif key == "command_line":
self._command_line = value
elif key == "status":
self._status = value
elif key == "console_type":
self._console_type = value
elif key == "name":
self.name = value
elif key in ["node_id", "project_id", "console_host",
"startup_config_content",
"private_config_content",
"startup_script"]:
if key in self._properties:
del self._properties[key]
else:
self._properties[key] = value
self._list_ports()
for link in self._links:
yield from link.node_updated(self) | python | def parse_node_response(self, response):
"""
Update the object with the remote node object
"""
for key, value in response.items():
if key == "console":
self._console = value
elif key == "node_directory":
self._node_directory = value
elif key == "command_line":
self._command_line = value
elif key == "status":
self._status = value
elif key == "console_type":
self._console_type = value
elif key == "name":
self.name = value
elif key in ["node_id", "project_id", "console_host",
"startup_config_content",
"private_config_content",
"startup_script"]:
if key in self._properties:
del self._properties[key]
else:
self._properties[key] = value
self._list_ports()
for link in self._links:
yield from link.node_updated(self) | [
"def",
"parse_node_response",
"(",
"self",
",",
"response",
")",
":",
"for",
"key",
",",
"value",
"in",
"response",
".",
"items",
"(",
")",
":",
"if",
"key",
"==",
"\"console\"",
":",
"self",
".",
"_console",
"=",
"value",
"elif",
"key",
"==",
"\"node_... | Update the object with the remote node object | [
"Update",
"the",
"object",
"with",
"the",
"remote",
"node",
"object"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L389-L416 | train | 221,588 |
GNS3/gns3-server | gns3server/controller/node.py | Node._node_data | def _node_data(self, properties=None):
"""
Prepare node data to send to the remote controller
:param properties: If properties is None use actual property otherwise use the parameter
"""
if properties:
data = copy.copy(properties)
else:
data = copy.copy(self._properties)
# We replace the startup script name by the content of the file
mapping = {
"base_script_file": "startup_script",
"startup_config": "startup_config_content",
"private_config": "private_config_content",
}
for k, v in mapping.items():
if k in list(self._properties.keys()):
data[v] = self._base_config_file_content(self._properties[k])
del data[k]
del self._properties[k] # We send the file only one time
data["name"] = self._name
if self._console:
# console is optional for builtin nodes
data["console"] = self._console
if self._console_type:
data["console_type"] = self._console_type
# None properties are not be send. Because it can mean the emulator doesn't support it
for key in list(data.keys()):
if data[key] is None or data[key] is {} or key in self.CONTROLLER_ONLY_PROPERTIES:
del data[key]
return data | python | def _node_data(self, properties=None):
"""
Prepare node data to send to the remote controller
:param properties: If properties is None use actual property otherwise use the parameter
"""
if properties:
data = copy.copy(properties)
else:
data = copy.copy(self._properties)
# We replace the startup script name by the content of the file
mapping = {
"base_script_file": "startup_script",
"startup_config": "startup_config_content",
"private_config": "private_config_content",
}
for k, v in mapping.items():
if k in list(self._properties.keys()):
data[v] = self._base_config_file_content(self._properties[k])
del data[k]
del self._properties[k] # We send the file only one time
data["name"] = self._name
if self._console:
# console is optional for builtin nodes
data["console"] = self._console
if self._console_type:
data["console_type"] = self._console_type
# None properties are not be send. Because it can mean the emulator doesn't support it
for key in list(data.keys()):
if data[key] is None or data[key] is {} or key in self.CONTROLLER_ONLY_PROPERTIES:
del data[key]
return data | [
"def",
"_node_data",
"(",
"self",
",",
"properties",
"=",
"None",
")",
":",
"if",
"properties",
":",
"data",
"=",
"copy",
".",
"copy",
"(",
"properties",
")",
"else",
":",
"data",
"=",
"copy",
".",
"copy",
"(",
"self",
".",
"_properties",
")",
"# We ... | Prepare node data to send to the remote controller
:param properties: If properties is None use actual property otherwise use the parameter | [
"Prepare",
"node",
"data",
"to",
"send",
"to",
"the",
"remote",
"controller"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L418-L450 | train | 221,589 |
GNS3/gns3-server | gns3server/controller/node.py | Node.reload | def reload(self):
"""
Suspend a node
"""
try:
yield from self.post("/reload", timeout=240)
except asyncio.TimeoutError:
raise aiohttp.web.HTTPRequestTimeout(text="Timeout when reloading {}".format(self._name)) | python | def reload(self):
"""
Suspend a node
"""
try:
yield from self.post("/reload", timeout=240)
except asyncio.TimeoutError:
raise aiohttp.web.HTTPRequestTimeout(text="Timeout when reloading {}".format(self._name)) | [
"def",
"reload",
"(",
"self",
")",
":",
"try",
":",
"yield",
"from",
"self",
".",
"post",
"(",
"\"/reload\"",
",",
"timeout",
"=",
"240",
")",
"except",
"asyncio",
".",
"TimeoutError",
":",
"raise",
"aiohttp",
".",
"web",
".",
"HTTPRequestTimeout",
"(",
... | Suspend a node | [
"Suspend",
"a",
"node"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L498-L505 | train | 221,590 |
GNS3/gns3-server | gns3server/controller/node.py | Node._upload_missing_image | def _upload_missing_image(self, type, img):
"""
Search an image on local computer and upload it to remote compute
if the image exists
"""
for directory in images_directories(type):
image = os.path.join(directory, img)
if os.path.exists(image):
self.project.controller.notification.emit("log.info", {"message": "Uploading missing image {}".format(img)})
try:
with open(image, 'rb') as f:
yield from self._compute.post("/{}/images/{}".format(self._node_type, os.path.basename(img)), data=f, timeout=None)
except OSError as e:
raise aiohttp.web.HTTPConflict(text="Can't upload {}: {}".format(image, str(e)))
self.project.controller.notification.emit("log.info", {"message": "Upload finished for {}".format(img)})
return True
return False | python | def _upload_missing_image(self, type, img):
"""
Search an image on local computer and upload it to remote compute
if the image exists
"""
for directory in images_directories(type):
image = os.path.join(directory, img)
if os.path.exists(image):
self.project.controller.notification.emit("log.info", {"message": "Uploading missing image {}".format(img)})
try:
with open(image, 'rb') as f:
yield from self._compute.post("/{}/images/{}".format(self._node_type, os.path.basename(img)), data=f, timeout=None)
except OSError as e:
raise aiohttp.web.HTTPConflict(text="Can't upload {}: {}".format(image, str(e)))
self.project.controller.notification.emit("log.info", {"message": "Upload finished for {}".format(img)})
return True
return False | [
"def",
"_upload_missing_image",
"(",
"self",
",",
"type",
",",
"img",
")",
":",
"for",
"directory",
"in",
"images_directories",
"(",
"type",
")",
":",
"image",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"img",
")",
"if",
"os",
".",
"... | Search an image on local computer and upload it to remote compute
if the image exists | [
"Search",
"an",
"image",
"on",
"local",
"computer",
"and",
"upload",
"it",
"to",
"remote",
"compute",
"if",
"the",
"image",
"exists"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L542-L558 | train | 221,591 |
GNS3/gns3-server | gns3server/controller/node.py | Node.dynamips_auto_idlepc | def dynamips_auto_idlepc(self):
"""
Compute the idle PC for a dynamips node
"""
return (yield from self._compute.get("/projects/{}/{}/nodes/{}/auto_idlepc".format(self._project.id, self._node_type, self._id), timeout=240)).json | python | def dynamips_auto_idlepc(self):
"""
Compute the idle PC for a dynamips node
"""
return (yield from self._compute.get("/projects/{}/{}/nodes/{}/auto_idlepc".format(self._project.id, self._node_type, self._id), timeout=240)).json | [
"def",
"dynamips_auto_idlepc",
"(",
"self",
")",
":",
"return",
"(",
"yield",
"from",
"self",
".",
"_compute",
".",
"get",
"(",
"\"/projects/{}/{}/nodes/{}/auto_idlepc\"",
".",
"format",
"(",
"self",
".",
"_project",
".",
"id",
",",
"self",
".",
"_node_type",
... | Compute the idle PC for a dynamips node | [
"Compute",
"the",
"idle",
"PC",
"for",
"a",
"dynamips",
"node"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L561-L565 | train | 221,592 |
GNS3/gns3-server | gns3server/controller/node.py | Node.get_port | def get_port(self, adapter_number, port_number):
"""
Return the port for this adapter_number and port_number
or returns None if the port is not found
"""
for port in self.ports:
if port.adapter_number == adapter_number and port.port_number == port_number:
return port
return None | python | def get_port(self, adapter_number, port_number):
"""
Return the port for this adapter_number and port_number
or returns None if the port is not found
"""
for port in self.ports:
if port.adapter_number == adapter_number and port.port_number == port_number:
return port
return None | [
"def",
"get_port",
"(",
"self",
",",
"adapter_number",
",",
"port_number",
")",
":",
"for",
"port",
"in",
"self",
".",
"ports",
":",
"if",
"port",
".",
"adapter_number",
"==",
"adapter_number",
"and",
"port",
".",
"port_number",
"==",
"port_number",
":",
"... | Return the port for this adapter_number and port_number
or returns None if the port is not found | [
"Return",
"the",
"port",
"for",
"this",
"adapter_number",
"and",
"port_number",
"or",
"returns",
"None",
"if",
"the",
"port",
"is",
"not",
"found"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L574-L582 | train | 221,593 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/c1700.py | C1700.set_chassis | def set_chassis(self, chassis):
"""
Sets the chassis.
:param: chassis string:
1720, 1721, 1750, 1751 or 1760
"""
yield from self._hypervisor.send('c1700 set_chassis "{name}" {chassis}'.format(name=self._name, chassis=chassis))
log.info('Router "{name}" [{id}]: chassis set to {chassis}'.format(name=self._name,
id=self._id,
chassis=chassis))
self._chassis = chassis
self._setup_chassis() | python | def set_chassis(self, chassis):
"""
Sets the chassis.
:param: chassis string:
1720, 1721, 1750, 1751 or 1760
"""
yield from self._hypervisor.send('c1700 set_chassis "{name}" {chassis}'.format(name=self._name, chassis=chassis))
log.info('Router "{name}" [{id}]: chassis set to {chassis}'.format(name=self._name,
id=self._id,
chassis=chassis))
self._chassis = chassis
self._setup_chassis() | [
"def",
"set_chassis",
"(",
"self",
",",
"chassis",
")",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'c1700 set_chassis \"{name}\" {chassis}'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"chassis",
"=",
"chassis",
")"... | Sets the chassis.
:param: chassis string:
1720, 1721, 1750, 1751 or 1760 | [
"Sets",
"the",
"chassis",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/c1700.py#L107-L122 | train | 221,594 |
GNS3/gns3-server | gns3server/controller/topology.py | load_topology | def load_topology(path):
"""
Open a topology file, patch it for last GNS3 release and return it
"""
log.debug("Read topology %s", path)
try:
with open(path, encoding="utf-8") as f:
topo = json.load(f)
except (OSError, UnicodeDecodeError, ValueError) as e:
raise aiohttp.web.HTTPConflict(text="Could not load topology {}: {}".format(path, str(e)))
if topo.get("revision", 0) > GNS3_FILE_FORMAT_REVISION:
raise aiohttp.web.HTTPConflict(text="This project is designed for a more recent version of GNS3 please update GNS3 to version {} or later".format(topo["version"]))
changed = False
if "revision" not in topo or topo["revision"] < GNS3_FILE_FORMAT_REVISION:
# If it's an old GNS3 file we need to convert it
# first we backup the file
try:
shutil.copy(path, path + ".backup{}".format(topo.get("revision", 0)))
except (OSError) as e:
raise aiohttp.web.HTTPConflict(text="Can't write backup of the topology {}: {}".format(path, str(e)))
changed = True
if "revision" not in topo or topo["revision"] < 5:
topo = _convert_1_3_later(topo, path)
# Version before GNS3 2.0 alpha 4
if topo["revision"] < 6:
topo = _convert_2_0_0_alpha(topo, path)
# Version before GNS3 2.0 beta 3
if topo["revision"] < 7:
topo = _convert_2_0_0_beta_2(topo, path)
# Version before GNS3 2.1
if topo["revision"] < 8:
topo = _convert_2_0_0(topo, path)
try:
_check_topology_schema(topo)
except aiohttp.web.HTTPConflict as e:
log.error("Can't load the topology %s", path)
raise e
if changed:
try:
with open(path, "w+", encoding="utf-8") as f:
json.dump(topo, f, indent=4, sort_keys=True)
except (OSError) as e:
raise aiohttp.web.HTTPConflict(text="Can't write the topology {}: {}".format(path, str(e)))
return topo | python | def load_topology(path):
"""
Open a topology file, patch it for last GNS3 release and return it
"""
log.debug("Read topology %s", path)
try:
with open(path, encoding="utf-8") as f:
topo = json.load(f)
except (OSError, UnicodeDecodeError, ValueError) as e:
raise aiohttp.web.HTTPConflict(text="Could not load topology {}: {}".format(path, str(e)))
if topo.get("revision", 0) > GNS3_FILE_FORMAT_REVISION:
raise aiohttp.web.HTTPConflict(text="This project is designed for a more recent version of GNS3 please update GNS3 to version {} or later".format(topo["version"]))
changed = False
if "revision" not in topo or topo["revision"] < GNS3_FILE_FORMAT_REVISION:
# If it's an old GNS3 file we need to convert it
# first we backup the file
try:
shutil.copy(path, path + ".backup{}".format(topo.get("revision", 0)))
except (OSError) as e:
raise aiohttp.web.HTTPConflict(text="Can't write backup of the topology {}: {}".format(path, str(e)))
changed = True
if "revision" not in topo or topo["revision"] < 5:
topo = _convert_1_3_later(topo, path)
# Version before GNS3 2.0 alpha 4
if topo["revision"] < 6:
topo = _convert_2_0_0_alpha(topo, path)
# Version before GNS3 2.0 beta 3
if topo["revision"] < 7:
topo = _convert_2_0_0_beta_2(topo, path)
# Version before GNS3 2.1
if topo["revision"] < 8:
topo = _convert_2_0_0(topo, path)
try:
_check_topology_schema(topo)
except aiohttp.web.HTTPConflict as e:
log.error("Can't load the topology %s", path)
raise e
if changed:
try:
with open(path, "w+", encoding="utf-8") as f:
json.dump(topo, f, indent=4, sort_keys=True)
except (OSError) as e:
raise aiohttp.web.HTTPConflict(text="Can't write the topology {}: {}".format(path, str(e)))
return topo | [
"def",
"load_topology",
"(",
"path",
")",
":",
"log",
".",
"debug",
"(",
"\"Read topology %s\"",
",",
"path",
")",
"try",
":",
"with",
"open",
"(",
"path",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"f",
":",
"topo",
"=",
"json",
".",
"load",
"(",... | Open a topology file, patch it for last GNS3 release and return it | [
"Open",
"a",
"topology",
"file",
"patch",
"it",
"for",
"last",
"GNS3",
"release",
"and",
"return",
"it"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/topology.py#L115-L166 | train | 221,595 |
GNS3/gns3-server | gns3server/controller/topology.py | _convert_2_0_0 | def _convert_2_0_0(topo, topo_path):
"""
Convert topologies from GNS3 2.0.0 to 2.1
Changes:
* Remove startup_script_path from VPCS and base config file for IOU and Dynamips
"""
topo["revision"] = 8
for node in topo.get("topology", {}).get("nodes", []):
if "properties" in node:
if node["node_type"] == "vpcs":
if "startup_script_path" in node["properties"]:
del node["properties"]["startup_script_path"]
if "startup_script" in node["properties"]:
del node["properties"]["startup_script"]
elif node["node_type"] == "dynamips" or node["node_type"] == "iou":
if "startup_config" in node["properties"]:
del node["properties"]["startup_config"]
if "private_config" in node["properties"]:
del node["properties"]["private_config"]
if "startup_config_content" in node["properties"]:
del node["properties"]["startup_config_content"]
if "private_config_content" in node["properties"]:
del node["properties"]["private_config_content"]
return topo | python | def _convert_2_0_0(topo, topo_path):
"""
Convert topologies from GNS3 2.0.0 to 2.1
Changes:
* Remove startup_script_path from VPCS and base config file for IOU and Dynamips
"""
topo["revision"] = 8
for node in topo.get("topology", {}).get("nodes", []):
if "properties" in node:
if node["node_type"] == "vpcs":
if "startup_script_path" in node["properties"]:
del node["properties"]["startup_script_path"]
if "startup_script" in node["properties"]:
del node["properties"]["startup_script"]
elif node["node_type"] == "dynamips" or node["node_type"] == "iou":
if "startup_config" in node["properties"]:
del node["properties"]["startup_config"]
if "private_config" in node["properties"]:
del node["properties"]["private_config"]
if "startup_config_content" in node["properties"]:
del node["properties"]["startup_config_content"]
if "private_config_content" in node["properties"]:
del node["properties"]["private_config_content"]
return topo | [
"def",
"_convert_2_0_0",
"(",
"topo",
",",
"topo_path",
")",
":",
"topo",
"[",
"\"revision\"",
"]",
"=",
"8",
"for",
"node",
"in",
"topo",
".",
"get",
"(",
"\"topology\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"nodes\"",
",",
"[",
"]",
")",
":",
... | Convert topologies from GNS3 2.0.0 to 2.1
Changes:
* Remove startup_script_path from VPCS and base config file for IOU and Dynamips | [
"Convert",
"topologies",
"from",
"GNS3",
"2",
".",
"0",
".",
"0",
"to",
"2",
".",
"1"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/topology.py#L169-L194 | train | 221,596 |
GNS3/gns3-server | gns3server/controller/topology.py | _convert_2_0_0_beta_2 | def _convert_2_0_0_beta_2(topo, topo_path):
"""
Convert topologies from GNS3 2.0.0 beta 2 to beta 3.
Changes:
* Node id folders for dynamips
"""
topo_dir = os.path.dirname(topo_path)
topo["revision"] = 7
for node in topo.get("topology", {}).get("nodes", []):
if node["node_type"] == "dynamips":
node_id = node["node_id"]
dynamips_id = node["properties"]["dynamips_id"]
dynamips_dir = os.path.join(topo_dir, "project-files", "dynamips")
node_dir = os.path.join(dynamips_dir, node_id)
try:
os.makedirs(os.path.join(node_dir, "configs"), exist_ok=True)
for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "*_i{}_*".format(dynamips_id))):
shutil.move(path, os.path.join(node_dir, os.path.basename(path)))
for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "configs", "i{}_*".format(dynamips_id))):
shutil.move(path, os.path.join(node_dir, "configs", os.path.basename(path)))
except OSError as e:
raise aiohttp.web.HTTPConflict(text="Can't convert project {}: {}".format(topo_path, str(e)))
return topo | python | def _convert_2_0_0_beta_2(topo, topo_path):
"""
Convert topologies from GNS3 2.0.0 beta 2 to beta 3.
Changes:
* Node id folders for dynamips
"""
topo_dir = os.path.dirname(topo_path)
topo["revision"] = 7
for node in topo.get("topology", {}).get("nodes", []):
if node["node_type"] == "dynamips":
node_id = node["node_id"]
dynamips_id = node["properties"]["dynamips_id"]
dynamips_dir = os.path.join(topo_dir, "project-files", "dynamips")
node_dir = os.path.join(dynamips_dir, node_id)
try:
os.makedirs(os.path.join(node_dir, "configs"), exist_ok=True)
for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "*_i{}_*".format(dynamips_id))):
shutil.move(path, os.path.join(node_dir, os.path.basename(path)))
for path in glob.glob(os.path.join(glob.escape(dynamips_dir), "configs", "i{}_*".format(dynamips_id))):
shutil.move(path, os.path.join(node_dir, "configs", os.path.basename(path)))
except OSError as e:
raise aiohttp.web.HTTPConflict(text="Can't convert project {}: {}".format(topo_path, str(e)))
return topo | [
"def",
"_convert_2_0_0_beta_2",
"(",
"topo",
",",
"topo_path",
")",
":",
"topo_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"topo_path",
")",
"topo",
"[",
"\"revision\"",
"]",
"=",
"7",
"for",
"node",
"in",
"topo",
".",
"get",
"(",
"\"topology\"",
... | Convert topologies from GNS3 2.0.0 beta 2 to beta 3.
Changes:
* Node id folders for dynamips | [
"Convert",
"topologies",
"from",
"GNS3",
"2",
".",
"0",
".",
"0",
"beta",
"2",
"to",
"beta",
"3",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/topology.py#L197-L222 | train | 221,597 |
GNS3/gns3-server | gns3server/controller/topology.py | _convert_2_0_0_alpha | def _convert_2_0_0_alpha(topo, topo_path):
"""
Convert topologies from GNS3 2.0.0 alpha to 2.0.0 final.
Changes:
* No more serial console
* No more option for VMware / VirtualBox remote console (always use telnet)
"""
topo["revision"] = 6
for node in topo.get("topology", {}).get("nodes", []):
if node.get("console_type") == "serial":
node["console_type"] = "telnet"
if node["node_type"] in ("vmware", "virtualbox"):
prop = node.get("properties")
if "enable_remote_console" in prop:
del prop["enable_remote_console"]
return topo | python | def _convert_2_0_0_alpha(topo, topo_path):
"""
Convert topologies from GNS3 2.0.0 alpha to 2.0.0 final.
Changes:
* No more serial console
* No more option for VMware / VirtualBox remote console (always use telnet)
"""
topo["revision"] = 6
for node in topo.get("topology", {}).get("nodes", []):
if node.get("console_type") == "serial":
node["console_type"] = "telnet"
if node["node_type"] in ("vmware", "virtualbox"):
prop = node.get("properties")
if "enable_remote_console" in prop:
del prop["enable_remote_console"]
return topo | [
"def",
"_convert_2_0_0_alpha",
"(",
"topo",
",",
"topo_path",
")",
":",
"topo",
"[",
"\"revision\"",
"]",
"=",
"6",
"for",
"node",
"in",
"topo",
".",
"get",
"(",
"\"topology\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"nodes\"",
",",
"[",
"]",
")",
... | Convert topologies from GNS3 2.0.0 alpha to 2.0.0 final.
Changes:
* No more serial console
* No more option for VMware / VirtualBox remote console (always use telnet) | [
"Convert",
"topologies",
"from",
"GNS3",
"2",
".",
"0",
".",
"0",
"alpha",
"to",
"2",
".",
"0",
".",
"0",
"final",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/topology.py#L225-L241 | train | 221,598 |
GNS3/gns3-server | gns3server/controller/topology.py | _convert_label | def _convert_label(label):
"""
Convert a label from 1.X to the new format
"""
style = qt_font_to_style(label.get("font"), label.get("color"))
return {
"text": html.escape(label["text"]),
"rotation": 0,
"style": style,
"x": int(label["x"]),
"y": int(label["y"])
} | python | def _convert_label(label):
"""
Convert a label from 1.X to the new format
"""
style = qt_font_to_style(label.get("font"), label.get("color"))
return {
"text": html.escape(label["text"]),
"rotation": 0,
"style": style,
"x": int(label["x"]),
"y": int(label["y"])
} | [
"def",
"_convert_label",
"(",
"label",
")",
":",
"style",
"=",
"qt_font_to_style",
"(",
"label",
".",
"get",
"(",
"\"font\"",
")",
",",
"label",
".",
"get",
"(",
"\"color\"",
")",
")",
"return",
"{",
"\"text\"",
":",
"html",
".",
"escape",
"(",
"label"... | Convert a label from 1.X to the new format | [
"Convert",
"a",
"label",
"from",
"1",
".",
"X",
"to",
"the",
"new",
"format"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/topology.py#L573-L584 | train | 221,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.