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/compute.py | Compute.interfaces | def interfaces(self):
"""
Get the list of network on compute
"""
if not self._interfaces_cache:
response = yield from self.get("/network/interfaces")
self._interfaces_cache = response.json
return self._interfaces_cache | python | def interfaces(self):
"""
Get the list of network on compute
"""
if not self._interfaces_cache:
response = yield from self.get("/network/interfaces")
self._interfaces_cache = response.json
return self._interfaces_cache | [
"def",
"interfaces",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_interfaces_cache",
":",
"response",
"=",
"yield",
"from",
"self",
".",
"get",
"(",
"\"/network/interfaces\"",
")",
"self",
".",
"_interfaces_cache",
"=",
"response",
".",
"json",
"return... | Get the list of network on compute | [
"Get",
"the",
"list",
"of",
"network",
"on",
"compute"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L141-L148 | train | 221,400 |
GNS3/gns3-server | gns3server/controller/compute.py | Compute.stream_file | def stream_file(self, project, path):
"""
Read file of a project and stream it
:param project: A project object
:param path: The path of the file in the project
:returns: A file stream
"""
# Due to Python 3.4 limitation we can't use with and asyncio
# https://www.python.org/dev/peps/pep-0492/
# that why we wrap the answer
class StreamResponse:
def __init__(self, response):
self._response = response
def __enter__(self):
return self._response.content
def __exit__(self):
self._response.close()
url = self._getUrl("/projects/{}/stream/{}".format(project.id, path))
response = yield from self._session().request("GET", url, auth=self._auth, timeout=None)
if response.status == 404:
raise aiohttp.web.HTTPNotFound(text="{} not found on compute".format(path))
elif response.status == 403:
raise aiohttp.web.HTTPForbidden(text="forbidden to open {} on compute".format(path))
elif response.status != 200:
raise aiohttp.web.HTTPInternalServerError(text="Unexpected error {}: {}: while opening {} on compute".format(response.status,
response.reason,
path))
return StreamResponse(response) | python | def stream_file(self, project, path):
"""
Read file of a project and stream it
:param project: A project object
:param path: The path of the file in the project
:returns: A file stream
"""
# Due to Python 3.4 limitation we can't use with and asyncio
# https://www.python.org/dev/peps/pep-0492/
# that why we wrap the answer
class StreamResponse:
def __init__(self, response):
self._response = response
def __enter__(self):
return self._response.content
def __exit__(self):
self._response.close()
url = self._getUrl("/projects/{}/stream/{}".format(project.id, path))
response = yield from self._session().request("GET", url, auth=self._auth, timeout=None)
if response.status == 404:
raise aiohttp.web.HTTPNotFound(text="{} not found on compute".format(path))
elif response.status == 403:
raise aiohttp.web.HTTPForbidden(text="forbidden to open {} on compute".format(path))
elif response.status != 200:
raise aiohttp.web.HTTPInternalServerError(text="Unexpected error {}: {}: while opening {} on compute".format(response.status,
response.reason,
path))
return StreamResponse(response) | [
"def",
"stream_file",
"(",
"self",
",",
"project",
",",
"path",
")",
":",
"# Due to Python 3.4 limitation we can't use with and asyncio",
"# https://www.python.org/dev/peps/pep-0492/",
"# that why we wrap the answer",
"class",
"StreamResponse",
":",
"def",
"__init__",
"(",
"sel... | Read file of a project and stream it
:param project: A project object
:param path: The path of the file in the project
:returns: A file stream | [
"Read",
"file",
"of",
"a",
"project",
"and",
"stream",
"it"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L340-L373 | train | 221,401 |
GNS3/gns3-server | gns3server/controller/compute.py | Compute.connect | def connect(self):
"""
Check if remote server is accessible
"""
if not self._connected and not self._closed:
try:
log.info("Connecting to compute '{}'".format(self._id))
response = yield from self._run_http_query("GET", "/capabilities")
except ComputeError as e:
# Try to reconnect after 2 seconds if server unavailable only if not during tests (otherwise we create a ressources usage bomb)
if not hasattr(sys, "_called_from_test") or not sys._called_from_test:
self._connection_failure += 1
# After 5 failure we close the project using the compute to avoid sync issues
if self._connection_failure == 5:
log.warning("Cannot connect to compute '{}': {}".format(self._id, e))
yield from self._controller.close_compute_projects(self)
asyncio.get_event_loop().call_later(2, lambda: asyncio.async(self._try_reconnect()))
return
except aiohttp.web.HTTPNotFound:
raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server or it's a 1.X server".format(self._id))
except aiohttp.web.HTTPUnauthorized:
raise aiohttp.web.HTTPConflict(text="Invalid auth for server {}".format(self._id))
except aiohttp.web.HTTPServiceUnavailable:
raise aiohttp.web.HTTPConflict(text="The server {} is unavailable".format(self._id))
except ValueError:
raise aiohttp.web.HTTPConflict(text="Invalid server url for server {}".format(self._id))
if "version" not in response.json:
self._http_session.close()
raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server".format(self._id))
self._capabilities = response.json
if parse_version(__version__)[:2] != parse_version(response.json["version"])[:2]:
self._http_session.close()
raise aiohttp.web.HTTPConflict(text="The server {} versions are not compatible {} != {}".format(self._id, __version__, response.json["version"]))
self._notifications = asyncio.gather(self._connect_notification())
self._connected = True
self._connection_failure = 0
self._controller.notification.emit("compute.updated", self.__json__()) | python | def connect(self):
"""
Check if remote server is accessible
"""
if not self._connected and not self._closed:
try:
log.info("Connecting to compute '{}'".format(self._id))
response = yield from self._run_http_query("GET", "/capabilities")
except ComputeError as e:
# Try to reconnect after 2 seconds if server unavailable only if not during tests (otherwise we create a ressources usage bomb)
if not hasattr(sys, "_called_from_test") or not sys._called_from_test:
self._connection_failure += 1
# After 5 failure we close the project using the compute to avoid sync issues
if self._connection_failure == 5:
log.warning("Cannot connect to compute '{}': {}".format(self._id, e))
yield from self._controller.close_compute_projects(self)
asyncio.get_event_loop().call_later(2, lambda: asyncio.async(self._try_reconnect()))
return
except aiohttp.web.HTTPNotFound:
raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server or it's a 1.X server".format(self._id))
except aiohttp.web.HTTPUnauthorized:
raise aiohttp.web.HTTPConflict(text="Invalid auth for server {}".format(self._id))
except aiohttp.web.HTTPServiceUnavailable:
raise aiohttp.web.HTTPConflict(text="The server {} is unavailable".format(self._id))
except ValueError:
raise aiohttp.web.HTTPConflict(text="Invalid server url for server {}".format(self._id))
if "version" not in response.json:
self._http_session.close()
raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server".format(self._id))
self._capabilities = response.json
if parse_version(__version__)[:2] != parse_version(response.json["version"])[:2]:
self._http_session.close()
raise aiohttp.web.HTTPConflict(text="The server {} versions are not compatible {} != {}".format(self._id, __version__, response.json["version"]))
self._notifications = asyncio.gather(self._connect_notification())
self._connected = True
self._connection_failure = 0
self._controller.notification.emit("compute.updated", self.__json__()) | [
"def",
"connect",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_connected",
"and",
"not",
"self",
".",
"_closed",
":",
"try",
":",
"log",
".",
"info",
"(",
"\"Connecting to compute '{}'\"",
".",
"format",
"(",
"self",
".",
"_id",
")",
")",
"respon... | Check if remote server is accessible | [
"Check",
"if",
"remote",
"server",
"is",
"accessible"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L401-L440 | train | 221,402 |
GNS3/gns3-server | gns3server/controller/compute.py | Compute._connect_notification | def _connect_notification(self):
"""
Connect to the notification stream
"""
try:
self._ws = yield from self._session().ws_connect(self._getUrl("/notifications/ws"), auth=self._auth)
except (aiohttp.WSServerHandshakeError, aiohttp.ClientResponseError):
self._ws = None
while self._ws is not None:
try:
response = yield from self._ws.receive()
except aiohttp.WSServerHandshakeError:
self._ws = None
break
if response.tp == aiohttp.WSMsgType.closed or response.tp == aiohttp.WSMsgType.error or response.data is None:
self._connected = False
break
msg = json.loads(response.data)
action = msg.pop("action")
event = msg.pop("event")
if action == "ping":
self._cpu_usage_percent = event["cpu_usage_percent"]
self._memory_usage_percent = event["memory_usage_percent"]
self._controller.notification.emit("compute.updated", self.__json__())
else:
yield from self._controller.notification.dispatch(action, event, compute_id=self.id)
if self._ws:
yield from self._ws.close()
# Try to reconnect after 1 seconds if server unavailable only if not during tests (otherwise we create a ressources usage bomb)
if not hasattr(sys, "_called_from_test") or not sys._called_from_test:
asyncio.get_event_loop().call_later(1, lambda: asyncio.async(self.connect()))
self._ws = None
self._cpu_usage_percent = None
self._memory_usage_percent = None
self._controller.notification.emit("compute.updated", self.__json__()) | python | def _connect_notification(self):
"""
Connect to the notification stream
"""
try:
self._ws = yield from self._session().ws_connect(self._getUrl("/notifications/ws"), auth=self._auth)
except (aiohttp.WSServerHandshakeError, aiohttp.ClientResponseError):
self._ws = None
while self._ws is not None:
try:
response = yield from self._ws.receive()
except aiohttp.WSServerHandshakeError:
self._ws = None
break
if response.tp == aiohttp.WSMsgType.closed or response.tp == aiohttp.WSMsgType.error or response.data is None:
self._connected = False
break
msg = json.loads(response.data)
action = msg.pop("action")
event = msg.pop("event")
if action == "ping":
self._cpu_usage_percent = event["cpu_usage_percent"]
self._memory_usage_percent = event["memory_usage_percent"]
self._controller.notification.emit("compute.updated", self.__json__())
else:
yield from self._controller.notification.dispatch(action, event, compute_id=self.id)
if self._ws:
yield from self._ws.close()
# Try to reconnect after 1 seconds if server unavailable only if not during tests (otherwise we create a ressources usage bomb)
if not hasattr(sys, "_called_from_test") or not sys._called_from_test:
asyncio.get_event_loop().call_later(1, lambda: asyncio.async(self.connect()))
self._ws = None
self._cpu_usage_percent = None
self._memory_usage_percent = None
self._controller.notification.emit("compute.updated", self.__json__()) | [
"def",
"_connect_notification",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_ws",
"=",
"yield",
"from",
"self",
".",
"_session",
"(",
")",
".",
"ws_connect",
"(",
"self",
".",
"_getUrl",
"(",
"\"/notifications/ws\"",
")",
",",
"auth",
"=",
"self",
... | Connect to the notification stream | [
"Connect",
"to",
"the",
"notification",
"stream"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L443-L479 | train | 221,403 |
GNS3/gns3-server | gns3server/controller/compute.py | Compute.forward | def forward(self, method, type, path, data=None):
"""
Forward a call to the emulator on compute
"""
try:
action = "/{}/{}".format(type, path)
res = yield from self.http_query(method, action, data=data, timeout=None)
except aiohttp.ServerDisconnectedError:
log.error("Connection lost to %s during %s %s", self._id, method, action)
raise aiohttp.web.HTTPGatewayTimeout()
return res.json | python | def forward(self, method, type, path, data=None):
"""
Forward a call to the emulator on compute
"""
try:
action = "/{}/{}".format(type, path)
res = yield from self.http_query(method, action, data=data, timeout=None)
except aiohttp.ServerDisconnectedError:
log.error("Connection lost to %s during %s %s", self._id, method, action)
raise aiohttp.web.HTTPGatewayTimeout()
return res.json | [
"def",
"forward",
"(",
"self",
",",
"method",
",",
"type",
",",
"path",
",",
"data",
"=",
"None",
")",
":",
"try",
":",
"action",
"=",
"\"/{}/{}\"",
".",
"format",
"(",
"type",
",",
"path",
")",
"res",
"=",
"yield",
"from",
"self",
".",
"http_query... | Forward a call to the emulator on compute | [
"Forward",
"a",
"call",
"to",
"the",
"emulator",
"on",
"compute"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L604-L614 | train | 221,404 |
GNS3/gns3-server | gns3server/controller/compute.py | Compute.images | def images(self, type):
"""
Return the list of images available for this type on controller
and on the compute node.
"""
images = []
res = yield from self.http_query("GET", "/{}/images".format(type), timeout=None)
images = res.json
try:
if type in ["qemu", "dynamips", "iou"]:
for local_image in list_images(type):
if local_image['filename'] not in [i['filename'] for i in images]:
images.append(local_image)
images = sorted(images, key=itemgetter('filename'))
else:
images = sorted(images, key=itemgetter('image'))
except OSError as e:
raise ComputeError("Can't list images: {}".format(str(e)))
return images | python | def images(self, type):
"""
Return the list of images available for this type on controller
and on the compute node.
"""
images = []
res = yield from self.http_query("GET", "/{}/images".format(type), timeout=None)
images = res.json
try:
if type in ["qemu", "dynamips", "iou"]:
for local_image in list_images(type):
if local_image['filename'] not in [i['filename'] for i in images]:
images.append(local_image)
images = sorted(images, key=itemgetter('filename'))
else:
images = sorted(images, key=itemgetter('image'))
except OSError as e:
raise ComputeError("Can't list images: {}".format(str(e)))
return images | [
"def",
"images",
"(",
"self",
",",
"type",
")",
":",
"images",
"=",
"[",
"]",
"res",
"=",
"yield",
"from",
"self",
".",
"http_query",
"(",
"\"GET\"",
",",
"\"/{}/images\"",
".",
"format",
"(",
"type",
")",
",",
"timeout",
"=",
"None",
")",
"images",
... | Return the list of images available for this type on controller
and on the compute node. | [
"Return",
"the",
"list",
"of",
"images",
"available",
"for",
"this",
"type",
"on",
"controller",
"and",
"on",
"the",
"compute",
"node",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L617-L637 | train | 221,405 |
GNS3/gns3-server | gns3server/controller/compute.py | Compute.list_files | def list_files(self, project):
"""
List files in the project on computes
"""
path = "/projects/{}/files".format(project.id)
res = yield from self.http_query("GET", path, timeout=120)
return res.json | python | def list_files(self, project):
"""
List files in the project on computes
"""
path = "/projects/{}/files".format(project.id)
res = yield from self.http_query("GET", path, timeout=120)
return res.json | [
"def",
"list_files",
"(",
"self",
",",
"project",
")",
":",
"path",
"=",
"\"/projects/{}/files\"",
".",
"format",
"(",
"project",
".",
"id",
")",
"res",
"=",
"yield",
"from",
"self",
".",
"http_query",
"(",
"\"GET\"",
",",
"path",
",",
"timeout",
"=",
... | List files in the project on computes | [
"List",
"files",
"in",
"the",
"project",
"on",
"computes"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L640-L646 | train | 221,406 |
GNS3/gns3-server | gns3server/controller/compute.py | Compute.get_ip_on_same_subnet | def get_ip_on_same_subnet(self, other_compute):
"""
Try to found the best ip for communication from one compute
to another
:returns: Tuple (ip_for_this_compute, ip_for_other_compute)
"""
if other_compute == self:
return (self.host_ip, self.host_ip)
# Perhaps the user has correct network gateway, we trust him
if (self.host_ip not in ('0.0.0.0', '127.0.0.1') and other_compute.host_ip not in ('0.0.0.0', '127.0.0.1')):
return (self.host_ip, other_compute.host_ip)
this_compute_interfaces = yield from self.interfaces()
other_compute_interfaces = yield from other_compute.interfaces()
# Sort interface to put the compute host in first position
# we guess that if user specified this host it could have a reason (VMware Nat / Host only interface)
this_compute_interfaces = sorted(this_compute_interfaces, key=lambda i: i["ip_address"] != self.host_ip)
other_compute_interfaces = sorted(other_compute_interfaces, key=lambda i: i["ip_address"] != other_compute.host_ip)
for this_interface in this_compute_interfaces:
# Skip if no ip or no netmask (vbox when stopped set a null netmask)
if len(this_interface["ip_address"]) == 0 or this_interface["netmask"] is None:
continue
# Ignore 169.254 network because it's for Windows special purpose
if this_interface["ip_address"].startswith("169.254."):
continue
this_network = ipaddress.ip_network("{}/{}".format(this_interface["ip_address"], this_interface["netmask"]), strict=False)
for other_interface in other_compute_interfaces:
if len(other_interface["ip_address"]) == 0 or other_interface["netmask"] is None:
continue
# Avoid stuff like 127.0.0.1
if other_interface["ip_address"] == this_interface["ip_address"]:
continue
other_network = ipaddress.ip_network("{}/{}".format(other_interface["ip_address"], other_interface["netmask"]), strict=False)
if this_network.overlaps(other_network):
return (this_interface["ip_address"], other_interface["ip_address"])
raise ValueError("No common subnet for compute {} and {}".format(self.name, other_compute.name)) | python | def get_ip_on_same_subnet(self, other_compute):
"""
Try to found the best ip for communication from one compute
to another
:returns: Tuple (ip_for_this_compute, ip_for_other_compute)
"""
if other_compute == self:
return (self.host_ip, self.host_ip)
# Perhaps the user has correct network gateway, we trust him
if (self.host_ip not in ('0.0.0.0', '127.0.0.1') and other_compute.host_ip not in ('0.0.0.0', '127.0.0.1')):
return (self.host_ip, other_compute.host_ip)
this_compute_interfaces = yield from self.interfaces()
other_compute_interfaces = yield from other_compute.interfaces()
# Sort interface to put the compute host in first position
# we guess that if user specified this host it could have a reason (VMware Nat / Host only interface)
this_compute_interfaces = sorted(this_compute_interfaces, key=lambda i: i["ip_address"] != self.host_ip)
other_compute_interfaces = sorted(other_compute_interfaces, key=lambda i: i["ip_address"] != other_compute.host_ip)
for this_interface in this_compute_interfaces:
# Skip if no ip or no netmask (vbox when stopped set a null netmask)
if len(this_interface["ip_address"]) == 0 or this_interface["netmask"] is None:
continue
# Ignore 169.254 network because it's for Windows special purpose
if this_interface["ip_address"].startswith("169.254."):
continue
this_network = ipaddress.ip_network("{}/{}".format(this_interface["ip_address"], this_interface["netmask"]), strict=False)
for other_interface in other_compute_interfaces:
if len(other_interface["ip_address"]) == 0 or other_interface["netmask"] is None:
continue
# Avoid stuff like 127.0.0.1
if other_interface["ip_address"] == this_interface["ip_address"]:
continue
other_network = ipaddress.ip_network("{}/{}".format(other_interface["ip_address"], other_interface["netmask"]), strict=False)
if this_network.overlaps(other_network):
return (this_interface["ip_address"], other_interface["ip_address"])
raise ValueError("No common subnet for compute {} and {}".format(self.name, other_compute.name)) | [
"def",
"get_ip_on_same_subnet",
"(",
"self",
",",
"other_compute",
")",
":",
"if",
"other_compute",
"==",
"self",
":",
"return",
"(",
"self",
".",
"host_ip",
",",
"self",
".",
"host_ip",
")",
"# Perhaps the user has correct network gateway, we trust him",
"if",
"(",... | Try to found the best ip for communication from one compute
to another
:returns: Tuple (ip_for_this_compute, ip_for_other_compute) | [
"Try",
"to",
"found",
"the",
"best",
"ip",
"for",
"communication",
"from",
"one",
"compute",
"to",
"another"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/compute.py#L649-L693 | train | 221,407 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/frame_relay_switch.py | FrameRelaySwitch.add_nio | def add_nio(self, nio, port_number):
"""
Adds a NIO as new port on Frame Relay switch.
:param nio: NIO instance to add
:param port_number: port to allocate for the NIO
"""
if port_number in self._nios:
raise DynamipsError("Port {} isn't free".format(port_number))
log.info('Frame Relay switch "{name}" [{id}]: NIO {nio} bound to port {port}'.format(name=self._name,
id=self._id,
nio=nio,
port=port_number))
self._nios[port_number] = nio
yield from self.set_mappings(self._mappings) | python | def add_nio(self, nio, port_number):
"""
Adds a NIO as new port on Frame Relay switch.
:param nio: NIO instance to add
:param port_number: port to allocate for the NIO
"""
if port_number in self._nios:
raise DynamipsError("Port {} isn't free".format(port_number))
log.info('Frame Relay switch "{name}" [{id}]: NIO {nio} bound to port {port}'.format(name=self._name,
id=self._id,
nio=nio,
port=port_number))
self._nios[port_number] = nio
yield from self.set_mappings(self._mappings) | [
"def",
"add_nio",
"(",
"self",
",",
"nio",
",",
"port_number",
")",
":",
"if",
"port_number",
"in",
"self",
".",
"_nios",
":",
"raise",
"DynamipsError",
"(",
"\"Port {} isn't free\"",
".",
"format",
"(",
"port_number",
")",
")",
"log",
".",
"info",
"(",
... | Adds a NIO as new port on Frame Relay switch.
:param nio: NIO instance to add
:param port_number: port to allocate for the NIO | [
"Adds",
"a",
"NIO",
"as",
"new",
"port",
"on",
"Frame",
"Relay",
"switch",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/frame_relay_switch.py#L160-L177 | train | 221,408 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/frame_relay_switch.py | FrameRelaySwitch.remove_nio | def remove_nio(self, port_number):
"""
Removes the specified NIO as member of this Frame Relay switch.
:param port_number: allocated port number
:returns: the NIO that was bound to the allocated port
"""
if port_number not in self._nios:
raise DynamipsError("Port {} is not allocated".format(port_number))
# remove VCs mapped with the port
for source, destination in self._active_mappings.copy().items():
source_port, source_dlci = source
destination_port, destination_dlci = destination
if port_number == source_port:
log.info('Frame Relay switch "{name}" [{id}]: unmapping VC between port {source_port} DLCI {source_dlci} and port {destination_port} DLCI {destination_dlci}'.format(name=self._name,
id=self._id,
source_port=source_port,
source_dlci=source_dlci,
destination_port=destination_port,
destination_dlci=destination_dlci))
yield from self.unmap_vc(source_port, source_dlci, destination_port, destination_dlci)
yield from self.unmap_vc(destination_port, destination_dlci, source_port, source_dlci)
nio = self._nios[port_number]
if isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
log.info('Frame Relay switch "{name}" [{id}]: NIO {nio} removed from port {port}'.format(name=self._name,
id=self._id,
nio=nio,
port=port_number))
del self._nios[port_number]
return nio | python | def remove_nio(self, port_number):
"""
Removes the specified NIO as member of this Frame Relay switch.
:param port_number: allocated port number
:returns: the NIO that was bound to the allocated port
"""
if port_number not in self._nios:
raise DynamipsError("Port {} is not allocated".format(port_number))
# remove VCs mapped with the port
for source, destination in self._active_mappings.copy().items():
source_port, source_dlci = source
destination_port, destination_dlci = destination
if port_number == source_port:
log.info('Frame Relay switch "{name}" [{id}]: unmapping VC between port {source_port} DLCI {source_dlci} and port {destination_port} DLCI {destination_dlci}'.format(name=self._name,
id=self._id,
source_port=source_port,
source_dlci=source_dlci,
destination_port=destination_port,
destination_dlci=destination_dlci))
yield from self.unmap_vc(source_port, source_dlci, destination_port, destination_dlci)
yield from self.unmap_vc(destination_port, destination_dlci, source_port, source_dlci)
nio = self._nios[port_number]
if isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
log.info('Frame Relay switch "{name}" [{id}]: NIO {nio} removed from port {port}'.format(name=self._name,
id=self._id,
nio=nio,
port=port_number))
del self._nios[port_number]
return nio | [
"def",
"remove_nio",
"(",
"self",
",",
"port_number",
")",
":",
"if",
"port_number",
"not",
"in",
"self",
".",
"_nios",
":",
"raise",
"DynamipsError",
"(",
"\"Port {} is not allocated\"",
".",
"format",
"(",
"port_number",
")",
")",
"# remove VCs mapped with the p... | Removes the specified NIO as member of this Frame Relay switch.
:param port_number: allocated port number
:returns: the NIO that was bound to the allocated port | [
"Removes",
"the",
"specified",
"NIO",
"as",
"member",
"of",
"this",
"Frame",
"Relay",
"switch",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/frame_relay_switch.py#L180-L216 | train | 221,409 |
GNS3/gns3-server | gns3server/main.py | main | def main():
"""
Entry point for GNS3 server
"""
if not sys.platform.startswith("win"):
if "--daemon" in sys.argv:
daemonize()
from gns3server.run import run
run() | python | def main():
"""
Entry point for GNS3 server
"""
if not sys.platform.startswith("win"):
if "--daemon" in sys.argv:
daemonize()
from gns3server.run import run
run() | [
"def",
"main",
"(",
")",
":",
"if",
"not",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"if",
"\"--daemon\"",
"in",
"sys",
".",
"argv",
":",
"daemonize",
"(",
")",
"from",
"gns3server",
".",
"run",
"import",
"run",
"run",
"(",... | Entry point for GNS3 server | [
"Entry",
"point",
"for",
"GNS3",
"server"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/main.py#L74-L83 | train | 221,410 |
GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM._get_free_display_port | def _get_free_display_port(self):
"""
Search a free display port
"""
display = 100
if not os.path.exists("/tmp/.X11-unix/"):
return display
while True:
if not os.path.exists("/tmp/.X11-unix/X{}".format(display)):
return display
display += 1 | python | def _get_free_display_port(self):
"""
Search a free display port
"""
display = 100
if not os.path.exists("/tmp/.X11-unix/"):
return display
while True:
if not os.path.exists("/tmp/.X11-unix/X{}".format(display)):
return display
display += 1 | [
"def",
"_get_free_display_port",
"(",
"self",
")",
":",
"display",
"=",
"100",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"\"/tmp/.X11-unix/\"",
")",
":",
"return",
"display",
"while",
"True",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
... | Search a free display port | [
"Search",
"a",
"free",
"display",
"port"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L120-L130 | train | 221,411 |
GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM.create | def create(self):
"""Creates the Docker container."""
try:
image_infos = yield from self._get_image_information()
except DockerHttp404Error:
log.info("Image %s is missing pulling it from docker hub", self._image)
yield from self.pull_image(self._image)
image_infos = yield from self._get_image_information()
if image_infos is None:
raise DockerError("Can't get image informations, please try again.")
params = {
"Hostname": self._name,
"Name": self._name,
"Image": self._image,
"NetworkDisabled": True,
"Tty": True,
"OpenStdin": True,
"StdinOnce": False,
"HostConfig": {
"CapAdd": ["ALL"],
"Privileged": True,
"Binds": self._mount_binds(image_infos)
},
"Volumes": {},
"Env": ["container=docker"], # Systemd compliant: https://github.com/GNS3/gns3-server/issues/573
"Cmd": [],
"Entrypoint": image_infos.get("Config", {"Entrypoint": []})["Entrypoint"]
}
if params["Entrypoint"] is None:
params["Entrypoint"] = []
if self._start_command:
params["Cmd"] = shlex.split(self._start_command)
if len(params["Cmd"]) == 0:
params["Cmd"] = image_infos.get("Config", {"Cmd": []})["Cmd"]
if params["Cmd"] is None:
params["Cmd"] = []
if len(params["Cmd"]) == 0 and len(params["Entrypoint"]) == 0:
params["Cmd"] = ["/bin/sh"]
params["Entrypoint"].insert(0, "/gns3/init.sh") # FIXME /gns3/init.sh is not found?
# Give the information to the container on how many interface should be inside
params["Env"].append("GNS3_MAX_ETHERNET=eth{}".format(self.adapters - 1))
# Give the information to the container the list of volume path mounted
params["Env"].append("GNS3_VOLUMES={}".format(":".join(self._volumes)))
if self._environment:
for e in self._environment.strip().split("\n"):
e = e.strip()
if not e.startswith("GNS3_"):
params["Env"].append(e)
if self._console_type == "vnc":
yield from self._start_vnc()
params["Env"].append("QT_GRAPHICSSYSTEM=native") # To fix a Qt issue: https://github.com/GNS3/gns3-server/issues/556
params["Env"].append("DISPLAY=:{}".format(self._display))
params["HostConfig"]["Binds"].append("/tmp/.X11-unix/:/tmp/.X11-unix/")
result = yield from self.manager.query("POST", "containers/create", data=params)
self._cid = result['Id']
log.info("Docker container '{name}' [{id}] created".format(
name=self._name, id=self._id))
return True | python | def create(self):
"""Creates the Docker container."""
try:
image_infos = yield from self._get_image_information()
except DockerHttp404Error:
log.info("Image %s is missing pulling it from docker hub", self._image)
yield from self.pull_image(self._image)
image_infos = yield from self._get_image_information()
if image_infos is None:
raise DockerError("Can't get image informations, please try again.")
params = {
"Hostname": self._name,
"Name": self._name,
"Image": self._image,
"NetworkDisabled": True,
"Tty": True,
"OpenStdin": True,
"StdinOnce": False,
"HostConfig": {
"CapAdd": ["ALL"],
"Privileged": True,
"Binds": self._mount_binds(image_infos)
},
"Volumes": {},
"Env": ["container=docker"], # Systemd compliant: https://github.com/GNS3/gns3-server/issues/573
"Cmd": [],
"Entrypoint": image_infos.get("Config", {"Entrypoint": []})["Entrypoint"]
}
if params["Entrypoint"] is None:
params["Entrypoint"] = []
if self._start_command:
params["Cmd"] = shlex.split(self._start_command)
if len(params["Cmd"]) == 0:
params["Cmd"] = image_infos.get("Config", {"Cmd": []})["Cmd"]
if params["Cmd"] is None:
params["Cmd"] = []
if len(params["Cmd"]) == 0 and len(params["Entrypoint"]) == 0:
params["Cmd"] = ["/bin/sh"]
params["Entrypoint"].insert(0, "/gns3/init.sh") # FIXME /gns3/init.sh is not found?
# Give the information to the container on how many interface should be inside
params["Env"].append("GNS3_MAX_ETHERNET=eth{}".format(self.adapters - 1))
# Give the information to the container the list of volume path mounted
params["Env"].append("GNS3_VOLUMES={}".format(":".join(self._volumes)))
if self._environment:
for e in self._environment.strip().split("\n"):
e = e.strip()
if not e.startswith("GNS3_"):
params["Env"].append(e)
if self._console_type == "vnc":
yield from self._start_vnc()
params["Env"].append("QT_GRAPHICSSYSTEM=native") # To fix a Qt issue: https://github.com/GNS3/gns3-server/issues/556
params["Env"].append("DISPLAY=:{}".format(self._display))
params["HostConfig"]["Binds"].append("/tmp/.X11-unix/:/tmp/.X11-unix/")
result = yield from self.manager.query("POST", "containers/create", data=params)
self._cid = result['Id']
log.info("Docker container '{name}' [{id}] created".format(
name=self._name, id=self._id))
return True | [
"def",
"create",
"(",
"self",
")",
":",
"try",
":",
"image_infos",
"=",
"yield",
"from",
"self",
".",
"_get_image_information",
"(",
")",
"except",
"DockerHttp404Error",
":",
"log",
".",
"info",
"(",
"\"Image %s is missing pulling it from docker hub\"",
",",
"self... | Creates the Docker container. | [
"Creates",
"the",
"Docker",
"container",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L268-L332 | train | 221,412 |
GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM.update | def update(self):
"""
Destroy an recreate the container with the new settings
"""
# We need to save the console and state and restore it
console = self.console
aux = self.aux
state = yield from self._get_container_state()
yield from self.reset()
yield from self.create()
self.console = console
self.aux = aux
if state == "running":
yield from self.start() | python | def update(self):
"""
Destroy an recreate the container with the new settings
"""
# We need to save the console and state and restore it
console = self.console
aux = self.aux
state = yield from self._get_container_state()
yield from self.reset()
yield from self.create()
self.console = console
self.aux = aux
if state == "running":
yield from self.start() | [
"def",
"update",
"(",
"self",
")",
":",
"# We need to save the console and state and restore it",
"console",
"=",
"self",
".",
"console",
"aux",
"=",
"self",
".",
"aux",
"state",
"=",
"yield",
"from",
"self",
".",
"_get_container_state",
"(",
")",
"yield",
"from... | Destroy an recreate the container with the new settings | [
"Destroy",
"an",
"recreate",
"the",
"container",
"with",
"the",
"new",
"settings"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L335-L349 | train | 221,413 |
GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM.start | def start(self):
"""Starts this Docker container."""
try:
state = yield from self._get_container_state()
except DockerHttp404Error:
raise DockerError("Docker container '{name}' with ID {cid} does not exist or is not ready yet. Please try again in a few seconds.".format(name=self.name,
cid=self._cid))
if state == "paused":
yield from self.unpause()
elif state == "running":
return
else:
yield from self._clean_servers()
yield from self.manager.query("POST", "containers/{}/start".format(self._cid))
self._namespace = yield from self._get_namespace()
yield from self._start_ubridge()
for adapter_number in range(0, self.adapters):
nio = self._ethernet_adapters[adapter_number].get_nio(0)
with (yield from self.manager.ubridge_lock):
try:
yield from self._add_ubridge_connection(nio, adapter_number)
except UbridgeNamespaceError:
log.error("Container %s failed to start", self.name)
yield from self.stop()
# The container can crash soon after the start, this means we can not move the interface to the container namespace
logdata = yield from self._get_log()
for line in logdata.split('\n'):
log.error(line)
raise DockerError(logdata)
if self.console_type == "telnet":
yield from self._start_console()
elif self.console_type == "http" or self.console_type == "https":
yield from self._start_http()
if self.allocate_aux:
yield from self._start_aux()
self.status = "started"
log.info("Docker container '{name}' [{image}] started listen for {console_type} on {console}".format(name=self._name,
image=self._image,
console=self.console,
console_type=self.console_type)) | python | def start(self):
"""Starts this Docker container."""
try:
state = yield from self._get_container_state()
except DockerHttp404Error:
raise DockerError("Docker container '{name}' with ID {cid} does not exist or is not ready yet. Please try again in a few seconds.".format(name=self.name,
cid=self._cid))
if state == "paused":
yield from self.unpause()
elif state == "running":
return
else:
yield from self._clean_servers()
yield from self.manager.query("POST", "containers/{}/start".format(self._cid))
self._namespace = yield from self._get_namespace()
yield from self._start_ubridge()
for adapter_number in range(0, self.adapters):
nio = self._ethernet_adapters[adapter_number].get_nio(0)
with (yield from self.manager.ubridge_lock):
try:
yield from self._add_ubridge_connection(nio, adapter_number)
except UbridgeNamespaceError:
log.error("Container %s failed to start", self.name)
yield from self.stop()
# The container can crash soon after the start, this means we can not move the interface to the container namespace
logdata = yield from self._get_log()
for line in logdata.split('\n'):
log.error(line)
raise DockerError(logdata)
if self.console_type == "telnet":
yield from self._start_console()
elif self.console_type == "http" or self.console_type == "https":
yield from self._start_http()
if self.allocate_aux:
yield from self._start_aux()
self.status = "started"
log.info("Docker container '{name}' [{image}] started listen for {console_type} on {console}".format(name=self._name,
image=self._image,
console=self.console,
console_type=self.console_type)) | [
"def",
"start",
"(",
"self",
")",
":",
"try",
":",
"state",
"=",
"yield",
"from",
"self",
".",
"_get_container_state",
"(",
")",
"except",
"DockerHttp404Error",
":",
"raise",
"DockerError",
"(",
"\"Docker container '{name}' with ID {cid} does not exist or is not ready y... | Starts this Docker container. | [
"Starts",
"this",
"Docker",
"container",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L352-L399 | train | 221,414 |
GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM._start_aux | def _start_aux(self):
"""
Start an auxilary console
"""
# We can not use the API because docker doesn't expose a websocket api for exec
# https://github.com/GNS3/gns3-gui/issues/1039
process = yield from asyncio.subprocess.create_subprocess_exec(
"docker", "exec", "-i", self._cid, "/gns3/bin/busybox", "script", "-qfc", "while true; do TERM=vt100 /gns3/bin/busybox sh; done", "/dev/null",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
stdin=asyncio.subprocess.PIPE)
server = AsyncioTelnetServer(reader=process.stdout, writer=process.stdin, binary=True, echo=True)
self._telnet_servers.append((yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.aux)))
log.debug("Docker container '%s' started listen for auxilary telnet on %d", self.name, self.aux) | python | def _start_aux(self):
"""
Start an auxilary console
"""
# We can not use the API because docker doesn't expose a websocket api for exec
# https://github.com/GNS3/gns3-gui/issues/1039
process = yield from asyncio.subprocess.create_subprocess_exec(
"docker", "exec", "-i", self._cid, "/gns3/bin/busybox", "script", "-qfc", "while true; do TERM=vt100 /gns3/bin/busybox sh; done", "/dev/null",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
stdin=asyncio.subprocess.PIPE)
server = AsyncioTelnetServer(reader=process.stdout, writer=process.stdin, binary=True, echo=True)
self._telnet_servers.append((yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.aux)))
log.debug("Docker container '%s' started listen for auxilary telnet on %d", self.name, self.aux) | [
"def",
"_start_aux",
"(",
"self",
")",
":",
"# We can not use the API because docker doesn't expose a websocket api for exec",
"# https://github.com/GNS3/gns3-gui/issues/1039",
"process",
"=",
"yield",
"from",
"asyncio",
".",
"subprocess",
".",
"create_subprocess_exec",
"(",
"\"d... | Start an auxilary console | [
"Start",
"an",
"auxilary",
"console"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L402-L416 | train | 221,415 |
GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM._fix_permissions | def _fix_permissions(self):
"""
Because docker run as root we need to fix permission and ownership to allow user to interact
with it from their filesystem and do operation like file delete
"""
state = yield from self._get_container_state()
if state == "stopped" or state == "exited":
# We need to restart it to fix permissions
yield from self.manager.query("POST", "containers/{}/start".format(self._cid))
for volume in self._volumes:
log.debug("Docker container '{name}' [{image}] fix ownership on {path}".format(
name=self._name, image=self._image, path=volume))
process = yield from asyncio.subprocess.create_subprocess_exec(
"docker",
"exec",
self._cid,
"/gns3/bin/busybox",
"sh",
"-c",
"("
"/gns3/bin/busybox find \"{path}\" -depth -print0"
" | /gns3/bin/busybox xargs -0 /gns3/bin/busybox stat -c '%a:%u:%g:%n' > \"{path}/.gns3_perms\""
")"
" && /gns3/bin/busybox chmod -R u+rX \"{path}\""
" && /gns3/bin/busybox chown {uid}:{gid} -R \"{path}\""
.format(uid=os.getuid(), gid=os.getgid(), path=volume),
)
yield from process.wait() | python | def _fix_permissions(self):
"""
Because docker run as root we need to fix permission and ownership to allow user to interact
with it from their filesystem and do operation like file delete
"""
state = yield from self._get_container_state()
if state == "stopped" or state == "exited":
# We need to restart it to fix permissions
yield from self.manager.query("POST", "containers/{}/start".format(self._cid))
for volume in self._volumes:
log.debug("Docker container '{name}' [{image}] fix ownership on {path}".format(
name=self._name, image=self._image, path=volume))
process = yield from asyncio.subprocess.create_subprocess_exec(
"docker",
"exec",
self._cid,
"/gns3/bin/busybox",
"sh",
"-c",
"("
"/gns3/bin/busybox find \"{path}\" -depth -print0"
" | /gns3/bin/busybox xargs -0 /gns3/bin/busybox stat -c '%a:%u:%g:%n' > \"{path}/.gns3_perms\""
")"
" && /gns3/bin/busybox chmod -R u+rX \"{path}\""
" && /gns3/bin/busybox chown {uid}:{gid} -R \"{path}\""
.format(uid=os.getuid(), gid=os.getgid(), path=volume),
)
yield from process.wait() | [
"def",
"_fix_permissions",
"(",
"self",
")",
":",
"state",
"=",
"yield",
"from",
"self",
".",
"_get_container_state",
"(",
")",
"if",
"state",
"==",
"\"stopped\"",
"or",
"state",
"==",
"\"exited\"",
":",
"# We need to restart it to fix permissions",
"yield",
"from... | Because docker run as root we need to fix permission and ownership to allow user to interact
with it from their filesystem and do operation like file delete | [
"Because",
"docker",
"run",
"as",
"root",
"we",
"need",
"to",
"fix",
"permission",
"and",
"ownership",
"to",
"allow",
"user",
"to",
"interact",
"with",
"it",
"from",
"their",
"filesystem",
"and",
"do",
"operation",
"like",
"file",
"delete"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L419-L448 | train | 221,416 |
GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM._start_vnc | def _start_vnc(self):
"""
Start a VNC server for this container
"""
self._display = self._get_free_display_port()
if shutil.which("Xvfb") is None or shutil.which("x11vnc") is None:
raise DockerError("Please install Xvfb and x11vnc before using the VNC support")
self._xvfb_process = yield from asyncio.create_subprocess_exec("Xvfb", "-nolisten", "tcp", ":{}".format(self._display), "-screen", "0", self._console_resolution + "x16")
# We pass a port for TCPV6 due to a crash in X11VNC if not here: https://github.com/GNS3/gns3-server/issues/569
self._x11vnc_process = yield from asyncio.create_subprocess_exec("x11vnc", "-forever", "-nopw", "-shared", "-geometry", self._console_resolution, "-display", "WAIT:{}".format(self._display), "-rfbport", str(self.console), "-rfbportv6", str(self.console), "-noncache", "-listen", self._manager.port_manager.console_host)
x11_socket = os.path.join("/tmp/.X11-unix/", "X{}".format(self._display))
yield from wait_for_file_creation(x11_socket) | python | def _start_vnc(self):
"""
Start a VNC server for this container
"""
self._display = self._get_free_display_port()
if shutil.which("Xvfb") is None or shutil.which("x11vnc") is None:
raise DockerError("Please install Xvfb and x11vnc before using the VNC support")
self._xvfb_process = yield from asyncio.create_subprocess_exec("Xvfb", "-nolisten", "tcp", ":{}".format(self._display), "-screen", "0", self._console_resolution + "x16")
# We pass a port for TCPV6 due to a crash in X11VNC if not here: https://github.com/GNS3/gns3-server/issues/569
self._x11vnc_process = yield from asyncio.create_subprocess_exec("x11vnc", "-forever", "-nopw", "-shared", "-geometry", self._console_resolution, "-display", "WAIT:{}".format(self._display), "-rfbport", str(self.console), "-rfbportv6", str(self.console), "-noncache", "-listen", self._manager.port_manager.console_host)
x11_socket = os.path.join("/tmp/.X11-unix/", "X{}".format(self._display))
yield from wait_for_file_creation(x11_socket) | [
"def",
"_start_vnc",
"(",
"self",
")",
":",
"self",
".",
"_display",
"=",
"self",
".",
"_get_free_display_port",
"(",
")",
"if",
"shutil",
".",
"which",
"(",
"\"Xvfb\"",
")",
"is",
"None",
"or",
"shutil",
".",
"which",
"(",
"\"x11vnc\"",
")",
"is",
"No... | Start a VNC server for this container | [
"Start",
"a",
"VNC",
"server",
"for",
"this",
"container"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L451-L464 | train | 221,417 |
GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM._start_http | def _start_http(self):
"""
Start an HTTP tunnel to container localhost. It's not perfect
but the only way we have to inject network packet is using nc.
"""
log.debug("Forward HTTP for %s to %d", self.name, self._console_http_port)
command = ["docker", "exec", "-i", self._cid, "/gns3/bin/busybox", "nc", "127.0.0.1", str(self._console_http_port)]
# We replace host and port in the server answer otherwise some link could be broken
server = AsyncioRawCommandServer(command, replaces=[
(
'://127.0.0.1'.encode(), # {{HOST}} mean client host
'://{{HOST}}'.encode(),
),
(
':{}'.format(self._console_http_port).encode(),
':{}'.format(self.console).encode(),
)
])
self._telnet_servers.append((yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console))) | python | def _start_http(self):
"""
Start an HTTP tunnel to container localhost. It's not perfect
but the only way we have to inject network packet is using nc.
"""
log.debug("Forward HTTP for %s to %d", self.name, self._console_http_port)
command = ["docker", "exec", "-i", self._cid, "/gns3/bin/busybox", "nc", "127.0.0.1", str(self._console_http_port)]
# We replace host and port in the server answer otherwise some link could be broken
server = AsyncioRawCommandServer(command, replaces=[
(
'://127.0.0.1'.encode(), # {{HOST}} mean client host
'://{{HOST}}'.encode(),
),
(
':{}'.format(self._console_http_port).encode(),
':{}'.format(self.console).encode(),
)
])
self._telnet_servers.append((yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console))) | [
"def",
"_start_http",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"Forward HTTP for %s to %d\"",
",",
"self",
".",
"name",
",",
"self",
".",
"_console_http_port",
")",
"command",
"=",
"[",
"\"docker\"",
",",
"\"exec\"",
",",
"\"-i\"",
",",
"self",
"... | Start an HTTP tunnel to container localhost. It's not perfect
but the only way we have to inject network packet is using nc. | [
"Start",
"an",
"HTTP",
"tunnel",
"to",
"container",
"localhost",
".",
"It",
"s",
"not",
"perfect",
"but",
"the",
"only",
"way",
"we",
"have",
"to",
"inject",
"network",
"packet",
"is",
"using",
"nc",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L467-L485 | train | 221,418 |
GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM._start_console | def _start_console(self):
"""
Start streaming the console via telnet
"""
class InputStream:
def __init__(self):
self._data = b""
def write(self, data):
self._data += data
@asyncio.coroutine
def drain(self):
if not self.ws.closed:
self.ws.send_bytes(self._data)
self._data = b""
output_stream = asyncio.StreamReader()
input_stream = InputStream()
telnet = AsyncioTelnetServer(reader=output_stream, writer=input_stream, echo=True)
self._telnet_servers.append((yield from asyncio.start_server(telnet.run, self._manager.port_manager.console_host, self.console)))
self._console_websocket = yield from self.manager.websocket_query("containers/{}/attach/ws?stream=1&stdin=1&stdout=1&stderr=1".format(self._cid))
input_stream.ws = self._console_websocket
output_stream.feed_data(self.name.encode() + b" console is now available... Press RETURN to get started.\r\n")
asyncio.async(self._read_console_output(self._console_websocket, output_stream)) | python | def _start_console(self):
"""
Start streaming the console via telnet
"""
class InputStream:
def __init__(self):
self._data = b""
def write(self, data):
self._data += data
@asyncio.coroutine
def drain(self):
if not self.ws.closed:
self.ws.send_bytes(self._data)
self._data = b""
output_stream = asyncio.StreamReader()
input_stream = InputStream()
telnet = AsyncioTelnetServer(reader=output_stream, writer=input_stream, echo=True)
self._telnet_servers.append((yield from asyncio.start_server(telnet.run, self._manager.port_manager.console_host, self.console)))
self._console_websocket = yield from self.manager.websocket_query("containers/{}/attach/ws?stream=1&stdin=1&stdout=1&stderr=1".format(self._cid))
input_stream.ws = self._console_websocket
output_stream.feed_data(self.name.encode() + b" console is now available... Press RETURN to get started.\r\n")
asyncio.async(self._read_console_output(self._console_websocket, output_stream)) | [
"def",
"_start_console",
"(",
"self",
")",
":",
"class",
"InputStream",
":",
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"_data",
"=",
"b\"\"",
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_data",
"+=",
"data",
"@",
... | Start streaming the console via telnet | [
"Start",
"streaming",
"the",
"console",
"via",
"telnet"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L488-L518 | train | 221,419 |
GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM._read_console_output | def _read_console_output(self, ws, out):
"""
Read Websocket and forward it to the telnet
:param ws: Websocket connection
:param out: Output stream
"""
while True:
msg = yield from ws.receive()
if msg.tp == aiohttp.WSMsgType.text:
out.feed_data(msg.data.encode())
elif msg.tp == aiohttp.WSMsgType.BINARY:
out.feed_data(msg.data)
elif msg.tp == aiohttp.WSMsgType.ERROR:
log.critical("Docker WebSocket Error: {}".format(msg.data))
else:
out.feed_eof()
ws.close()
break
yield from self.stop() | python | def _read_console_output(self, ws, out):
"""
Read Websocket and forward it to the telnet
:param ws: Websocket connection
:param out: Output stream
"""
while True:
msg = yield from ws.receive()
if msg.tp == aiohttp.WSMsgType.text:
out.feed_data(msg.data.encode())
elif msg.tp == aiohttp.WSMsgType.BINARY:
out.feed_data(msg.data)
elif msg.tp == aiohttp.WSMsgType.ERROR:
log.critical("Docker WebSocket Error: {}".format(msg.data))
else:
out.feed_eof()
ws.close()
break
yield from self.stop() | [
"def",
"_read_console_output",
"(",
"self",
",",
"ws",
",",
"out",
")",
":",
"while",
"True",
":",
"msg",
"=",
"yield",
"from",
"ws",
".",
"receive",
"(",
")",
"if",
"msg",
".",
"tp",
"==",
"aiohttp",
".",
"WSMsgType",
".",
"text",
":",
"out",
".",... | Read Websocket and forward it to the telnet
:param ws: Websocket connection
:param out: Output stream | [
"Read",
"Websocket",
"and",
"forward",
"it",
"to",
"the",
"telnet"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L521-L541 | train | 221,420 |
GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM.is_running | def is_running(self):
"""Checks if the container is running.
:returns: True or False
:rtype: bool
"""
state = yield from self._get_container_state()
if state == "running":
return True
if self.status == "started": # The container crashed we need to clean
yield from self.stop()
return False | python | def is_running(self):
"""Checks if the container is running.
:returns: True or False
:rtype: bool
"""
state = yield from self._get_container_state()
if state == "running":
return True
if self.status == "started": # The container crashed we need to clean
yield from self.stop()
return False | [
"def",
"is_running",
"(",
"self",
")",
":",
"state",
"=",
"yield",
"from",
"self",
".",
"_get_container_state",
"(",
")",
"if",
"state",
"==",
"\"running\"",
":",
"return",
"True",
"if",
"self",
".",
"status",
"==",
"\"started\"",
":",
"# The container crash... | Checks if the container is running.
:returns: True or False
:rtype: bool | [
"Checks",
"if",
"the",
"container",
"is",
"running",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L544-L555 | train | 221,421 |
GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM.restart | def restart(self):
"""Restart this Docker container."""
yield from self.manager.query("POST", "containers/{}/restart".format(self._cid))
log.info("Docker container '{name}' [{image}] restarted".format(
name=self._name, image=self._image)) | python | def restart(self):
"""Restart this Docker container."""
yield from self.manager.query("POST", "containers/{}/restart".format(self._cid))
log.info("Docker container '{name}' [{image}] restarted".format(
name=self._name, image=self._image)) | [
"def",
"restart",
"(",
"self",
")",
":",
"yield",
"from",
"self",
".",
"manager",
".",
"query",
"(",
"\"POST\"",
",",
"\"containers/{}/restart\"",
".",
"format",
"(",
"self",
".",
"_cid",
")",
")",
"log",
".",
"info",
"(",
"\"Docker container '{name}' [{imag... | Restart this Docker container. | [
"Restart",
"this",
"Docker",
"container",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L558-L562 | train | 221,422 |
GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM._clean_servers | def _clean_servers(self):
"""
Clean the list of running console servers
"""
if len(self._telnet_servers) > 0:
for telnet_server in self._telnet_servers:
telnet_server.close()
yield from telnet_server.wait_closed()
self._telnet_servers = [] | python | def _clean_servers(self):
"""
Clean the list of running console servers
"""
if len(self._telnet_servers) > 0:
for telnet_server in self._telnet_servers:
telnet_server.close()
yield from telnet_server.wait_closed()
self._telnet_servers = [] | [
"def",
"_clean_servers",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_telnet_servers",
")",
">",
"0",
":",
"for",
"telnet_server",
"in",
"self",
".",
"_telnet_servers",
":",
"telnet_server",
".",
"close",
"(",
")",
"yield",
"from",
"telnet_serve... | Clean the list of running console servers | [
"Clean",
"the",
"list",
"of",
"running",
"console",
"servers"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L565-L573 | train | 221,423 |
GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM.stop | def stop(self):
"""Stops this Docker container."""
try:
yield from self._clean_servers()
yield from self._stop_ubridge()
try:
state = yield from self._get_container_state()
except DockerHttp404Error:
self.status = "stopped"
return
if state == "paused":
yield from self.unpause()
yield from self._fix_permissions()
state = yield from self._get_container_state()
if state != "stopped" or state != "exited":
# t=5 number of seconds to wait before killing the container
try:
yield from self.manager.query("POST", "containers/{}/stop".format(self._cid), params={"t": 5})
log.info("Docker container '{name}' [{image}] stopped".format(
name=self._name, image=self._image))
except DockerHttp304Error:
# Container is already stopped
pass
# Ignore runtime error because when closing the server
except RuntimeError as e:
log.debug("Docker runtime error when closing: {}".format(str(e)))
return
self.status = "stopped" | python | def stop(self):
"""Stops this Docker container."""
try:
yield from self._clean_servers()
yield from self._stop_ubridge()
try:
state = yield from self._get_container_state()
except DockerHttp404Error:
self.status = "stopped"
return
if state == "paused":
yield from self.unpause()
yield from self._fix_permissions()
state = yield from self._get_container_state()
if state != "stopped" or state != "exited":
# t=5 number of seconds to wait before killing the container
try:
yield from self.manager.query("POST", "containers/{}/stop".format(self._cid), params={"t": 5})
log.info("Docker container '{name}' [{image}] stopped".format(
name=self._name, image=self._image))
except DockerHttp304Error:
# Container is already stopped
pass
# Ignore runtime error because when closing the server
except RuntimeError as e:
log.debug("Docker runtime error when closing: {}".format(str(e)))
return
self.status = "stopped" | [
"def",
"stop",
"(",
"self",
")",
":",
"try",
":",
"yield",
"from",
"self",
".",
"_clean_servers",
"(",
")",
"yield",
"from",
"self",
".",
"_stop_ubridge",
"(",
")",
"try",
":",
"state",
"=",
"yield",
"from",
"self",
".",
"_get_container_state",
"(",
")... | Stops this Docker container. | [
"Stops",
"this",
"Docker",
"container",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L576-L607 | train | 221,424 |
GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM.pause | def pause(self):
"""Pauses this Docker container."""
yield from self.manager.query("POST", "containers/{}/pause".format(self._cid))
self.status = "suspended"
log.info("Docker container '{name}' [{image}] paused".format(name=self._name, image=self._image)) | python | def pause(self):
"""Pauses this Docker container."""
yield from self.manager.query("POST", "containers/{}/pause".format(self._cid))
self.status = "suspended"
log.info("Docker container '{name}' [{image}] paused".format(name=self._name, image=self._image)) | [
"def",
"pause",
"(",
"self",
")",
":",
"yield",
"from",
"self",
".",
"manager",
".",
"query",
"(",
"\"POST\"",
",",
"\"containers/{}/pause\"",
".",
"format",
"(",
"self",
".",
"_cid",
")",
")",
"self",
".",
"status",
"=",
"\"suspended\"",
"log",
".",
"... | Pauses this Docker container. | [
"Pauses",
"this",
"Docker",
"container",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L610-L614 | train | 221,425 |
GNS3/gns3-server | gns3server/compute/docker/docker_vm.py | DockerVM._get_log | def _get_log(self):
"""
Return the log from the container
:returns: string
"""
result = yield from self.manager.query("GET", "containers/{}/logs".format(self._cid), params={"stderr": 1, "stdout": 1})
return result | python | def _get_log(self):
"""
Return the log from the container
:returns: string
"""
result = yield from self.manager.query("GET", "containers/{}/logs".format(self._cid), params={"stderr": 1, "stdout": 1})
return result | [
"def",
"_get_log",
"(",
"self",
")",
":",
"result",
"=",
"yield",
"from",
"self",
".",
"manager",
".",
"query",
"(",
"\"GET\"",
",",
"\"containers/{}/logs\"",
".",
"format",
"(",
"self",
".",
"_cid",
")",
",",
"params",
"=",
"{",
"\"stderr\"",
":",
"1"... | Return the log from the container
:returns: string | [
"Return",
"the",
"log",
"from",
"the",
"container"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/docker/docker_vm.py#L916-L924 | train | 221,426 |
GNS3/gns3-server | gns3server/compute/iou/utils/application_id.py | get_next_application_id | def get_next_application_id(nodes):
"""
Calculates free application_id from given nodes
:param nodes:
:raises IOUError when exceeds number
:return: integer first free id
"""
used = set([n.application_id for n in nodes])
pool = set(range(1, 512))
try:
return (pool - used).pop()
except KeyError:
raise IOUError("Cannot create a new IOU VM (limit of 512 VMs on one host reached)") | python | def get_next_application_id(nodes):
"""
Calculates free application_id from given nodes
:param nodes:
:raises IOUError when exceeds number
:return: integer first free id
"""
used = set([n.application_id for n in nodes])
pool = set(range(1, 512))
try:
return (pool - used).pop()
except KeyError:
raise IOUError("Cannot create a new IOU VM (limit of 512 VMs on one host reached)") | [
"def",
"get_next_application_id",
"(",
"nodes",
")",
":",
"used",
"=",
"set",
"(",
"[",
"n",
".",
"application_id",
"for",
"n",
"in",
"nodes",
"]",
")",
"pool",
"=",
"set",
"(",
"range",
"(",
"1",
",",
"512",
")",
")",
"try",
":",
"return",
"(",
... | Calculates free application_id from given nodes
:param nodes:
:raises IOUError when exceeds number
:return: integer first free id | [
"Calculates",
"free",
"application_id",
"from",
"given",
"nodes"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/utils/application_id.py#L24-L37 | train | 221,427 |
GNS3/gns3-server | gns3server/config.py | Config.clear | def clear(self):
"""Restart with a clean config"""
self._config = configparser.RawConfigParser()
# Override config from command line even if we modify the config file and live reload it.
self._override_config = {}
self.read_config() | python | def clear(self):
"""Restart with a clean config"""
self._config = configparser.RawConfigParser()
# Override config from command line even if we modify the config file and live reload it.
self._override_config = {}
self.read_config() | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"_config",
"=",
"configparser",
".",
"RawConfigParser",
"(",
")",
"# Override config from command line even if we modify the config file and live reload it.",
"self",
".",
"_override_config",
"=",
"{",
"}",
"self",
"."... | Restart with a clean config | [
"Restart",
"with",
"a",
"clean",
"config"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/config.py#L137-L143 | train | 221,428 |
GNS3/gns3-server | gns3server/config.py | Config.read_config | def read_config(self):
"""
Read the configuration files.
"""
try:
parsed_files = self._config.read(self._files, encoding="utf-8")
except configparser.Error as e:
log.error("Can't parse configuration file: %s", str(e))
return
if not parsed_files:
log.warning("No configuration file could be found or read")
else:
for file in parsed_files:
log.info("Load configuration file {}".format(file))
self._watched_files[file] = os.stat(file).st_mtime | python | def read_config(self):
"""
Read the configuration files.
"""
try:
parsed_files = self._config.read(self._files, encoding="utf-8")
except configparser.Error as e:
log.error("Can't parse configuration file: %s", str(e))
return
if not parsed_files:
log.warning("No configuration file could be found or read")
else:
for file in parsed_files:
log.info("Load configuration file {}".format(file))
self._watched_files[file] = os.stat(file).st_mtime | [
"def",
"read_config",
"(",
"self",
")",
":",
"try",
":",
"parsed_files",
"=",
"self",
".",
"_config",
".",
"read",
"(",
"self",
".",
"_files",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"except",
"configparser",
".",
"Error",
"as",
"e",
":",
"log",
".",
... | Read the configuration files. | [
"Read",
"the",
"configuration",
"files",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/config.py#L169-L184 | train | 221,429 |
GNS3/gns3-server | gns3server/config.py | Config.get_section_config | def get_section_config(self, section):
"""
Get a specific configuration section.
Returns the default section if none can be found.
:returns: configparser section
"""
if section not in self._config:
return self._config["DEFAULT"]
return self._config[section] | python | def get_section_config(self, section):
"""
Get a specific configuration section.
Returns the default section if none can be found.
:returns: configparser section
"""
if section not in self._config:
return self._config["DEFAULT"]
return self._config[section] | [
"def",
"get_section_config",
"(",
"self",
",",
"section",
")",
":",
"if",
"section",
"not",
"in",
"self",
".",
"_config",
":",
"return",
"self",
".",
"_config",
"[",
"\"DEFAULT\"",
"]",
"return",
"self",
".",
"_config",
"[",
"section",
"]"
] | Get a specific configuration section.
Returns the default section if none can be found.
:returns: configparser section | [
"Get",
"a",
"specific",
"configuration",
"section",
".",
"Returns",
"the",
"default",
"section",
"if",
"none",
"can",
"be",
"found",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/config.py#L195-L205 | train | 221,430 |
GNS3/gns3-server | gns3server/config.py | Config.set_section_config | def set_section_config(self, section, content):
"""
Set a specific configuration section. It's not
dumped on the disk.
:param section: Section name
:param content: A dictionary with section content
"""
if not self._config.has_section(section):
self._config.add_section(section)
for key in content:
if isinstance(content[key], bool):
content[key] = str(content[key]).lower()
self._config.set(section, key, content[key])
self._override_config[section] = content | python | def set_section_config(self, section, content):
"""
Set a specific configuration section. It's not
dumped on the disk.
:param section: Section name
:param content: A dictionary with section content
"""
if not self._config.has_section(section):
self._config.add_section(section)
for key in content:
if isinstance(content[key], bool):
content[key] = str(content[key]).lower()
self._config.set(section, key, content[key])
self._override_config[section] = content | [
"def",
"set_section_config",
"(",
"self",
",",
"section",
",",
"content",
")",
":",
"if",
"not",
"self",
".",
"_config",
".",
"has_section",
"(",
"section",
")",
":",
"self",
".",
"_config",
".",
"add_section",
"(",
"section",
")",
"for",
"key",
"in",
... | Set a specific configuration section. It's not
dumped on the disk.
:param section: Section name
:param content: A dictionary with section content | [
"Set",
"a",
"specific",
"configuration",
"section",
".",
"It",
"s",
"not",
"dumped",
"on",
"the",
"disk",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/config.py#L207-L222 | train | 221,431 |
GNS3/gns3-server | gns3server/config.py | Config.set | def set(self, section, key, value):
"""
Set a config value.
It's not dumped on the disk.
If the section doesn't exists the section is created
"""
conf = self.get_section_config(section)
if isinstance(value, bool):
conf[key] = str(value)
else:
conf[key] = value
self.set_section_config(section, conf) | python | def set(self, section, key, value):
"""
Set a config value.
It's not dumped on the disk.
If the section doesn't exists the section is created
"""
conf = self.get_section_config(section)
if isinstance(value, bool):
conf[key] = str(value)
else:
conf[key] = value
self.set_section_config(section, conf) | [
"def",
"set",
"(",
"self",
",",
"section",
",",
"key",
",",
"value",
")",
":",
"conf",
"=",
"self",
".",
"get_section_config",
"(",
"section",
")",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"conf",
"[",
"key",
"]",
"=",
"str",
"(",
... | Set a config value.
It's not dumped on the disk.
If the section doesn't exists the section is created | [
"Set",
"a",
"config",
"value",
".",
"It",
"s",
"not",
"dumped",
"on",
"the",
"disk",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/config.py#L224-L237 | train | 221,432 |
GNS3/gns3-server | gns3server/config.py | Config.instance | def instance(*args, **kwargs):
"""
Singleton to return only one instance of Config.
:returns: instance of Config
"""
if not hasattr(Config, "_instance") or Config._instance is None:
Config._instance = Config(*args, **kwargs)
return Config._instance | python | def instance(*args, **kwargs):
"""
Singleton to return only one instance of Config.
:returns: instance of Config
"""
if not hasattr(Config, "_instance") or Config._instance is None:
Config._instance = Config(*args, **kwargs)
return Config._instance | [
"def",
"instance",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"hasattr",
"(",
"Config",
",",
"\"_instance\"",
")",
"or",
"Config",
".",
"_instance",
"is",
"None",
":",
"Config",
".",
"_instance",
"=",
"Config",
"(",
"*",
"args"... | Singleton to return only one instance of Config.
:returns: instance of Config | [
"Singleton",
"to",
"return",
"only",
"one",
"instance",
"of",
"Config",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/config.py#L240-L249 | train | 221,433 |
GNS3/gns3-server | gns3server/utils/asyncio/__init__.py | wait_run_in_executor | def wait_run_in_executor(func, *args, **kwargs):
"""
Run blocking code in a different thread and wait
for the result.
:param func: Run this function in a different thread
:param args: Parameters of the function
:param kwargs: Keyword parameters of the function
:returns: Return the result of the function
"""
loop = asyncio.get_event_loop()
future = loop.run_in_executor(None, functools.partial(func, *args, **kwargs))
yield from asyncio.wait([future])
return future.result() | python | def wait_run_in_executor(func, *args, **kwargs):
"""
Run blocking code in a different thread and wait
for the result.
:param func: Run this function in a different thread
:param args: Parameters of the function
:param kwargs: Keyword parameters of the function
:returns: Return the result of the function
"""
loop = asyncio.get_event_loop()
future = loop.run_in_executor(None, functools.partial(func, *args, **kwargs))
yield from asyncio.wait([future])
return future.result() | [
"def",
"wait_run_in_executor",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"future",
"=",
"loop",
".",
"run_in_executor",
"(",
"None",
",",
"functools",
".",
"partial",
"(",
... | Run blocking code in a different thread and wait
for the result.
:param func: Run this function in a different thread
:param args: Parameters of the function
:param kwargs: Keyword parameters of the function
:returns: Return the result of the function | [
"Run",
"blocking",
"code",
"in",
"a",
"different",
"thread",
"and",
"wait",
"for",
"the",
"result",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/__init__.py#L26-L40 | train | 221,434 |
GNS3/gns3-server | gns3server/utils/asyncio/__init__.py | subprocess_check_output | def subprocess_check_output(*args, cwd=None, env=None, stderr=False):
"""
Run a command and capture output
:param *args: List of command arguments
:param cwd: Current working directory
:param env: Command environment
:param stderr: Read on stderr
:returns: Command output
"""
if stderr:
proc = yield from asyncio.create_subprocess_exec(*args, stderr=asyncio.subprocess.PIPE, cwd=cwd, env=env)
output = yield from proc.stderr.read()
else:
proc = yield from asyncio.create_subprocess_exec(*args, stdout=asyncio.subprocess.PIPE, cwd=cwd, env=env)
output = yield from proc.stdout.read()
if output is None:
return ""
# If we received garbage we ignore invalid characters
# it should happens only when user try to use another binary
# and the code of VPCS, dynamips... Will detect it's not the correct binary
return output.decode("utf-8", errors="ignore") | python | def subprocess_check_output(*args, cwd=None, env=None, stderr=False):
"""
Run a command and capture output
:param *args: List of command arguments
:param cwd: Current working directory
:param env: Command environment
:param stderr: Read on stderr
:returns: Command output
"""
if stderr:
proc = yield from asyncio.create_subprocess_exec(*args, stderr=asyncio.subprocess.PIPE, cwd=cwd, env=env)
output = yield from proc.stderr.read()
else:
proc = yield from asyncio.create_subprocess_exec(*args, stdout=asyncio.subprocess.PIPE, cwd=cwd, env=env)
output = yield from proc.stdout.read()
if output is None:
return ""
# If we received garbage we ignore invalid characters
# it should happens only when user try to use another binary
# and the code of VPCS, dynamips... Will detect it's not the correct binary
return output.decode("utf-8", errors="ignore") | [
"def",
"subprocess_check_output",
"(",
"*",
"args",
",",
"cwd",
"=",
"None",
",",
"env",
"=",
"None",
",",
"stderr",
"=",
"False",
")",
":",
"if",
"stderr",
":",
"proc",
"=",
"yield",
"from",
"asyncio",
".",
"create_subprocess_exec",
"(",
"*",
"args",
... | Run a command and capture output
:param *args: List of command arguments
:param cwd: Current working directory
:param env: Command environment
:param stderr: Read on stderr
:returns: Command output | [
"Run",
"a",
"command",
"and",
"capture",
"output"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/__init__.py#L44-L66 | train | 221,435 |
GNS3/gns3-server | gns3server/utils/asyncio/__init__.py | wait_for_process_termination | def wait_for_process_termination(process, timeout=10):
"""
Wait for a process terminate, and raise asyncio.TimeoutError in case of
timeout.
In theory this can be implemented by just:
yield from asyncio.wait_for(self._iou_process.wait(), timeout=100)
But it's broken before Python 3.4:
http://bugs.python.org/issue23140
:param process: An asyncio subprocess
:param timeout: Timeout in seconds
"""
if sys.version_info >= (3, 5):
try:
yield from asyncio.wait_for(process.wait(), timeout=timeout)
except ProcessLookupError:
return
else:
while timeout > 0:
if process.returncode is not None:
return
yield from asyncio.sleep(0.1)
timeout -= 0.1
raise asyncio.TimeoutError() | python | def wait_for_process_termination(process, timeout=10):
"""
Wait for a process terminate, and raise asyncio.TimeoutError in case of
timeout.
In theory this can be implemented by just:
yield from asyncio.wait_for(self._iou_process.wait(), timeout=100)
But it's broken before Python 3.4:
http://bugs.python.org/issue23140
:param process: An asyncio subprocess
:param timeout: Timeout in seconds
"""
if sys.version_info >= (3, 5):
try:
yield from asyncio.wait_for(process.wait(), timeout=timeout)
except ProcessLookupError:
return
else:
while timeout > 0:
if process.returncode is not None:
return
yield from asyncio.sleep(0.1)
timeout -= 0.1
raise asyncio.TimeoutError() | [
"def",
"wait_for_process_termination",
"(",
"process",
",",
"timeout",
"=",
"10",
")",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"5",
")",
":",
"try",
":",
"yield",
"from",
"asyncio",
".",
"wait_for",
"(",
"process",
".",
"wait",
"(",... | Wait for a process terminate, and raise asyncio.TimeoutError in case of
timeout.
In theory this can be implemented by just:
yield from asyncio.wait_for(self._iou_process.wait(), timeout=100)
But it's broken before Python 3.4:
http://bugs.python.org/issue23140
:param process: An asyncio subprocess
:param timeout: Timeout in seconds | [
"Wait",
"for",
"a",
"process",
"terminate",
"and",
"raise",
"asyncio",
".",
"TimeoutError",
"in",
"case",
"of",
"timeout",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/__init__.py#L69-L95 | train | 221,436 |
GNS3/gns3-server | gns3server/utils/asyncio/__init__.py | locked_coroutine | def locked_coroutine(f):
"""
Method decorator that replace asyncio.coroutine that warranty
that this specific method of this class instance will not we
executed twice at the same time
"""
@asyncio.coroutine
def new_function(*args, **kwargs):
# In the instance of the class we will store
# a lock has an attribute.
lock_var_name = "__" + f.__name__ + "_lock"
if not hasattr(args[0], lock_var_name):
setattr(args[0], lock_var_name, asyncio.Lock())
with (yield from getattr(args[0], lock_var_name)):
return (yield from f(*args, **kwargs))
return new_function | python | def locked_coroutine(f):
"""
Method decorator that replace asyncio.coroutine that warranty
that this specific method of this class instance will not we
executed twice at the same time
"""
@asyncio.coroutine
def new_function(*args, **kwargs):
# In the instance of the class we will store
# a lock has an attribute.
lock_var_name = "__" + f.__name__ + "_lock"
if not hasattr(args[0], lock_var_name):
setattr(args[0], lock_var_name, asyncio.Lock())
with (yield from getattr(args[0], lock_var_name)):
return (yield from f(*args, **kwargs))
return new_function | [
"def",
"locked_coroutine",
"(",
"f",
")",
":",
"@",
"asyncio",
".",
"coroutine",
"def",
"new_function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# In the instance of the class we will store",
"# a lock has an attribute.",
"lock_var_name",
"=",
"\"__\"",... | Method decorator that replace asyncio.coroutine that warranty
that this specific method of this class instance will not we
executed twice at the same time | [
"Method",
"decorator",
"that",
"replace",
"asyncio",
".",
"coroutine",
"that",
"warranty",
"that",
"this",
"specific",
"method",
"of",
"this",
"class",
"instance",
"will",
"not",
"we",
"executed",
"twice",
"at",
"the",
"same",
"time"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/__init__.py#L142-L160 | train | 221,437 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/bridge.py | Bridge.set_name | def set_name(self, new_name):
"""
Renames this bridge.
:param new_name: New name for this bridge
"""
yield from self._hypervisor.send('nio_bridge rename "{name}" "{new_name}"'.format(name=self._name,
new_name=new_name))
self._name = new_name | python | def set_name(self, new_name):
"""
Renames this bridge.
:param new_name: New name for this bridge
"""
yield from self._hypervisor.send('nio_bridge rename "{name}" "{new_name}"'.format(name=self._name,
new_name=new_name))
self._name = new_name | [
"def",
"set_name",
"(",
"self",
",",
"new_name",
")",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'nio_bridge rename \"{name}\" \"{new_name}\"'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"new_name",
"=",
"new_name",
... | Renames this bridge.
:param new_name: New name for this bridge | [
"Renames",
"this",
"bridge",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/bridge.py#L55-L65 | train | 221,438 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/bridge.py | Bridge.delete | def delete(self):
"""
Deletes this bridge.
"""
if self._hypervisor and self in self._hypervisor.devices:
self._hypervisor.devices.remove(self)
if self._hypervisor and not self._hypervisor.devices:
yield from self._hypervisor.send('nio_bridge delete "{}"'.format(self._name)) | python | def delete(self):
"""
Deletes this bridge.
"""
if self._hypervisor and self in self._hypervisor.devices:
self._hypervisor.devices.remove(self)
if self._hypervisor and not self._hypervisor.devices:
yield from self._hypervisor.send('nio_bridge delete "{}"'.format(self._name)) | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"_hypervisor",
"and",
"self",
"in",
"self",
".",
"_hypervisor",
".",
"devices",
":",
"self",
".",
"_hypervisor",
".",
"devices",
".",
"remove",
"(",
"self",
")",
"if",
"self",
".",
"_hypervisor... | Deletes this bridge. | [
"Deletes",
"this",
"bridge",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/bridge.py#L78-L86 | train | 221,439 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/bridge.py | Bridge.add_nio | def add_nio(self, nio):
"""
Adds a NIO as new port on this bridge.
:param nio: NIO instance to add
"""
yield from self._hypervisor.send('nio_bridge add_nio "{name}" {nio}'.format(name=self._name, nio=nio))
self._nios.append(nio) | python | def add_nio(self, nio):
"""
Adds a NIO as new port on this bridge.
:param nio: NIO instance to add
"""
yield from self._hypervisor.send('nio_bridge add_nio "{name}" {nio}'.format(name=self._name, nio=nio))
self._nios.append(nio) | [
"def",
"add_nio",
"(",
"self",
",",
"nio",
")",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'nio_bridge add_nio \"{name}\" {nio}'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"nio",
"=",
"nio",
")",
")",
"self",
... | Adds a NIO as new port on this bridge.
:param nio: NIO instance to add | [
"Adds",
"a",
"NIO",
"as",
"new",
"port",
"on",
"this",
"bridge",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/bridge.py#L89-L97 | train | 221,440 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/bridge.py | Bridge.remove_nio | def remove_nio(self, nio):
"""
Removes the specified NIO as member of this bridge.
:param nio: NIO instance to remove
"""
if self._hypervisor:
yield from self._hypervisor.send('nio_bridge remove_nio "{name}" {nio}'.format(name=self._name, nio=nio))
self._nios.remove(nio) | python | def remove_nio(self, nio):
"""
Removes the specified NIO as member of this bridge.
:param nio: NIO instance to remove
"""
if self._hypervisor:
yield from self._hypervisor.send('nio_bridge remove_nio "{name}" {nio}'.format(name=self._name, nio=nio))
self._nios.remove(nio) | [
"def",
"remove_nio",
"(",
"self",
",",
"nio",
")",
":",
"if",
"self",
".",
"_hypervisor",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'nio_bridge remove_nio \"{name}\" {nio}'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
... | Removes the specified NIO as member of this bridge.
:param nio: NIO instance to remove | [
"Removes",
"the",
"specified",
"NIO",
"as",
"member",
"of",
"this",
"bridge",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/bridge.py#L100-L108 | train | 221,441 |
GNS3/gns3-server | gns3server/controller/import_project.py | _move_node_file | def _move_node_file(path, old_id, new_id):
"""
Move the files from a node when changing his id
:param path: Path of the project
:param old_id: ID before change
:param new_id: New node UUID
"""
root = os.path.join(path, "project-files")
if os.path.exists(root):
for dirname in os.listdir(root):
module_dir = os.path.join(root, dirname)
if os.path.isdir(module_dir):
node_dir = os.path.join(module_dir, old_id)
if os.path.exists(node_dir):
shutil.move(node_dir, os.path.join(module_dir, new_id)) | python | def _move_node_file(path, old_id, new_id):
"""
Move the files from a node when changing his id
:param path: Path of the project
:param old_id: ID before change
:param new_id: New node UUID
"""
root = os.path.join(path, "project-files")
if os.path.exists(root):
for dirname in os.listdir(root):
module_dir = os.path.join(root, dirname)
if os.path.isdir(module_dir):
node_dir = os.path.join(module_dir, old_id)
if os.path.exists(node_dir):
shutil.move(node_dir, os.path.join(module_dir, new_id)) | [
"def",
"_move_node_file",
"(",
"path",
",",
"old_id",
",",
"new_id",
")",
":",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"project-files\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"root",
")",
":",
"for",
"dirname",
... | Move the files from a node when changing his id
:param path: Path of the project
:param old_id: ID before change
:param new_id: New node UUID | [
"Move",
"the",
"files",
"from",
"a",
"node",
"when",
"changing",
"his",
"id"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/import_project.py#L157-L172 | train | 221,442 |
GNS3/gns3-server | gns3server/controller/import_project.py | _move_files_to_compute | def _move_files_to_compute(compute, project_id, directory, files_path):
"""
Move the files to a remote compute
"""
location = os.path.join(directory, files_path)
if os.path.exists(location):
for (dirpath, dirnames, filenames) in os.walk(location):
for filename in filenames:
path = os.path.join(dirpath, filename)
dst = os.path.relpath(path, directory)
yield from _upload_file(compute, project_id, path, dst)
shutil.rmtree(os.path.join(directory, files_path)) | python | def _move_files_to_compute(compute, project_id, directory, files_path):
"""
Move the files to a remote compute
"""
location = os.path.join(directory, files_path)
if os.path.exists(location):
for (dirpath, dirnames, filenames) in os.walk(location):
for filename in filenames:
path = os.path.join(dirpath, filename)
dst = os.path.relpath(path, directory)
yield from _upload_file(compute, project_id, path, dst)
shutil.rmtree(os.path.join(directory, files_path)) | [
"def",
"_move_files_to_compute",
"(",
"compute",
",",
"project_id",
",",
"directory",
",",
"files_path",
")",
":",
"location",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"files_path",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"lo... | Move the files to a remote compute | [
"Move",
"the",
"files",
"to",
"a",
"remote",
"compute"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/import_project.py#L176-L187 | train | 221,443 |
GNS3/gns3-server | gns3server/controller/import_project.py | _upload_file | def _upload_file(compute, project_id, file_path, path):
"""
Upload a file to a remote project
:param file_path: File path on the controller file system
:param path: File path on the remote system relative to project directory
"""
path = "/projects/{}/files/{}".format(project_id, path.replace("\\", "/"))
with open(file_path, "rb") as f:
yield from compute.http_query("POST", path, f, timeout=None) | python | def _upload_file(compute, project_id, file_path, path):
"""
Upload a file to a remote project
:param file_path: File path on the controller file system
:param path: File path on the remote system relative to project directory
"""
path = "/projects/{}/files/{}".format(project_id, path.replace("\\", "/"))
with open(file_path, "rb") as f:
yield from compute.http_query("POST", path, f, timeout=None) | [
"def",
"_upload_file",
"(",
"compute",
",",
"project_id",
",",
"file_path",
",",
"path",
")",
":",
"path",
"=",
"\"/projects/{}/files/{}\"",
".",
"format",
"(",
"project_id",
",",
"path",
".",
"replace",
"(",
"\"\\\\\"",
",",
"\"/\"",
")",
")",
"with",
"op... | Upload a file to a remote project
:param file_path: File path on the controller file system
:param path: File path on the remote system relative to project directory | [
"Upload",
"a",
"file",
"to",
"a",
"remote",
"project"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/import_project.py#L191-L200 | train | 221,444 |
GNS3/gns3-server | gns3server/controller/import_project.py | _import_images | def _import_images(controller, path):
"""
Copy images to the images directory or delete them if they
already exists.
"""
image_dir = controller.images_path()
root = os.path.join(path, "images")
for (dirpath, dirnames, filenames) in os.walk(root):
for filename in filenames:
path = os.path.join(dirpath, filename)
dst = os.path.join(image_dir, os.path.relpath(path, root))
os.makedirs(os.path.dirname(dst), exist_ok=True)
shutil.move(path, dst) | python | def _import_images(controller, path):
"""
Copy images to the images directory or delete them if they
already exists.
"""
image_dir = controller.images_path()
root = os.path.join(path, "images")
for (dirpath, dirnames, filenames) in os.walk(root):
for filename in filenames:
path = os.path.join(dirpath, filename)
dst = os.path.join(image_dir, os.path.relpath(path, root))
os.makedirs(os.path.dirname(dst), exist_ok=True)
shutil.move(path, dst) | [
"def",
"_import_images",
"(",
"controller",
",",
"path",
")",
":",
"image_dir",
"=",
"controller",
".",
"images_path",
"(",
")",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"images\"",
")",
"for",
"(",
"dirpath",
",",
"dirnames",
"... | Copy images to the images directory or delete them if they
already exists. | [
"Copy",
"images",
"to",
"the",
"images",
"directory",
"or",
"delete",
"them",
"if",
"they",
"already",
"exists",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/import_project.py#L203-L216 | train | 221,445 |
GNS3/gns3-server | gns3server/utils/windows_loopback.py | parse_add_loopback | def parse_add_loopback():
"""
Validate params when adding a loopback adapter
"""
class Add(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
try:
ipaddress.IPv4Interface("{}/{}".format(values[1], values[2]))
except ipaddress.AddressValueError as e:
raise argparse.ArgumentTypeError("Invalid IP address: {}".format(e))
except ipaddress.NetmaskValueError as e:
raise argparse.ArgumentTypeError("Invalid subnet mask: {}".format(e))
setattr(args, self.dest, values)
return Add | python | def parse_add_loopback():
"""
Validate params when adding a loopback adapter
"""
class Add(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
try:
ipaddress.IPv4Interface("{}/{}".format(values[1], values[2]))
except ipaddress.AddressValueError as e:
raise argparse.ArgumentTypeError("Invalid IP address: {}".format(e))
except ipaddress.NetmaskValueError as e:
raise argparse.ArgumentTypeError("Invalid subnet mask: {}".format(e))
setattr(args, self.dest, values)
return Add | [
"def",
"parse_add_loopback",
"(",
")",
":",
"class",
"Add",
"(",
"argparse",
".",
"Action",
")",
":",
"def",
"__call__",
"(",
"self",
",",
"parser",
",",
"args",
",",
"values",
",",
"option_string",
"=",
"None",
")",
":",
"try",
":",
"ipaddress",
".",
... | Validate params when adding a loopback adapter | [
"Validate",
"params",
"when",
"adding",
"a",
"loopback",
"adapter"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/windows_loopback.py#L31-L46 | train | 221,446 |
GNS3/gns3-server | gns3server/utils/windows_loopback.py | main | def main():
"""
Entry point for the Windows loopback tool.
"""
parser = argparse.ArgumentParser(description='%(prog)s add/remove Windows loopback adapters')
parser.add_argument('-a', "--add", nargs=3, action=parse_add_loopback(), help="add a Windows loopback adapter")
parser.add_argument("-r", "--remove", action="store", help="remove a Windows loopback adapter")
try:
args = parser.parse_args()
except argparse.ArgumentTypeError as e:
raise SystemExit(e)
# devcon is required to install/remove Windows loopback adapters
devcon_path = shutil.which("devcon")
if not devcon_path:
raise SystemExit("Could not find devcon.exe")
from win32com.shell import shell
if not shell.IsUserAnAdmin():
raise SystemExit("You must run this script as an administrator")
try:
if args.add:
add_loopback(devcon_path, args.add[0], args.add[1], args.add[2])
if args.remove:
remove_loopback(devcon_path, args.remove)
except SystemExit as e:
print(e)
os.system("pause") | python | def main():
"""
Entry point for the Windows loopback tool.
"""
parser = argparse.ArgumentParser(description='%(prog)s add/remove Windows loopback adapters')
parser.add_argument('-a', "--add", nargs=3, action=parse_add_loopback(), help="add a Windows loopback adapter")
parser.add_argument("-r", "--remove", action="store", help="remove a Windows loopback adapter")
try:
args = parser.parse_args()
except argparse.ArgumentTypeError as e:
raise SystemExit(e)
# devcon is required to install/remove Windows loopback adapters
devcon_path = shutil.which("devcon")
if not devcon_path:
raise SystemExit("Could not find devcon.exe")
from win32com.shell import shell
if not shell.IsUserAnAdmin():
raise SystemExit("You must run this script as an administrator")
try:
if args.add:
add_loopback(devcon_path, args.add[0], args.add[1], args.add[2])
if args.remove:
remove_loopback(devcon_path, args.remove)
except SystemExit as e:
print(e)
os.system("pause") | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'%(prog)s add/remove Windows loopback adapters'",
")",
"parser",
".",
"add_argument",
"(",
"'-a'",
",",
"\"--add\"",
",",
"nargs",
"=",
"3",
",",
"action",
... | Entry point for the Windows loopback tool. | [
"Entry",
"point",
"for",
"the",
"Windows",
"loopback",
"tool",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/windows_loopback.py#L105-L134 | train | 221,447 |
GNS3/gns3-server | gns3server/utils/picture.py | _svg_convert_size | def _svg_convert_size(size):
"""
Convert svg size to the px version
:param size: String with the size
"""
# https://www.w3.org/TR/SVG/coords.html#Units
conversion_table = {
"pt": 1.25,
"pc": 15,
"mm": 3.543307,
"cm": 35.43307,
"in": 90,
"px": 1
}
if len(size) > 3:
if size[-2:] in conversion_table:
return round(float(size[:-2]) * conversion_table[size[-2:]])
return round(float(size)) | python | def _svg_convert_size(size):
"""
Convert svg size to the px version
:param size: String with the size
"""
# https://www.w3.org/TR/SVG/coords.html#Units
conversion_table = {
"pt": 1.25,
"pc": 15,
"mm": 3.543307,
"cm": 35.43307,
"in": 90,
"px": 1
}
if len(size) > 3:
if size[-2:] in conversion_table:
return round(float(size[:-2]) * conversion_table[size[-2:]])
return round(float(size)) | [
"def",
"_svg_convert_size",
"(",
"size",
")",
":",
"# https://www.w3.org/TR/SVG/coords.html#Units",
"conversion_table",
"=",
"{",
"\"pt\"",
":",
"1.25",
",",
"\"pc\"",
":",
"15",
",",
"\"mm\"",
":",
"3.543307",
",",
"\"cm\"",
":",
"35.43307",
",",
"\"in\"",
":",... | Convert svg size to the px version
:param size: String with the size | [
"Convert",
"svg",
"size",
"to",
"the",
"px",
"version"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/picture.py#L114-L134 | train | 221,448 |
GNS3/gns3-server | gns3server/utils/images.py | list_images | def list_images(type):
"""
Scan directories for available image for a type
:param type: emulator type (dynamips, qemu, iou)
"""
files = set()
images = []
server_config = Config.instance().get_section_config("Server")
general_images_directory = os.path.expanduser(server_config.get("images_path", "~/GNS3/images"))
# Subfolder of the general_images_directory specific to this VM type
default_directory = default_images_directory(type)
for directory in images_directories(type):
# We limit recursion to path outside the default images directory
# the reason is in the default directory manage file organization and
# it should be flatten to keep things simple
recurse = True
if os.path.commonprefix([directory, general_images_directory]) == general_images_directory:
recurse = False
directory = os.path.normpath(directory)
for root, _, filenames in _os_walk(directory, recurse=recurse):
for filename in filenames:
path = os.path.join(root, filename)
if filename not in files:
if filename.endswith(".md5sum") or filename.startswith("."):
continue
elif ((filename.endswith(".image") or filename.endswith(".bin")) and type == "dynamips") \
or ((filename.endswith(".bin") or filename.startswith("i86bi")) and type == "iou") \
or (not filename.endswith(".bin") and not filename.endswith(".image") and type == "qemu"):
files.add(filename)
# It the image is located in the standard directory the path is relative
if os.path.commonprefix([root, default_directory]) != default_directory:
path = os.path.join(root, filename)
else:
path = os.path.relpath(os.path.join(root, filename), default_directory)
try:
if type in ["dynamips", "iou"]:
with open(os.path.join(root, filename), "rb") as f:
# read the first 7 bytes of the file.
elf_header_start = f.read(7)
# valid IOS images must start with the ELF magic number, be 32-bit, big endian and have an ELF version of 1
if not elf_header_start == b'\x7fELF\x01\x02\x01' and not elf_header_start == b'\x7fELF\x01\x01\x01':
continue
images.append({
"filename": filename,
"path": force_unix_path(path),
"md5sum": md5sum(os.path.join(root, filename)),
"filesize": os.stat(os.path.join(root, filename)).st_size})
except OSError as e:
log.warn("Can't add image {}: {}".format(path, str(e)))
return images | python | def list_images(type):
"""
Scan directories for available image for a type
:param type: emulator type (dynamips, qemu, iou)
"""
files = set()
images = []
server_config = Config.instance().get_section_config("Server")
general_images_directory = os.path.expanduser(server_config.get("images_path", "~/GNS3/images"))
# Subfolder of the general_images_directory specific to this VM type
default_directory = default_images_directory(type)
for directory in images_directories(type):
# We limit recursion to path outside the default images directory
# the reason is in the default directory manage file organization and
# it should be flatten to keep things simple
recurse = True
if os.path.commonprefix([directory, general_images_directory]) == general_images_directory:
recurse = False
directory = os.path.normpath(directory)
for root, _, filenames in _os_walk(directory, recurse=recurse):
for filename in filenames:
path = os.path.join(root, filename)
if filename not in files:
if filename.endswith(".md5sum") or filename.startswith("."):
continue
elif ((filename.endswith(".image") or filename.endswith(".bin")) and type == "dynamips") \
or ((filename.endswith(".bin") or filename.startswith("i86bi")) and type == "iou") \
or (not filename.endswith(".bin") and not filename.endswith(".image") and type == "qemu"):
files.add(filename)
# It the image is located in the standard directory the path is relative
if os.path.commonprefix([root, default_directory]) != default_directory:
path = os.path.join(root, filename)
else:
path = os.path.relpath(os.path.join(root, filename), default_directory)
try:
if type in ["dynamips", "iou"]:
with open(os.path.join(root, filename), "rb") as f:
# read the first 7 bytes of the file.
elf_header_start = f.read(7)
# valid IOS images must start with the ELF magic number, be 32-bit, big endian and have an ELF version of 1
if not elf_header_start == b'\x7fELF\x01\x02\x01' and not elf_header_start == b'\x7fELF\x01\x01\x01':
continue
images.append({
"filename": filename,
"path": force_unix_path(path),
"md5sum": md5sum(os.path.join(root, filename)),
"filesize": os.stat(os.path.join(root, filename)).st_size})
except OSError as e:
log.warn("Can't add image {}: {}".format(path, str(e)))
return images | [
"def",
"list_images",
"(",
"type",
")",
":",
"files",
"=",
"set",
"(",
")",
"images",
"=",
"[",
"]",
"server_config",
"=",
"Config",
".",
"instance",
"(",
")",
".",
"get_section_config",
"(",
"\"Server\"",
")",
"general_images_directory",
"=",
"os",
".",
... | Scan directories for available image for a type
:param type: emulator type (dynamips, qemu, iou) | [
"Scan",
"directories",
"for",
"available",
"image",
"for",
"a",
"type"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/images.py#L29-L87 | train | 221,449 |
GNS3/gns3-server | gns3server/utils/images.py | _os_walk | def _os_walk(directory, recurse=True, **kwargs):
"""
Work like os.walk but if recurse is False just list current directory
"""
if recurse:
for root, dirs, files in os.walk(directory, **kwargs):
yield root, dirs, files
else:
files = []
for filename in os.listdir(directory):
if os.path.isfile(os.path.join(directory, filename)):
files.append(filename)
yield directory, [], files | python | def _os_walk(directory, recurse=True, **kwargs):
"""
Work like os.walk but if recurse is False just list current directory
"""
if recurse:
for root, dirs, files in os.walk(directory, **kwargs):
yield root, dirs, files
else:
files = []
for filename in os.listdir(directory):
if os.path.isfile(os.path.join(directory, filename)):
files.append(filename)
yield directory, [], files | [
"def",
"_os_walk",
"(",
"directory",
",",
"recurse",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"recurse",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"directory",
",",
"*",
"*",
"kwargs",
")",
":",
"yi... | Work like os.walk but if recurse is False just list current directory | [
"Work",
"like",
"os",
".",
"walk",
"but",
"if",
"recurse",
"is",
"False",
"just",
"list",
"current",
"directory"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/images.py#L90-L102 | train | 221,450 |
GNS3/gns3-server | gns3server/utils/images.py | images_directories | def images_directories(type):
"""
Return all directory where we will look for images
by priority
:param type: Type of emulator
"""
server_config = Config.instance().get_section_config("Server")
paths = []
img_dir = os.path.expanduser(server_config.get("images_path", "~/GNS3/images"))
type_img_directory = default_images_directory(type)
try:
os.makedirs(type_img_directory, exist_ok=True)
paths.append(type_img_directory)
except (OSError, PermissionError):
pass
for directory in server_config.get("additional_images_path", "").split(";"):
paths.append(directory)
# Compatibility with old topologies we look in parent directory
paths.append(img_dir)
# Return only the existings paths
return [force_unix_path(p) for p in paths if os.path.exists(p)] | python | def images_directories(type):
"""
Return all directory where we will look for images
by priority
:param type: Type of emulator
"""
server_config = Config.instance().get_section_config("Server")
paths = []
img_dir = os.path.expanduser(server_config.get("images_path", "~/GNS3/images"))
type_img_directory = default_images_directory(type)
try:
os.makedirs(type_img_directory, exist_ok=True)
paths.append(type_img_directory)
except (OSError, PermissionError):
pass
for directory in server_config.get("additional_images_path", "").split(";"):
paths.append(directory)
# Compatibility with old topologies we look in parent directory
paths.append(img_dir)
# Return only the existings paths
return [force_unix_path(p) for p in paths if os.path.exists(p)] | [
"def",
"images_directories",
"(",
"type",
")",
":",
"server_config",
"=",
"Config",
".",
"instance",
"(",
")",
".",
"get_section_config",
"(",
"\"Server\"",
")",
"paths",
"=",
"[",
"]",
"img_dir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"server_con... | Return all directory where we will look for images
by priority
:param type: Type of emulator | [
"Return",
"all",
"directory",
"where",
"we",
"will",
"look",
"for",
"images",
"by",
"priority"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/images.py#L121-L143 | train | 221,451 |
GNS3/gns3-server | gns3server/utils/images.py | md5sum | def md5sum(path):
"""
Return the md5sum of an image and cache it on disk
:param path: Path to the image
:returns: Digest of the image
"""
if path is None or len(path) == 0 or not os.path.exists(path):
return None
try:
with open(path + '.md5sum') as f:
md5 = f.read()
if len(md5) == 32:
return md5
# Unicode error is when user rename an image to .md5sum ....
except (OSError, UnicodeDecodeError):
pass
try:
m = hashlib.md5()
with open(path, 'rb') as f:
while True:
buf = f.read(128)
if not buf:
break
m.update(buf)
digest = m.hexdigest()
except OSError as e:
log.error("Can't create digest of %s: %s", path, str(e))
return None
try:
with open('{}.md5sum'.format(path), 'w+') as f:
f.write(digest)
except OSError as e:
log.error("Can't write digest of %s: %s", path, str(e))
return digest | python | def md5sum(path):
"""
Return the md5sum of an image and cache it on disk
:param path: Path to the image
:returns: Digest of the image
"""
if path is None or len(path) == 0 or not os.path.exists(path):
return None
try:
with open(path + '.md5sum') as f:
md5 = f.read()
if len(md5) == 32:
return md5
# Unicode error is when user rename an image to .md5sum ....
except (OSError, UnicodeDecodeError):
pass
try:
m = hashlib.md5()
with open(path, 'rb') as f:
while True:
buf = f.read(128)
if not buf:
break
m.update(buf)
digest = m.hexdigest()
except OSError as e:
log.error("Can't create digest of %s: %s", path, str(e))
return None
try:
with open('{}.md5sum'.format(path), 'w+') as f:
f.write(digest)
except OSError as e:
log.error("Can't write digest of %s: %s", path, str(e))
return digest | [
"def",
"md5sum",
"(",
"path",
")",
":",
"if",
"path",
"is",
"None",
"or",
"len",
"(",
"path",
")",
"==",
"0",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"None",
"try",
":",
"with",
"open",
"(",
"path",
"+",
... | Return the md5sum of an image and cache it on disk
:param path: Path to the image
:returns: Digest of the image | [
"Return",
"the",
"md5sum",
"of",
"an",
"image",
"and",
"cache",
"it",
"on",
"disk"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/images.py#L146-L185 | train | 221,452 |
GNS3/gns3-server | gns3server/utils/images.py | remove_checksum | def remove_checksum(path):
"""
Remove the checksum of an image from cache if exists
"""
path = '{}.md5sum'.format(path)
if os.path.exists(path):
os.remove(path) | python | def remove_checksum(path):
"""
Remove the checksum of an image from cache if exists
"""
path = '{}.md5sum'.format(path)
if os.path.exists(path):
os.remove(path) | [
"def",
"remove_checksum",
"(",
"path",
")",
":",
"path",
"=",
"'{}.md5sum'",
".",
"format",
"(",
"path",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"remove",
"(",
"path",
")"
] | Remove the checksum of an image from cache if exists | [
"Remove",
"the",
"checksum",
"of",
"an",
"image",
"from",
"cache",
"if",
"exists"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/images.py#L188-L195 | train | 221,453 |
GNS3/gns3-server | gns3server/compute/project.py | Project.record_tcp_port | def record_tcp_port(self, port):
"""
Associate a reserved TCP port number with this project.
:param port: TCP port number
"""
if port not in self._used_tcp_ports:
self._used_tcp_ports.add(port) | python | def record_tcp_port(self, port):
"""
Associate a reserved TCP port number with this project.
:param port: TCP port number
"""
if port not in self._used_tcp_ports:
self._used_tcp_ports.add(port) | [
"def",
"record_tcp_port",
"(",
"self",
",",
"port",
")",
":",
"if",
"port",
"not",
"in",
"self",
".",
"_used_tcp_ports",
":",
"self",
".",
"_used_tcp_ports",
".",
"add",
"(",
"port",
")"
] | Associate a reserved TCP port number with this project.
:param port: TCP port number | [
"Associate",
"a",
"reserved",
"TCP",
"port",
"number",
"with",
"this",
"project",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/project.py#L134-L142 | train | 221,454 |
GNS3/gns3-server | gns3server/compute/project.py | Project.record_udp_port | def record_udp_port(self, port):
"""
Associate a reserved UDP port number with this project.
:param port: UDP port number
"""
if port not in self._used_udp_ports:
self._used_udp_ports.add(port) | python | def record_udp_port(self, port):
"""
Associate a reserved UDP port number with this project.
:param port: UDP port number
"""
if port not in self._used_udp_ports:
self._used_udp_ports.add(port) | [
"def",
"record_udp_port",
"(",
"self",
",",
"port",
")",
":",
"if",
"port",
"not",
"in",
"self",
".",
"_used_udp_ports",
":",
"self",
".",
"_used_udp_ports",
".",
"add",
"(",
"port",
")"
] | Associate a reserved UDP port number with this project.
:param port: UDP port number | [
"Associate",
"a",
"reserved",
"UDP",
"port",
"number",
"with",
"this",
"project",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/project.py#L144-L152 | train | 221,455 |
GNS3/gns3-server | gns3server/compute/project.py | Project.remove_tcp_port | def remove_tcp_port(self, port):
"""
Removes an associated TCP port number from this project.
:param port: TCP port number
"""
if port in self._used_tcp_ports:
self._used_tcp_ports.remove(port) | python | def remove_tcp_port(self, port):
"""
Removes an associated TCP port number from this project.
:param port: TCP port number
"""
if port in self._used_tcp_ports:
self._used_tcp_ports.remove(port) | [
"def",
"remove_tcp_port",
"(",
"self",
",",
"port",
")",
":",
"if",
"port",
"in",
"self",
".",
"_used_tcp_ports",
":",
"self",
".",
"_used_tcp_ports",
".",
"remove",
"(",
"port",
")"
] | Removes an associated TCP port number from this project.
:param port: TCP port number | [
"Removes",
"an",
"associated",
"TCP",
"port",
"number",
"from",
"this",
"project",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/project.py#L154-L162 | train | 221,456 |
GNS3/gns3-server | gns3server/compute/project.py | Project.remove_udp_port | def remove_udp_port(self, port):
"""
Removes an associated UDP port number from this project.
:param port: UDP port number
"""
if port in self._used_udp_ports:
self._used_udp_ports.remove(port) | python | def remove_udp_port(self, port):
"""
Removes an associated UDP port number from this project.
:param port: UDP port number
"""
if port in self._used_udp_ports:
self._used_udp_ports.remove(port) | [
"def",
"remove_udp_port",
"(",
"self",
",",
"port",
")",
":",
"if",
"port",
"in",
"self",
".",
"_used_udp_ports",
":",
"self",
".",
"_used_udp_ports",
".",
"remove",
"(",
"port",
")"
] | Removes an associated UDP port number from this project.
:param port: UDP port number | [
"Removes",
"an",
"associated",
"UDP",
"port",
"number",
"from",
"this",
"project",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/project.py#L164-L172 | train | 221,457 |
GNS3/gns3-server | gns3server/compute/project.py | Project.module_working_directory | def module_working_directory(self, module_name):
"""
Returns a working directory for the module
The directory is created if the directory doesn't exist.
:param module_name: name for the module
:returns: working directory
"""
workdir = self.module_working_path(module_name)
if not self._deleted:
try:
os.makedirs(workdir, exist_ok=True)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not create module working directory: {}".format(e))
return workdir | python | def module_working_directory(self, module_name):
"""
Returns a working directory for the module
The directory is created if the directory doesn't exist.
:param module_name: name for the module
:returns: working directory
"""
workdir = self.module_working_path(module_name)
if not self._deleted:
try:
os.makedirs(workdir, exist_ok=True)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not create module working directory: {}".format(e))
return workdir | [
"def",
"module_working_directory",
"(",
"self",
",",
"module_name",
")",
":",
"workdir",
"=",
"self",
".",
"module_working_path",
"(",
"module_name",
")",
"if",
"not",
"self",
".",
"_deleted",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"workdir",
",",
"e... | Returns a working directory for the module
The directory is created if the directory doesn't exist.
:param module_name: name for the module
:returns: working directory | [
"Returns",
"a",
"working",
"directory",
"for",
"the",
"module",
"The",
"directory",
"is",
"created",
"if",
"the",
"directory",
"doesn",
"t",
"exist",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/project.py#L174-L189 | train | 221,458 |
GNS3/gns3-server | gns3server/compute/project.py | Project.node_working_directory | def node_working_directory(self, node):
"""
Returns a working directory for a specific node.
If the directory doesn't exist, the directory is created.
:param node: Node instance
:returns: Node working directory
"""
workdir = self.node_working_path(node)
if not self._deleted:
try:
os.makedirs(workdir, exist_ok=True)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not create the node working directory: {}".format(e))
return workdir | python | def node_working_directory(self, node):
"""
Returns a working directory for a specific node.
If the directory doesn't exist, the directory is created.
:param node: Node instance
:returns: Node working directory
"""
workdir = self.node_working_path(node)
if not self._deleted:
try:
os.makedirs(workdir, exist_ok=True)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not create the node working directory: {}".format(e))
return workdir | [
"def",
"node_working_directory",
"(",
"self",
",",
"node",
")",
":",
"workdir",
"=",
"self",
".",
"node_working_path",
"(",
"node",
")",
"if",
"not",
"self",
".",
"_deleted",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"workdir",
",",
"exist_ok",
"=",
... | Returns a working directory for a specific node.
If the directory doesn't exist, the directory is created.
:param node: Node instance
:returns: Node working directory | [
"Returns",
"a",
"working",
"directory",
"for",
"a",
"specific",
"node",
".",
"If",
"the",
"directory",
"doesn",
"t",
"exist",
"the",
"directory",
"is",
"created",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/project.py#L200-L216 | train | 221,459 |
GNS3/gns3-server | gns3server/compute/project.py | Project.capture_working_directory | def capture_working_directory(self):
"""
Returns a working directory where to temporary store packet capture files.
:returns: path to the directory
"""
workdir = os.path.join(self._path, "tmp", "captures")
if not self._deleted:
try:
os.makedirs(workdir, exist_ok=True)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not create the capture working directory: {}".format(e))
return workdir | python | def capture_working_directory(self):
"""
Returns a working directory where to temporary store packet capture files.
:returns: path to the directory
"""
workdir = os.path.join(self._path, "tmp", "captures")
if not self._deleted:
try:
os.makedirs(workdir, exist_ok=True)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not create the capture working directory: {}".format(e))
return workdir | [
"def",
"capture_working_directory",
"(",
"self",
")",
":",
"workdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"\"tmp\"",
",",
"\"captures\"",
")",
"if",
"not",
"self",
".",
"_deleted",
":",
"try",
":",
"os",
".",
"makedirs"... | Returns a working directory where to temporary store packet capture files.
:returns: path to the directory | [
"Returns",
"a",
"working",
"directory",
"where",
"to",
"temporary",
"store",
"packet",
"capture",
"files",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/project.py#L233-L246 | train | 221,460 |
GNS3/gns3-server | gns3server/compute/project.py | Project.remove_node | def remove_node(self, node):
"""
Removes a node from the project.
In theory this should be called by the node manager.
:param node: Node instance
"""
if node in self._nodes:
yield from node.delete()
self._nodes.remove(node) | python | def remove_node(self, node):
"""
Removes a node from the project.
In theory this should be called by the node manager.
:param node: Node instance
"""
if node in self._nodes:
yield from node.delete()
self._nodes.remove(node) | [
"def",
"remove_node",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
"in",
"self",
".",
"_nodes",
":",
"yield",
"from",
"node",
".",
"delete",
"(",
")",
"self",
".",
"_nodes",
".",
"remove",
"(",
"node",
")"
] | Removes a node from the project.
In theory this should be called by the node manager.
:param node: Node instance | [
"Removes",
"a",
"node",
"from",
"the",
"project",
".",
"In",
"theory",
"this",
"should",
"be",
"called",
"by",
"the",
"node",
"manager",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/project.py#L278-L288 | train | 221,461 |
GNS3/gns3-server | gns3server/compute/project.py | Project.close | def close(self):
"""
Closes the project, but keep information on disk
"""
project_nodes_id = set([n.id for n in self.nodes])
for module in self.compute():
module_nodes_id = set([n.id for n in module.instance().nodes])
# We close the project only for the modules using it
if len(module_nodes_id & project_nodes_id):
yield from module.instance().project_closing(self)
yield from self._close_and_clean(False)
for module in self.compute():
module_nodes_id = set([n.id for n in module.instance().nodes])
# We close the project only for the modules using it
if len(module_nodes_id & project_nodes_id):
yield from module.instance().project_closed(self)
try:
if os.path.exists(self.tmp_working_directory()):
shutil.rmtree(self.tmp_working_directory())
except OSError:
pass | python | def close(self):
"""
Closes the project, but keep information on disk
"""
project_nodes_id = set([n.id for n in self.nodes])
for module in self.compute():
module_nodes_id = set([n.id for n in module.instance().nodes])
# We close the project only for the modules using it
if len(module_nodes_id & project_nodes_id):
yield from module.instance().project_closing(self)
yield from self._close_and_clean(False)
for module in self.compute():
module_nodes_id = set([n.id for n in module.instance().nodes])
# We close the project only for the modules using it
if len(module_nodes_id & project_nodes_id):
yield from module.instance().project_closed(self)
try:
if os.path.exists(self.tmp_working_directory()):
shutil.rmtree(self.tmp_working_directory())
except OSError:
pass | [
"def",
"close",
"(",
"self",
")",
":",
"project_nodes_id",
"=",
"set",
"(",
"[",
"n",
".",
"id",
"for",
"n",
"in",
"self",
".",
"nodes",
"]",
")",
"for",
"module",
"in",
"self",
".",
"compute",
"(",
")",
":",
"module_nodes_id",
"=",
"set",
"(",
"... | Closes the project, but keep information on disk | [
"Closes",
"the",
"project",
"but",
"keep",
"information",
"on",
"disk"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/project.py#L291-L316 | train | 221,462 |
GNS3/gns3-server | gns3server/compute/project.py | Project._close_and_clean | def _close_and_clean(self, cleanup):
"""
Closes the project, and cleanup the disk if cleanup is True
:param cleanup: Whether to delete the project directory
"""
tasks = []
for node in self._nodes:
tasks.append(asyncio.async(node.manager.close_node(node.id)))
if tasks:
done, _ = yield from asyncio.wait(tasks)
for future in done:
try:
future.result()
except (Exception, GeneratorExit) as e:
log.error("Could not close node {}".format(e), exc_info=1)
if cleanup and os.path.exists(self.path):
self._deleted = True
try:
yield from wait_run_in_executor(shutil.rmtree, self.path)
log.info("Project {id} with path '{path}' deleted".format(path=self._path, id=self._id))
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not delete the project directory: {}".format(e))
else:
log.info("Project {id} with path '{path}' closed".format(path=self._path, id=self._id))
if self._used_tcp_ports:
log.warning("Project {} has TCP ports still in use: {}".format(self.id, self._used_tcp_ports))
if self._used_udp_ports:
log.warning("Project {} has UDP ports still in use: {}".format(self.id, self._used_udp_ports))
# clean the remaining ports that have not been cleaned by their respective node.
port_manager = PortManager.instance()
for port in self._used_tcp_ports.copy():
port_manager.release_tcp_port(port, self)
for port in self._used_udp_ports.copy():
port_manager.release_udp_port(port, self) | python | def _close_and_clean(self, cleanup):
"""
Closes the project, and cleanup the disk if cleanup is True
:param cleanup: Whether to delete the project directory
"""
tasks = []
for node in self._nodes:
tasks.append(asyncio.async(node.manager.close_node(node.id)))
if tasks:
done, _ = yield from asyncio.wait(tasks)
for future in done:
try:
future.result()
except (Exception, GeneratorExit) as e:
log.error("Could not close node {}".format(e), exc_info=1)
if cleanup and os.path.exists(self.path):
self._deleted = True
try:
yield from wait_run_in_executor(shutil.rmtree, self.path)
log.info("Project {id} with path '{path}' deleted".format(path=self._path, id=self._id))
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not delete the project directory: {}".format(e))
else:
log.info("Project {id} with path '{path}' closed".format(path=self._path, id=self._id))
if self._used_tcp_ports:
log.warning("Project {} has TCP ports still in use: {}".format(self.id, self._used_tcp_ports))
if self._used_udp_ports:
log.warning("Project {} has UDP ports still in use: {}".format(self.id, self._used_udp_ports))
# clean the remaining ports that have not been cleaned by their respective node.
port_manager = PortManager.instance()
for port in self._used_tcp_ports.copy():
port_manager.release_tcp_port(port, self)
for port in self._used_udp_ports.copy():
port_manager.release_udp_port(port, self) | [
"def",
"_close_and_clean",
"(",
"self",
",",
"cleanup",
")",
":",
"tasks",
"=",
"[",
"]",
"for",
"node",
"in",
"self",
".",
"_nodes",
":",
"tasks",
".",
"append",
"(",
"asyncio",
".",
"async",
"(",
"node",
".",
"manager",
".",
"close_node",
"(",
"nod... | Closes the project, and cleanup the disk if cleanup is True
:param cleanup: Whether to delete the project directory | [
"Closes",
"the",
"project",
"and",
"cleanup",
"the",
"disk",
"if",
"cleanup",
"is",
"True"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/project.py#L319-L358 | train | 221,463 |
GNS3/gns3-server | gns3server/compute/project.py | Project.delete | def delete(self):
"""
Removes project from disk
"""
for module in self.compute():
yield from module.instance().project_closing(self)
yield from self._close_and_clean(True)
for module in self.compute():
yield from module.instance().project_closed(self) | python | def delete(self):
"""
Removes project from disk
"""
for module in self.compute():
yield from module.instance().project_closing(self)
yield from self._close_and_clean(True)
for module in self.compute():
yield from module.instance().project_closed(self) | [
"def",
"delete",
"(",
"self",
")",
":",
"for",
"module",
"in",
"self",
".",
"compute",
"(",
")",
":",
"yield",
"from",
"module",
".",
"instance",
"(",
")",
".",
"project_closing",
"(",
"self",
")",
"yield",
"from",
"self",
".",
"_close_and_clean",
"(",... | Removes project from disk | [
"Removes",
"project",
"from",
"disk"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/project.py#L361-L370 | train | 221,464 |
GNS3/gns3-server | gns3server/compute/project.py | Project._hash_file | def _hash_file(self, path):
"""
Compute and md5 hash for file
:returns: hexadecimal md5
"""
m = hashlib.md5()
with open(path, "rb") as f:
while True:
buf = f.read(128)
if not buf:
break
m.update(buf)
return m.hexdigest() | python | def _hash_file(self, path):
"""
Compute and md5 hash for file
:returns: hexadecimal md5
"""
m = hashlib.md5()
with open(path, "rb") as f:
while True:
buf = f.read(128)
if not buf:
break
m.update(buf)
return m.hexdigest() | [
"def",
"_hash_file",
"(",
"self",
",",
"path",
")",
":",
"m",
"=",
"hashlib",
".",
"md5",
"(",
")",
"with",
"open",
"(",
"path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"while",
"True",
":",
"buf",
"=",
"f",
".",
"read",
"(",
"128",
")",
"if",
"n... | Compute and md5 hash for file
:returns: hexadecimal md5 | [
"Compute",
"and",
"md5",
"hash",
"for",
"file"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/project.py#L413-L427 | train | 221,465 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/ethernet_switch.py | EthernetSwitchConsole.mac | def mac(self):
"""
Show MAC address table
"""
res = 'Port Mac VLAN\n'
result = (yield from self._node._hypervisor.send('ethsw show_mac_addr_table {}'.format(self._node.name)))
for line in result:
mac, vlan, nio = line.replace(' ', ' ').split(' ')
mac = mac.replace('.', '')
mac = "{}:{}:{}:{}:{}:{}".format(
mac[0:2],
mac[2:4],
mac[4:6],
mac[6:8],
mac[8:10],
mac[10:12])
for port_number, switch_nio in self._node.nios.items():
if switch_nio.name == nio:
res += 'Ethernet' + str(port_number) + ' ' + mac + ' ' + vlan + '\n'
break
return res | python | def mac(self):
"""
Show MAC address table
"""
res = 'Port Mac VLAN\n'
result = (yield from self._node._hypervisor.send('ethsw show_mac_addr_table {}'.format(self._node.name)))
for line in result:
mac, vlan, nio = line.replace(' ', ' ').split(' ')
mac = mac.replace('.', '')
mac = "{}:{}:{}:{}:{}:{}".format(
mac[0:2],
mac[2:4],
mac[4:6],
mac[6:8],
mac[8:10],
mac[10:12])
for port_number, switch_nio in self._node.nios.items():
if switch_nio.name == nio:
res += 'Ethernet' + str(port_number) + ' ' + mac + ' ' + vlan + '\n'
break
return res | [
"def",
"mac",
"(",
"self",
")",
":",
"res",
"=",
"'Port Mac VLAN\\n'",
"result",
"=",
"(",
"yield",
"from",
"self",
".",
"_node",
".",
"_hypervisor",
".",
"send",
"(",
"'ethsw show_mac_addr_table {}'",
".",
"format",
"(",
"self",
".",
"_no... | Show MAC address table | [
"Show",
"MAC",
"address",
"table"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/ethernet_switch.py#L47-L67 | train | 221,466 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/ethernet_switch.py | EthernetSwitch.set_name | def set_name(self, new_name):
"""
Renames this Ethernet switch.
:param new_name: New name for this switch
"""
yield from self._hypervisor.send('ethsw rename "{name}" "{new_name}"'.format(name=self._name, new_name=new_name))
log.info('Ethernet switch "{name}" [{id}]: renamed to "{new_name}"'.format(name=self._name,
id=self._id,
new_name=new_name))
self._name = new_name | python | def set_name(self, new_name):
"""
Renames this Ethernet switch.
:param new_name: New name for this switch
"""
yield from self._hypervisor.send('ethsw rename "{name}" "{new_name}"'.format(name=self._name, new_name=new_name))
log.info('Ethernet switch "{name}" [{id}]: renamed to "{new_name}"'.format(name=self._name,
id=self._id,
new_name=new_name))
self._name = new_name | [
"def",
"set_name",
"(",
"self",
",",
"new_name",
")",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'ethsw rename \"{name}\" \"{new_name}\"'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"new_name",
"=",
"new_name",
")"... | Renames this Ethernet switch.
:param new_name: New name for this switch | [
"Renames",
"this",
"Ethernet",
"switch",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/ethernet_switch.py#L175-L186 | train | 221,467 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/ethernet_switch.py | EthernetSwitch.close | def close(self):
"""
Deletes this Ethernet switch.
"""
yield from self._telnet.close()
self._telnet_server.close()
for nio in self._nios.values():
if nio:
yield from nio.close()
self.manager.port_manager.release_tcp_port(self._console, self._project)
if self._hypervisor:
try:
yield from self._hypervisor.send('ethsw delete "{}"'.format(self._name))
log.info('Ethernet switch "{name}" [{id}] has been deleted'.format(name=self._name, id=self._id))
except DynamipsError:
log.debug("Could not properly delete Ethernet switch {}".format(self._name))
if self._hypervisor and self in self._hypervisor.devices:
self._hypervisor.devices.remove(self)
if self._hypervisor and not self._hypervisor.devices:
yield from self.hypervisor.stop()
self._hypervisor = None
return True | python | def close(self):
"""
Deletes this Ethernet switch.
"""
yield from self._telnet.close()
self._telnet_server.close()
for nio in self._nios.values():
if nio:
yield from nio.close()
self.manager.port_manager.release_tcp_port(self._console, self._project)
if self._hypervisor:
try:
yield from self._hypervisor.send('ethsw delete "{}"'.format(self._name))
log.info('Ethernet switch "{name}" [{id}] has been deleted'.format(name=self._name, id=self._id))
except DynamipsError:
log.debug("Could not properly delete Ethernet switch {}".format(self._name))
if self._hypervisor and self in self._hypervisor.devices:
self._hypervisor.devices.remove(self)
if self._hypervisor and not self._hypervisor.devices:
yield from self.hypervisor.stop()
self._hypervisor = None
return True | [
"def",
"close",
"(",
"self",
")",
":",
"yield",
"from",
"self",
".",
"_telnet",
".",
"close",
"(",
")",
"self",
".",
"_telnet_server",
".",
"close",
"(",
")",
"for",
"nio",
"in",
"self",
".",
"_nios",
".",
"values",
"(",
")",
":",
"if",
"nio",
":... | Deletes this Ethernet switch. | [
"Deletes",
"this",
"Ethernet",
"switch",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/ethernet_switch.py#L213-L235 | train | 221,468 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/ethernet_switch.py | EthernetSwitch.add_nio | def add_nio(self, nio, port_number):
"""
Adds a NIO as new port on Ethernet switch.
:param nio: NIO instance to add
:param port_number: port to allocate for the NIO
"""
if port_number in self._nios:
raise DynamipsError("Port {} isn't free".format(port_number))
yield from self._hypervisor.send('ethsw add_nio "{name}" {nio}'.format(name=self._name, nio=nio))
log.info('Ethernet switch "{name}" [{id}]: NIO {nio} bound to port {port}'.format(name=self._name,
id=self._id,
nio=nio,
port=port_number))
self._nios[port_number] = nio
for port_settings in self._ports:
if port_settings["port_number"] == port_number:
yield from self.set_port_settings(port_number, port_settings)
break | python | def add_nio(self, nio, port_number):
"""
Adds a NIO as new port on Ethernet switch.
:param nio: NIO instance to add
:param port_number: port to allocate for the NIO
"""
if port_number in self._nios:
raise DynamipsError("Port {} isn't free".format(port_number))
yield from self._hypervisor.send('ethsw add_nio "{name}" {nio}'.format(name=self._name, nio=nio))
log.info('Ethernet switch "{name}" [{id}]: NIO {nio} bound to port {port}'.format(name=self._name,
id=self._id,
nio=nio,
port=port_number))
self._nios[port_number] = nio
for port_settings in self._ports:
if port_settings["port_number"] == port_number:
yield from self.set_port_settings(port_number, port_settings)
break | [
"def",
"add_nio",
"(",
"self",
",",
"nio",
",",
"port_number",
")",
":",
"if",
"port_number",
"in",
"self",
".",
"_nios",
":",
"raise",
"DynamipsError",
"(",
"\"Port {} isn't free\"",
".",
"format",
"(",
"port_number",
")",
")",
"yield",
"from",
"self",
".... | Adds a NIO as new port on Ethernet switch.
:param nio: NIO instance to add
:param port_number: port to allocate for the NIO | [
"Adds",
"a",
"NIO",
"as",
"new",
"port",
"on",
"Ethernet",
"switch",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/ethernet_switch.py#L238-L259 | train | 221,469 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/ethernet_switch.py | EthernetSwitch.remove_nio | def remove_nio(self, port_number):
"""
Removes the specified NIO as member of this Ethernet switch.
:param port_number: allocated port number
:returns: the NIO that was bound to the port
"""
if port_number not in self._nios:
raise DynamipsError("Port {} is not allocated".format(port_number))
nio = self._nios[port_number]
if isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
if self._hypervisor:
yield from self._hypervisor.send('ethsw remove_nio "{name}" {nio}'.format(name=self._name, nio=nio))
log.info('Ethernet 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]
if port_number in self._mappings:
del self._mappings[port_number]
return nio | python | def remove_nio(self, port_number):
"""
Removes the specified NIO as member of this Ethernet switch.
:param port_number: allocated port number
:returns: the NIO that was bound to the port
"""
if port_number not in self._nios:
raise DynamipsError("Port {} is not allocated".format(port_number))
nio = self._nios[port_number]
if isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
if self._hypervisor:
yield from self._hypervisor.send('ethsw remove_nio "{name}" {nio}'.format(name=self._name, nio=nio))
log.info('Ethernet 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]
if port_number in self._mappings:
del self._mappings[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",
")",
")",
"nio",
"=",
"self",
".",
... | Removes the specified NIO as member of this Ethernet switch.
:param port_number: allocated port number
:returns: the NIO that was bound to the port | [
"Removes",
"the",
"specified",
"NIO",
"as",
"member",
"of",
"this",
"Ethernet",
"switch",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/ethernet_switch.py#L262-L289 | train | 221,470 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/ethernet_switch.py | EthernetSwitch.set_port_settings | def set_port_settings(self, port_number, settings):
"""
Applies port settings to a specific port.
:param port_number: port number to set the settings
:param settings: port settings
"""
if settings["type"] == "access":
yield from self.set_access_port(port_number, settings["vlan"])
elif settings["type"] == "dot1q":
yield from self.set_dot1q_port(port_number, settings["vlan"])
elif settings["type"] == "qinq":
yield from self.set_qinq_port(port_number, settings["vlan"], settings.get("ethertype")) | python | def set_port_settings(self, port_number, settings):
"""
Applies port settings to a specific port.
:param port_number: port number to set the settings
:param settings: port settings
"""
if settings["type"] == "access":
yield from self.set_access_port(port_number, settings["vlan"])
elif settings["type"] == "dot1q":
yield from self.set_dot1q_port(port_number, settings["vlan"])
elif settings["type"] == "qinq":
yield from self.set_qinq_port(port_number, settings["vlan"], settings.get("ethertype")) | [
"def",
"set_port_settings",
"(",
"self",
",",
"port_number",
",",
"settings",
")",
":",
"if",
"settings",
"[",
"\"type\"",
"]",
"==",
"\"access\"",
":",
"yield",
"from",
"self",
".",
"set_access_port",
"(",
"port_number",
",",
"settings",
"[",
"\"vlan\"",
"]... | Applies port settings to a specific port.
:param port_number: port number to set the settings
:param settings: port settings | [
"Applies",
"port",
"settings",
"to",
"a",
"specific",
"port",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/ethernet_switch.py#L292-L305 | train | 221,471 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/ethernet_switch.py | EthernetSwitch.set_access_port | def set_access_port(self, port_number, vlan_id):
"""
Sets the specified port as an ACCESS port.
:param port_number: allocated port number
:param vlan_id: VLAN number membership
"""
if port_number not in self._nios:
raise DynamipsError("Port {} is not allocated".format(port_number))
nio = self._nios[port_number]
yield from self._hypervisor.send('ethsw set_access_port "{name}" {nio} {vlan_id}'.format(name=self._name,
nio=nio,
vlan_id=vlan_id))
log.info('Ethernet switch "{name}" [{id}]: port {port} set as an access port in VLAN {vlan_id}'.format(name=self._name,
id=self._id,
port=port_number,
vlan_id=vlan_id))
self._mappings[port_number] = ("access", vlan_id) | python | def set_access_port(self, port_number, vlan_id):
"""
Sets the specified port as an ACCESS port.
:param port_number: allocated port number
:param vlan_id: VLAN number membership
"""
if port_number not in self._nios:
raise DynamipsError("Port {} is not allocated".format(port_number))
nio = self._nios[port_number]
yield from self._hypervisor.send('ethsw set_access_port "{name}" {nio} {vlan_id}'.format(name=self._name,
nio=nio,
vlan_id=vlan_id))
log.info('Ethernet switch "{name}" [{id}]: port {port} set as an access port in VLAN {vlan_id}'.format(name=self._name,
id=self._id,
port=port_number,
vlan_id=vlan_id))
self._mappings[port_number] = ("access", vlan_id) | [
"def",
"set_access_port",
"(",
"self",
",",
"port_number",
",",
"vlan_id",
")",
":",
"if",
"port_number",
"not",
"in",
"self",
".",
"_nios",
":",
"raise",
"DynamipsError",
"(",
"\"Port {} is not allocated\"",
".",
"format",
"(",
"port_number",
")",
")",
"nio",... | Sets the specified port as an ACCESS port.
:param port_number: allocated port number
:param vlan_id: VLAN number membership | [
"Sets",
"the",
"specified",
"port",
"as",
"an",
"ACCESS",
"port",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/ethernet_switch.py#L308-L328 | train | 221,472 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/ethernet_switch.py | EthernetSwitch.get_mac_addr_table | def get_mac_addr_table(self):
"""
Returns the MAC address table for this Ethernet switch.
:returns: list of entries (Ethernet address, VLAN, NIO)
"""
mac_addr_table = yield from self._hypervisor.send('ethsw show_mac_addr_table "{}"'.format(self._name))
return mac_addr_table | python | def get_mac_addr_table(self):
"""
Returns the MAC address table for this Ethernet switch.
:returns: list of entries (Ethernet address, VLAN, NIO)
"""
mac_addr_table = yield from self._hypervisor.send('ethsw show_mac_addr_table "{}"'.format(self._name))
return mac_addr_table | [
"def",
"get_mac_addr_table",
"(",
"self",
")",
":",
"mac_addr_table",
"=",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'ethsw show_mac_addr_table \"{}\"'",
".",
"format",
"(",
"self",
".",
"_name",
")",
")",
"return",
"mac_addr_table"
] | Returns the MAC address table for this Ethernet switch.
:returns: list of entries (Ethernet address, VLAN, NIO) | [
"Returns",
"the",
"MAC",
"address",
"table",
"for",
"this",
"Ethernet",
"switch",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/ethernet_switch.py#L383-L391 | train | 221,473 |
GNS3/gns3-server | gns3server/web/web_server.py | WebServer.instance | def instance(host=None, port=None):
"""
Singleton to return only one instance of Server.
:returns: instance of Server
"""
if not hasattr(WebServer, "_instance") or WebServer._instance is None:
assert host is not None
assert port is not None
WebServer._instance = WebServer(host, port)
return WebServer._instance | python | def instance(host=None, port=None):
"""
Singleton to return only one instance of Server.
:returns: instance of Server
"""
if not hasattr(WebServer, "_instance") or WebServer._instance is None:
assert host is not None
assert port is not None
WebServer._instance = WebServer(host, port)
return WebServer._instance | [
"def",
"instance",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"WebServer",
",",
"\"_instance\"",
")",
"or",
"WebServer",
".",
"_instance",
"is",
"None",
":",
"assert",
"host",
"is",
"not",
"None",
"assert... | Singleton to return only one instance of Server.
:returns: instance of Server | [
"Singleton",
"to",
"return",
"only",
"one",
"instance",
"of",
"Server",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/web/web_server.py#L64-L75 | train | 221,474 |
GNS3/gns3-server | gns3server/web/web_server.py | WebServer.shutdown_server | def shutdown_server(self):
"""
Cleanly shutdown the server.
"""
if not self._closing:
self._closing = True
else:
log.warning("Close is already in progress")
return
if self._server:
self._server.close()
yield from self._server.wait_closed()
if self._app:
yield from self._app.shutdown()
if self._handler:
try:
# aiohttp < 2.3
yield from self._handler.finish_connections(2) # Parameter is timeout
except AttributeError:
# aiohttp >= 2.3
yield from self._handler.shutdown(2) # Parameter is timeout
if self._app:
yield from self._app.cleanup()
yield from Controller.instance().stop()
for module in MODULES:
log.debug("Unloading module {}".format(module.__name__))
m = module.instance()
yield from m.unload()
if PortManager.instance().tcp_ports:
log.warning("TCP ports are still used {}".format(PortManager.instance().tcp_ports))
if PortManager.instance().udp_ports:
log.warning("UDP ports are still used {}".format(PortManager.instance().udp_ports))
for task in asyncio.Task.all_tasks():
task.cancel()
try:
yield from asyncio.wait_for(task, 1)
except BaseException:
pass
self._loop.stop() | python | def shutdown_server(self):
"""
Cleanly shutdown the server.
"""
if not self._closing:
self._closing = True
else:
log.warning("Close is already in progress")
return
if self._server:
self._server.close()
yield from self._server.wait_closed()
if self._app:
yield from self._app.shutdown()
if self._handler:
try:
# aiohttp < 2.3
yield from self._handler.finish_connections(2) # Parameter is timeout
except AttributeError:
# aiohttp >= 2.3
yield from self._handler.shutdown(2) # Parameter is timeout
if self._app:
yield from self._app.cleanup()
yield from Controller.instance().stop()
for module in MODULES:
log.debug("Unloading module {}".format(module.__name__))
m = module.instance()
yield from m.unload()
if PortManager.instance().tcp_ports:
log.warning("TCP ports are still used {}".format(PortManager.instance().tcp_ports))
if PortManager.instance().udp_ports:
log.warning("UDP ports are still used {}".format(PortManager.instance().udp_ports))
for task in asyncio.Task.all_tasks():
task.cancel()
try:
yield from asyncio.wait_for(task, 1)
except BaseException:
pass
self._loop.stop() | [
"def",
"shutdown_server",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_closing",
":",
"self",
".",
"_closing",
"=",
"True",
"else",
":",
"log",
".",
"warning",
"(",
"\"Close is already in progress\"",
")",
"return",
"if",
"self",
".",
"_server",
":",... | Cleanly shutdown the server. | [
"Cleanly",
"shutdown",
"the",
"server",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/web/web_server.py#L87-L133 | train | 221,475 |
GNS3/gns3-server | gns3server/web/web_server.py | WebServer._exit_handling | def _exit_handling(self):
"""
Makes sure the asyncio loop is closed.
"""
def close_asyncio_loop():
loop = None
try:
loop = asyncio.get_event_loop()
except AttributeError:
pass
if loop is not None:
loop.close()
atexit.register(close_asyncio_loop) | python | def _exit_handling(self):
"""
Makes sure the asyncio loop is closed.
"""
def close_asyncio_loop():
loop = None
try:
loop = asyncio.get_event_loop()
except AttributeError:
pass
if loop is not None:
loop.close()
atexit.register(close_asyncio_loop) | [
"def",
"_exit_handling",
"(",
"self",
")",
":",
"def",
"close_asyncio_loop",
"(",
")",
":",
"loop",
"=",
"None",
"try",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"except",
"AttributeError",
":",
"pass",
"if",
"loop",
"is",
"not",
"Non... | Makes sure the asyncio loop is closed. | [
"Makes",
"sure",
"the",
"asyncio",
"loop",
"is",
"closed",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/web/web_server.py#L181-L195 | train | 221,476 |
GNS3/gns3-server | gns3server/web/web_server.py | WebServer._on_startup | def _on_startup(self, *args):
"""
Called when the HTTP server start
"""
yield from Controller.instance().start()
# Because with a large image collection
# without md5sum already computed we start the
# computing with server start
asyncio.async(Qemu.instance().list_images()) | python | def _on_startup(self, *args):
"""
Called when the HTTP server start
"""
yield from Controller.instance().start()
# Because with a large image collection
# without md5sum already computed we start the
# computing with server start
asyncio.async(Qemu.instance().list_images()) | [
"def",
"_on_startup",
"(",
"self",
",",
"*",
"args",
")",
":",
"yield",
"from",
"Controller",
".",
"instance",
"(",
")",
".",
"start",
"(",
")",
"# Because with a large image collection",
"# without md5sum already computed we start the",
"# computing with server start",
... | Called when the HTTP server start | [
"Called",
"when",
"the",
"HTTP",
"server",
"start"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/web/web_server.py#L198-L206 | train | 221,477 |
GNS3/gns3-server | gns3server/compute/builtin/nodes/ethernet_hub.py | EthernetHub.create | def create(self):
"""
Creates this hub.
"""
super().create()
log.info('Ethernet hub "{name}" [{id}] has been created'.format(name=self._name, id=self._id)) | python | def create(self):
"""
Creates this hub.
"""
super().create()
log.info('Ethernet hub "{name}" [{id}] has been created'.format(name=self._name, id=self._id)) | [
"def",
"create",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"create",
"(",
")",
"log",
".",
"info",
"(",
"'Ethernet hub \"{name}\" [{id}] has been created'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"id",
"=",
"self",
".",
"_id",
... | Creates this hub. | [
"Creates",
"this",
"hub",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/builtin/nodes/ethernet_hub.py#L48-L54 | train | 221,478 |
GNS3/gns3-server | gns3server/compute/virtualbox/__init__.py | VirtualBox.list_vms | def list_vms(self, allow_clone=False):
"""
Gets VirtualBox VM list.
"""
vbox_vms = []
result = yield from self.execute("list", ["vms"])
for line in result:
if len(line) == 0 or line[0] != '"' or line[-1:] != "}":
continue # Broken output (perhaps a carriage return in VM name)
vmname, _ = line.rsplit(' ', 1)
vmname = vmname.strip('"')
if vmname == "<inaccessible>":
continue # ignore inaccessible VMs
extra_data = yield from self.execute("getextradata", [vmname, "GNS3/Clone"])
if allow_clone or len(extra_data) == 0 or not extra_data[0].strip() == "Value: yes":
# get the amount of RAM
info_results = yield from self.execute("showvminfo", [vmname, "--machinereadable"])
ram = 0
for info in info_results:
try:
name, value = info.split('=', 1)
if name.strip() == "memory":
ram = int(value.strip())
break
except ValueError:
continue
vbox_vms.append({"vmname": vmname, "ram": ram})
return vbox_vms | python | def list_vms(self, allow_clone=False):
"""
Gets VirtualBox VM list.
"""
vbox_vms = []
result = yield from self.execute("list", ["vms"])
for line in result:
if len(line) == 0 or line[0] != '"' or line[-1:] != "}":
continue # Broken output (perhaps a carriage return in VM name)
vmname, _ = line.rsplit(' ', 1)
vmname = vmname.strip('"')
if vmname == "<inaccessible>":
continue # ignore inaccessible VMs
extra_data = yield from self.execute("getextradata", [vmname, "GNS3/Clone"])
if allow_clone or len(extra_data) == 0 or not extra_data[0].strip() == "Value: yes":
# get the amount of RAM
info_results = yield from self.execute("showvminfo", [vmname, "--machinereadable"])
ram = 0
for info in info_results:
try:
name, value = info.split('=', 1)
if name.strip() == "memory":
ram = int(value.strip())
break
except ValueError:
continue
vbox_vms.append({"vmname": vmname, "ram": ram})
return vbox_vms | [
"def",
"list_vms",
"(",
"self",
",",
"allow_clone",
"=",
"False",
")",
":",
"vbox_vms",
"=",
"[",
"]",
"result",
"=",
"yield",
"from",
"self",
".",
"execute",
"(",
"\"list\"",
",",
"[",
"\"vms\"",
"]",
")",
"for",
"line",
"in",
"result",
":",
"if",
... | Gets VirtualBox VM list. | [
"Gets",
"VirtualBox",
"VM",
"list",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/virtualbox/__init__.py#L174-L202 | train | 221,479 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/c7200.py | C7200.set_npe | def set_npe(self, npe):
"""
Sets the NPE model.
:params npe: NPE model string (e.g. "npe-200")
NPE models are npe-100, npe-150, npe-175, npe-200,
npe-225, npe-300, npe-400 and npe-g2 (PowerPC c7200 only)
"""
if (yield from self.is_running()):
raise DynamipsError("Cannot change NPE on running router")
yield from self._hypervisor.send('c7200 set_npe "{name}" {npe}'.format(name=self._name, npe=npe))
log.info('Router "{name}" [{id}]: NPE updated from {old_npe} to {new_npe}'.format(name=self._name,
id=self._id,
old_npe=self._npe,
new_npe=npe))
self._npe = npe | python | def set_npe(self, npe):
"""
Sets the NPE model.
:params npe: NPE model string (e.g. "npe-200")
NPE models are npe-100, npe-150, npe-175, npe-200,
npe-225, npe-300, npe-400 and npe-g2 (PowerPC c7200 only)
"""
if (yield from self.is_running()):
raise DynamipsError("Cannot change NPE on running router")
yield from self._hypervisor.send('c7200 set_npe "{name}" {npe}'.format(name=self._name, npe=npe))
log.info('Router "{name}" [{id}]: NPE updated from {old_npe} to {new_npe}'.format(name=self._name,
id=self._id,
old_npe=self._npe,
new_npe=npe))
self._npe = npe | [
"def",
"set_npe",
"(",
"self",
",",
"npe",
")",
":",
"if",
"(",
"yield",
"from",
"self",
".",
"is_running",
"(",
")",
")",
":",
"raise",
"DynamipsError",
"(",
"\"Cannot change NPE on running router\"",
")",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
... | Sets the NPE model.
:params npe: NPE model string (e.g. "npe-200")
NPE models are npe-100, npe-150, npe-175, npe-200,
npe-225, npe-300, npe-400 and npe-g2 (PowerPC c7200 only) | [
"Sets",
"the",
"NPE",
"model",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/c7200.py#L114-L132 | train | 221,480 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/c7200.py | C7200.set_midplane | def set_midplane(self, midplane):
"""
Sets the midplane model.
:returns: midplane model string (e.g. "vxr" or "std")
"""
yield from self._hypervisor.send('c7200 set_midplane "{name}" {midplane}'.format(name=self._name, midplane=midplane))
log.info('Router "{name}" [{id}]: midplane updated from {old_midplane} to {new_midplane}'.format(name=self._name,
id=self._id,
old_midplane=self._midplane,
new_midplane=midplane))
self._midplane = midplane | python | def set_midplane(self, midplane):
"""
Sets the midplane model.
:returns: midplane model string (e.g. "vxr" or "std")
"""
yield from self._hypervisor.send('c7200 set_midplane "{name}" {midplane}'.format(name=self._name, midplane=midplane))
log.info('Router "{name}" [{id}]: midplane updated from {old_midplane} to {new_midplane}'.format(name=self._name,
id=self._id,
old_midplane=self._midplane,
new_midplane=midplane))
self._midplane = midplane | [
"def",
"set_midplane",
"(",
"self",
",",
"midplane",
")",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'c7200 set_midplane \"{name}\" {midplane}'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"midplane",
"=",
"midplane",... | Sets the midplane model.
:returns: midplane model string (e.g. "vxr" or "std") | [
"Sets",
"the",
"midplane",
"model",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/c7200.py#L145-L158 | train | 221,481 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/c7200.py | C7200.set_sensors | def set_sensors(self, sensors):
"""
Sets the 4 sensors with temperature in degree Celcius.
:param sensors: list of 4 sensor temperatures corresponding to
sensor 1 = I/0 controller inlet
sensor 2 = I/0 controller outlet
sensor 3 = NPE inlet
sensor 4 = NPE outlet
Example: [22, 22, 22, 22]
"""
sensor_id = 0
for sensor in sensors:
yield from self._hypervisor.send('c7200 set_temp_sensor "{name}" {sensor_id} {temp}'.format(name=self._name,
sensor_id=sensor_id,
temp=sensor))
log.info('Router "{name}" [{id}]: sensor {sensor_id} temperature updated from {old_temp}C to {new_temp}C'.format(name=self._name,
id=self._id,
sensor_id=sensor_id,
old_temp=self._sensors[sensor_id],
new_temp=sensors[sensor_id]))
sensor_id += 1
self._sensors = sensors | python | def set_sensors(self, sensors):
"""
Sets the 4 sensors with temperature in degree Celcius.
:param sensors: list of 4 sensor temperatures corresponding to
sensor 1 = I/0 controller inlet
sensor 2 = I/0 controller outlet
sensor 3 = NPE inlet
sensor 4 = NPE outlet
Example: [22, 22, 22, 22]
"""
sensor_id = 0
for sensor in sensors:
yield from self._hypervisor.send('c7200 set_temp_sensor "{name}" {sensor_id} {temp}'.format(name=self._name,
sensor_id=sensor_id,
temp=sensor))
log.info('Router "{name}" [{id}]: sensor {sensor_id} temperature updated from {old_temp}C to {new_temp}C'.format(name=self._name,
id=self._id,
sensor_id=sensor_id,
old_temp=self._sensors[sensor_id],
new_temp=sensors[sensor_id]))
sensor_id += 1
self._sensors = sensors | [
"def",
"set_sensors",
"(",
"self",
",",
"sensors",
")",
":",
"sensor_id",
"=",
"0",
"for",
"sensor",
"in",
"sensors",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'c7200 set_temp_sensor \"{name}\" {sensor_id} {temp}'",
".",
"format",
"(",... | Sets the 4 sensors with temperature in degree Celcius.
:param sensors: list of 4 sensor temperatures corresponding to
sensor 1 = I/0 controller inlet
sensor 2 = I/0 controller outlet
sensor 3 = NPE inlet
sensor 4 = NPE outlet
Example: [22, 22, 22, 22] | [
"Sets",
"the",
"4",
"sensors",
"with",
"temperature",
"in",
"degree",
"Celcius",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/c7200.py#L171-L196 | train | 221,482 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/c7200.py | C7200.set_power_supplies | def set_power_supplies(self, power_supplies):
"""
Sets the 2 power supplies with 0 = off, 1 = on.
:param power_supplies: list of 2 power supplies.
Example: [1, 0] = first power supply is on, second is off.
"""
power_supply_id = 0
for power_supply in power_supplies:
yield from self._hypervisor.send('c7200 set_power_supply "{name}" {power_supply_id} {powered_on}'.format(name=self._name,
power_supply_id=power_supply_id,
powered_on=power_supply))
log.info('Router "{name}" [{id}]: power supply {power_supply_id} state updated to {powered_on}'.format(name=self._name,
id=self._id,
power_supply_id=power_supply_id,
powered_on=power_supply))
power_supply_id += 1
self._power_supplies = power_supplies | python | def set_power_supplies(self, power_supplies):
"""
Sets the 2 power supplies with 0 = off, 1 = on.
:param power_supplies: list of 2 power supplies.
Example: [1, 0] = first power supply is on, second is off.
"""
power_supply_id = 0
for power_supply in power_supplies:
yield from self._hypervisor.send('c7200 set_power_supply "{name}" {power_supply_id} {powered_on}'.format(name=self._name,
power_supply_id=power_supply_id,
powered_on=power_supply))
log.info('Router "{name}" [{id}]: power supply {power_supply_id} state updated to {powered_on}'.format(name=self._name,
id=self._id,
power_supply_id=power_supply_id,
powered_on=power_supply))
power_supply_id += 1
self._power_supplies = power_supplies | [
"def",
"set_power_supplies",
"(",
"self",
",",
"power_supplies",
")",
":",
"power_supply_id",
"=",
"0",
"for",
"power_supply",
"in",
"power_supplies",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'c7200 set_power_supply \"{name}\" {power_supply... | Sets the 2 power supplies with 0 = off, 1 = on.
:param power_supplies: list of 2 power supplies.
Example: [1, 0] = first power supply is on, second is off. | [
"Sets",
"the",
"2",
"power",
"supplies",
"with",
"0",
"=",
"off",
"1",
"=",
"on",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/c7200.py#L209-L229 | train | 221,483 |
GNS3/gns3-server | gns3server/compute/dynamips/nodes/c7200.py | C7200.start | def start(self):
"""
Starts this router.
At least the IOS image must be set before starting it.
"""
# trick: we must send sensors and power supplies info after starting the router
# otherwise they are not taken into account (Dynamips bug?)
yield from Router.start(self)
if self._sensors != [22, 22, 22, 22]:
yield from self.set_sensors(self._sensors)
if self._power_supplies != [1, 1]:
yield from self.set_power_supplies(self._power_supplies) | python | def start(self):
"""
Starts this router.
At least the IOS image must be set before starting it.
"""
# trick: we must send sensors and power supplies info after starting the router
# otherwise they are not taken into account (Dynamips bug?)
yield from Router.start(self)
if self._sensors != [22, 22, 22, 22]:
yield from self.set_sensors(self._sensors)
if self._power_supplies != [1, 1]:
yield from self.set_power_supplies(self._power_supplies) | [
"def",
"start",
"(",
"self",
")",
":",
"# trick: we must send sensors and power supplies info after starting the router",
"# otherwise they are not taken into account (Dynamips bug?)",
"yield",
"from",
"Router",
".",
"start",
"(",
"self",
")",
"if",
"self",
".",
"_sensors",
"... | Starts this router.
At least the IOS image must be set before starting it. | [
"Starts",
"this",
"router",
".",
"At",
"least",
"the",
"IOS",
"image",
"must",
"be",
"set",
"before",
"starting",
"it",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/c7200.py#L232-L244 | train | 221,484 |
GNS3/gns3-server | gns3server/controller/export_project.py | export_project | def export_project(project, temporary_dir, include_images=False, keep_compute_id=False,
allow_all_nodes=False, ignore_prefixes=None):
"""
Export the project as zip. It's a ZipStream object.
The file will be read chunk by chunk when you iterate on
the zip.
It will ignore some files like snapshots and
:param temporary_dir: A temporary dir where to store intermediate data
:param keep_compute_id: If false replace all compute id by local it's the standard behavior for .gns3project to make them portable
:param allow_all_nodes: Allow all nodes type to be include in the zip even if not portable default False
:returns: ZipStream object
"""
# To avoid issue with data not saved we disallow the export of a running topologie
if project.is_running():
raise aiohttp.web.HTTPConflict(text="Running topology could not be exported")
# Make sure we save the project
project.dump()
z = zipstream.ZipFile(allowZip64=True)
if not os.path.exists(project._path):
raise aiohttp.web.HTTPNotFound(text="The project doesn't exist at location {}".format(project._path))
# First we process the .gns3 in order to be sure we don't have an error
for file in os.listdir(project._path):
if file.endswith(".gns3"):
images = yield from _export_project_file(project, os.path.join(project._path, file),
z, include_images, keep_compute_id, allow_all_nodes, temporary_dir)
for root, dirs, files in os.walk(project._path, topdown=True):
files = [f for f in files if not _filter_files(os.path.join(root, f))]
for file in files:
path = os.path.join(root, file)
# Try open the file
try:
open(path).close()
except OSError as e:
msg = "Could not export file {}: {}".format(path, e)
log.warn(msg)
project.controller.notification.emit("log.warning", {"message": msg})
continue
if file.endswith(".gns3"):
pass
else:
z.write(path, os.path.relpath(path, project._path), compress_type=zipfile.ZIP_DEFLATED)
downloaded_files = set()
for compute in project.computes:
if compute.id != "local":
compute_files = yield from compute.list_files(project)
for compute_file in compute_files:
if not _filter_files(compute_file["path"]):
(fd, temp_path) = tempfile.mkstemp(dir=temporary_dir)
f = open(fd, "wb", closefd=True)
response = yield from compute.download_file(project, compute_file["path"])
while True:
data = yield from response.content.read(512)
if not data:
break
f.write(data)
response.close()
f.close()
z.write(temp_path, arcname=compute_file["path"], compress_type=zipfile.ZIP_DEFLATED)
downloaded_files.add(compute_file['path'])
return z | python | def export_project(project, temporary_dir, include_images=False, keep_compute_id=False,
allow_all_nodes=False, ignore_prefixes=None):
"""
Export the project as zip. It's a ZipStream object.
The file will be read chunk by chunk when you iterate on
the zip.
It will ignore some files like snapshots and
:param temporary_dir: A temporary dir where to store intermediate data
:param keep_compute_id: If false replace all compute id by local it's the standard behavior for .gns3project to make them portable
:param allow_all_nodes: Allow all nodes type to be include in the zip even if not portable default False
:returns: ZipStream object
"""
# To avoid issue with data not saved we disallow the export of a running topologie
if project.is_running():
raise aiohttp.web.HTTPConflict(text="Running topology could not be exported")
# Make sure we save the project
project.dump()
z = zipstream.ZipFile(allowZip64=True)
if not os.path.exists(project._path):
raise aiohttp.web.HTTPNotFound(text="The project doesn't exist at location {}".format(project._path))
# First we process the .gns3 in order to be sure we don't have an error
for file in os.listdir(project._path):
if file.endswith(".gns3"):
images = yield from _export_project_file(project, os.path.join(project._path, file),
z, include_images, keep_compute_id, allow_all_nodes, temporary_dir)
for root, dirs, files in os.walk(project._path, topdown=True):
files = [f for f in files if not _filter_files(os.path.join(root, f))]
for file in files:
path = os.path.join(root, file)
# Try open the file
try:
open(path).close()
except OSError as e:
msg = "Could not export file {}: {}".format(path, e)
log.warn(msg)
project.controller.notification.emit("log.warning", {"message": msg})
continue
if file.endswith(".gns3"):
pass
else:
z.write(path, os.path.relpath(path, project._path), compress_type=zipfile.ZIP_DEFLATED)
downloaded_files = set()
for compute in project.computes:
if compute.id != "local":
compute_files = yield from compute.list_files(project)
for compute_file in compute_files:
if not _filter_files(compute_file["path"]):
(fd, temp_path) = tempfile.mkstemp(dir=temporary_dir)
f = open(fd, "wb", closefd=True)
response = yield from compute.download_file(project, compute_file["path"])
while True:
data = yield from response.content.read(512)
if not data:
break
f.write(data)
response.close()
f.close()
z.write(temp_path, arcname=compute_file["path"], compress_type=zipfile.ZIP_DEFLATED)
downloaded_files.add(compute_file['path'])
return z | [
"def",
"export_project",
"(",
"project",
",",
"temporary_dir",
",",
"include_images",
"=",
"False",
",",
"keep_compute_id",
"=",
"False",
",",
"allow_all_nodes",
"=",
"False",
",",
"ignore_prefixes",
"=",
"None",
")",
":",
"# To avoid issue with data not saved we disa... | Export the project as zip. It's a ZipStream object.
The file will be read chunk by chunk when you iterate on
the zip.
It will ignore some files like snapshots and
:param temporary_dir: A temporary dir where to store intermediate data
:param keep_compute_id: If false replace all compute id by local it's the standard behavior for .gns3project to make them portable
:param allow_all_nodes: Allow all nodes type to be include in the zip even if not portable default False
:returns: ZipStream object | [
"Export",
"the",
"project",
"as",
"zip",
".",
"It",
"s",
"a",
"ZipStream",
"object",
".",
"The",
"file",
"will",
"be",
"read",
"chunk",
"by",
"chunk",
"when",
"you",
"iterate",
"on",
"the",
"zip",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/export_project.py#L32-L102 | train | 221,485 |
GNS3/gns3-server | gns3server/controller/notification.py | Notification.dispatch | def dispatch(self, action, event, compute_id):
"""
Notification received from compute node. Send it directly
to clients or process it
:param action: Action name
:param event: Event to send
:param compute_id: Compute id of the sender
"""
if action == "node.updated":
try:
# Update controller node data and send the event node.updated
project = self._controller.get_project(event["project_id"])
node = project.get_node(event["node_id"])
yield from node.parse_node_response(event)
self.emit("node.updated", node.__json__())
except (aiohttp.web.HTTPNotFound, aiohttp.web.HTTPForbidden): # Project closing
return
elif action == "ping":
event["compute_id"] = compute_id
self.emit(action, event)
else:
self.emit(action, event) | python | def dispatch(self, action, event, compute_id):
"""
Notification received from compute node. Send it directly
to clients or process it
:param action: Action name
:param event: Event to send
:param compute_id: Compute id of the sender
"""
if action == "node.updated":
try:
# Update controller node data and send the event node.updated
project = self._controller.get_project(event["project_id"])
node = project.get_node(event["node_id"])
yield from node.parse_node_response(event)
self.emit("node.updated", node.__json__())
except (aiohttp.web.HTTPNotFound, aiohttp.web.HTTPForbidden): # Project closing
return
elif action == "ping":
event["compute_id"] = compute_id
self.emit(action, event)
else:
self.emit(action, event) | [
"def",
"dispatch",
"(",
"self",
",",
"action",
",",
"event",
",",
"compute_id",
")",
":",
"if",
"action",
"==",
"\"node.updated\"",
":",
"try",
":",
"# Update controller node data and send the event node.updated",
"project",
"=",
"self",
".",
"_controller",
".",
"... | Notification received from compute node. Send it directly
to clients or process it
:param action: Action name
:param event: Event to send
:param compute_id: Compute id of the sender | [
"Notification",
"received",
"from",
"compute",
"node",
".",
"Send",
"it",
"directly",
"to",
"clients",
"or",
"process",
"it"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/notification.py#L56-L79 | train | 221,486 |
GNS3/gns3-server | gns3server/controller/notification.py | Notification.emit | def emit(self, action, event):
"""
Send a notification to clients scoped by projects
:param action: Action name
:param event: Event to send
"""
# If use in tests for documentation we save a sample
if os.environ.get("PYTEST_BUILD_DOCUMENTATION") == "1":
os.makedirs("docs/api/notifications", exist_ok=True)
try:
import json
data = json.dumps(event, indent=4, sort_keys=True)
if "MagicMock" not in data:
with open(os.path.join("docs/api/notifications", action + ".json"), 'w+') as f:
f.write(data)
except TypeError: # If we receive a mock as an event it will raise TypeError when using json dump
pass
if "project_id" in event:
self._send_event_to_project(event["project_id"], action, event)
else:
self._send_event_to_all(action, event) | python | def emit(self, action, event):
"""
Send a notification to clients scoped by projects
:param action: Action name
:param event: Event to send
"""
# If use in tests for documentation we save a sample
if os.environ.get("PYTEST_BUILD_DOCUMENTATION") == "1":
os.makedirs("docs/api/notifications", exist_ok=True)
try:
import json
data = json.dumps(event, indent=4, sort_keys=True)
if "MagicMock" not in data:
with open(os.path.join("docs/api/notifications", action + ".json"), 'w+') as f:
f.write(data)
except TypeError: # If we receive a mock as an event it will raise TypeError when using json dump
pass
if "project_id" in event:
self._send_event_to_project(event["project_id"], action, event)
else:
self._send_event_to_all(action, event) | [
"def",
"emit",
"(",
"self",
",",
"action",
",",
"event",
")",
":",
"# If use in tests for documentation we save a sample",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"\"PYTEST_BUILD_DOCUMENTATION\"",
")",
"==",
"\"1\"",
":",
"os",
".",
"makedirs",
"(",
"\"docs... | Send a notification to clients scoped by projects
:param action: Action name
:param event: Event to send | [
"Send",
"a",
"notification",
"to",
"clients",
"scoped",
"by",
"projects"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/notification.py#L81-L104 | train | 221,487 |
GNS3/gns3-server | gns3server/controller/notification.py | Notification._send_event_to_project | def _send_event_to_project(self, project_id, action, event):
"""
Send an event to all the client listening for notifications for
this project
:param project: Project where we need to send the event
:param action: Action name
:param event: Event to send
"""
try:
project_listeners = self._listeners[project_id]
except KeyError:
return
for listener in project_listeners:
listener.put_nowait((action, event, {})) | python | def _send_event_to_project(self, project_id, action, event):
"""
Send an event to all the client listening for notifications for
this project
:param project: Project where we need to send the event
:param action: Action name
:param event: Event to send
"""
try:
project_listeners = self._listeners[project_id]
except KeyError:
return
for listener in project_listeners:
listener.put_nowait((action, event, {})) | [
"def",
"_send_event_to_project",
"(",
"self",
",",
"project_id",
",",
"action",
",",
"event",
")",
":",
"try",
":",
"project_listeners",
"=",
"self",
".",
"_listeners",
"[",
"project_id",
"]",
"except",
"KeyError",
":",
"return",
"for",
"listener",
"in",
"pr... | Send an event to all the client listening for notifications for
this project
:param project: Project where we need to send the event
:param action: Action name
:param event: Event to send | [
"Send",
"an",
"event",
"to",
"all",
"the",
"client",
"listening",
"for",
"notifications",
"for",
"this",
"project"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/notification.py#L106-L120 | train | 221,488 |
GNS3/gns3-server | gns3server/controller/notification.py | Notification._send_event_to_all | def _send_event_to_all(self, action, event):
"""
Send an event to all the client listening for notifications on all
projects
:param action: Action name
:param event: Event to send
"""
for project_listeners in self._listeners.values():
for listener in project_listeners:
listener.put_nowait((action, event, {})) | python | def _send_event_to_all(self, action, event):
"""
Send an event to all the client listening for notifications on all
projects
:param action: Action name
:param event: Event to send
"""
for project_listeners in self._listeners.values():
for listener in project_listeners:
listener.put_nowait((action, event, {})) | [
"def",
"_send_event_to_all",
"(",
"self",
",",
"action",
",",
"event",
")",
":",
"for",
"project_listeners",
"in",
"self",
".",
"_listeners",
".",
"values",
"(",
")",
":",
"for",
"listener",
"in",
"project_listeners",
":",
"listener",
".",
"put_nowait",
"(",... | Send an event to all the client listening for notifications on all
projects
:param action: Action name
:param event: Event to send | [
"Send",
"an",
"event",
"to",
"all",
"the",
"client",
"listening",
"for",
"notifications",
"on",
"all",
"projects"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/notification.py#L122-L132 | train | 221,489 |
GNS3/gns3-server | gns3server/controller/__init__.py | Controller._update_config | def _update_config(self):
"""
Call this when the server configuration file
change
"""
if self._local_server:
server_config = Config.instance().get_section_config("Server")
self._local_server.user = server_config.get("user")
self._local_server.password = server_config.get("password") | python | def _update_config(self):
"""
Call this when the server configuration file
change
"""
if self._local_server:
server_config = Config.instance().get_section_config("Server")
self._local_server.user = server_config.get("user")
self._local_server.password = server_config.get("password") | [
"def",
"_update_config",
"(",
"self",
")",
":",
"if",
"self",
".",
"_local_server",
":",
"server_config",
"=",
"Config",
".",
"instance",
"(",
")",
".",
"get_section_config",
"(",
"\"Server\"",
")",
"self",
".",
"_local_server",
".",
"user",
"=",
"server_con... | Call this when the server configuration file
change | [
"Call",
"this",
"when",
"the",
"server",
"configuration",
"file",
"change"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/__init__.py#L205-L213 | train | 221,490 |
GNS3/gns3-server | gns3server/controller/__init__.py | Controller.save | def save(self):
"""
Save the controller configuration on disk
"""
# We don't save during the loading otherwise we could lost stuff
if self._settings is None:
return
data = {
"computes": [],
"settings": self._settings,
"gns3vm": self.gns3vm.__json__(),
"version": __version__
}
for c in self._computes.values():
if c.id != "local" and c.id != "vm":
data["computes"].append({
"host": c.host,
"name": c.name,
"port": c.port,
"protocol": c.protocol,
"user": c.user,
"password": c.password,
"compute_id": c.id
})
try:
os.makedirs(os.path.dirname(self._config_file), exist_ok=True)
with open(self._config_file, 'w+') as f:
json.dump(data, f, indent=4)
except OSError as e:
log.error("Can't write the configuration {}: {}".format(self._config_file, str(e))) | python | def save(self):
"""
Save the controller configuration on disk
"""
# We don't save during the loading otherwise we could lost stuff
if self._settings is None:
return
data = {
"computes": [],
"settings": self._settings,
"gns3vm": self.gns3vm.__json__(),
"version": __version__
}
for c in self._computes.values():
if c.id != "local" and c.id != "vm":
data["computes"].append({
"host": c.host,
"name": c.name,
"port": c.port,
"protocol": c.protocol,
"user": c.user,
"password": c.password,
"compute_id": c.id
})
try:
os.makedirs(os.path.dirname(self._config_file), exist_ok=True)
with open(self._config_file, 'w+') as f:
json.dump(data, f, indent=4)
except OSError as e:
log.error("Can't write the configuration {}: {}".format(self._config_file, str(e))) | [
"def",
"save",
"(",
"self",
")",
":",
"# We don't save during the loading otherwise we could lost stuff",
"if",
"self",
".",
"_settings",
"is",
"None",
":",
"return",
"data",
"=",
"{",
"\"computes\"",
":",
"[",
"]",
",",
"\"settings\"",
":",
"self",
".",
"_setti... | Save the controller configuration on disk | [
"Save",
"the",
"controller",
"configuration",
"on",
"disk"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/__init__.py#L230-L260 | train | 221,491 |
GNS3/gns3-server | gns3server/controller/__init__.py | Controller._load_controller_settings | def _load_controller_settings(self):
"""
Reload the controller configuration from disk
"""
try:
if not os.path.exists(self._config_file):
yield from self._import_gns3_gui_conf()
self.save()
with open(self._config_file) as f:
data = json.load(f)
except (OSError, ValueError) as e:
log.critical("Cannot load %s: %s", self._config_file, str(e))
self._settings = {}
return []
if "settings" in data and data["settings"] is not None:
self._settings = data["settings"]
else:
self._settings = {}
if "gns3vm" in data:
self.gns3vm.settings = data["gns3vm"]
self.load_appliances()
return data.get("computes", []) | python | def _load_controller_settings(self):
"""
Reload the controller configuration from disk
"""
try:
if not os.path.exists(self._config_file):
yield from self._import_gns3_gui_conf()
self.save()
with open(self._config_file) as f:
data = json.load(f)
except (OSError, ValueError) as e:
log.critical("Cannot load %s: %s", self._config_file, str(e))
self._settings = {}
return []
if "settings" in data and data["settings"] is not None:
self._settings = data["settings"]
else:
self._settings = {}
if "gns3vm" in data:
self.gns3vm.settings = data["gns3vm"]
self.load_appliances()
return data.get("computes", []) | [
"def",
"_load_controller_settings",
"(",
"self",
")",
":",
"try",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_config_file",
")",
":",
"yield",
"from",
"self",
".",
"_import_gns3_gui_conf",
"(",
")",
"self",
".",
"save",
"(",
... | Reload the controller configuration from disk | [
"Reload",
"the",
"controller",
"configuration",
"from",
"disk"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/__init__.py#L263-L286 | train | 221,492 |
GNS3/gns3-server | gns3server/controller/__init__.py | Controller.load_projects | def load_projects(self):
"""
Preload the list of projects from disk
"""
server_config = Config.instance().get_section_config("Server")
projects_path = os.path.expanduser(server_config.get("projects_path", "~/GNS3/projects"))
os.makedirs(projects_path, exist_ok=True)
try:
for project_path in os.listdir(projects_path):
project_dir = os.path.join(projects_path, project_path)
if os.path.isdir(project_dir):
for file in os.listdir(project_dir):
if file.endswith(".gns3"):
try:
yield from self.load_project(os.path.join(project_dir, file), load=False)
except (aiohttp.web_exceptions.HTTPConflict, NotImplementedError):
pass # Skip not compatible projects
except OSError as e:
log.error(str(e)) | python | def load_projects(self):
"""
Preload the list of projects from disk
"""
server_config = Config.instance().get_section_config("Server")
projects_path = os.path.expanduser(server_config.get("projects_path", "~/GNS3/projects"))
os.makedirs(projects_path, exist_ok=True)
try:
for project_path in os.listdir(projects_path):
project_dir = os.path.join(projects_path, project_path)
if os.path.isdir(project_dir):
for file in os.listdir(project_dir):
if file.endswith(".gns3"):
try:
yield from self.load_project(os.path.join(project_dir, file), load=False)
except (aiohttp.web_exceptions.HTTPConflict, NotImplementedError):
pass # Skip not compatible projects
except OSError as e:
log.error(str(e)) | [
"def",
"load_projects",
"(",
"self",
")",
":",
"server_config",
"=",
"Config",
".",
"instance",
"(",
")",
".",
"get_section_config",
"(",
"\"Server\"",
")",
"projects_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"server_config",
".",
"get",
"(",
... | Preload the list of projects from disk | [
"Preload",
"the",
"list",
"of",
"projects",
"from",
"disk"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/__init__.py#L289-L307 | train | 221,493 |
GNS3/gns3-server | gns3server/controller/__init__.py | Controller.load_base_files | def load_base_files(self):
"""
At startup we copy base file to the user location to allow
them to customize it
"""
dst_path = self.configs_path()
src_path = get_resource('configs')
try:
for file in os.listdir(src_path):
if not os.path.exists(os.path.join(dst_path, file)):
shutil.copy(os.path.join(src_path, file), os.path.join(dst_path, file))
except OSError:
pass | python | def load_base_files(self):
"""
At startup we copy base file to the user location to allow
them to customize it
"""
dst_path = self.configs_path()
src_path = get_resource('configs')
try:
for file in os.listdir(src_path):
if not os.path.exists(os.path.join(dst_path, file)):
shutil.copy(os.path.join(src_path, file), os.path.join(dst_path, file))
except OSError:
pass | [
"def",
"load_base_files",
"(",
"self",
")",
":",
"dst_path",
"=",
"self",
".",
"configs_path",
"(",
")",
"src_path",
"=",
"get_resource",
"(",
"'configs'",
")",
"try",
":",
"for",
"file",
"in",
"os",
".",
"listdir",
"(",
"src_path",
")",
":",
"if",
"no... | At startup we copy base file to the user location to allow
them to customize it | [
"At",
"startup",
"we",
"copy",
"base",
"file",
"to",
"the",
"user",
"location",
"to",
"allow",
"them",
"to",
"customize",
"it"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/__init__.py#L309-L321 | train | 221,494 |
GNS3/gns3-server | gns3server/controller/__init__.py | Controller._import_gns3_gui_conf | def _import_gns3_gui_conf(self):
"""
Import old config from GNS3 GUI
"""
config_file = os.path.join(os.path.dirname(self._config_file), "gns3_gui.conf")
if os.path.exists(config_file):
with open(config_file) as f:
data = json.load(f)
server_settings = data.get("Servers", {})
for remote in server_settings.get("remote_servers", []):
try:
yield from self.add_compute(
host=remote.get("host", "localhost"),
port=remote.get("port", 3080),
protocol=remote.get("protocol", "http"),
name=remote.get("url"),
user=remote.get("user"),
password=remote.get("password")
)
except aiohttp.web.HTTPConflict:
pass # if the server is broken we skip it
if "vm" in server_settings:
vmname = None
vm_settings = server_settings["vm"]
if vm_settings["virtualization"] == "VMware":
engine = "vmware"
vmname = vm_settings.get("vmname", "")
elif vm_settings["virtualization"] == "VirtualBox":
engine = "virtualbox"
vmname = vm_settings.get("vmname", "")
else:
engine = "remote"
# In case of remote server we match the compute with url parameter
for compute in self._computes.values():
if compute.host == vm_settings.get("remote_vm_host") and compute.port == vm_settings.get("remote_vm_port"):
vmname = compute.name
if vm_settings.get("auto_stop", True):
when_exit = "stop"
else:
when_exit = "keep"
self.gns3vm.settings = {
"engine": engine,
"enable": vm_settings.get("auto_start", False),
"when_exit": when_exit,
"headless": vm_settings.get("headless", False),
"vmname": vmname
}
self._settings = {} | python | def _import_gns3_gui_conf(self):
"""
Import old config from GNS3 GUI
"""
config_file = os.path.join(os.path.dirname(self._config_file), "gns3_gui.conf")
if os.path.exists(config_file):
with open(config_file) as f:
data = json.load(f)
server_settings = data.get("Servers", {})
for remote in server_settings.get("remote_servers", []):
try:
yield from self.add_compute(
host=remote.get("host", "localhost"),
port=remote.get("port", 3080),
protocol=remote.get("protocol", "http"),
name=remote.get("url"),
user=remote.get("user"),
password=remote.get("password")
)
except aiohttp.web.HTTPConflict:
pass # if the server is broken we skip it
if "vm" in server_settings:
vmname = None
vm_settings = server_settings["vm"]
if vm_settings["virtualization"] == "VMware":
engine = "vmware"
vmname = vm_settings.get("vmname", "")
elif vm_settings["virtualization"] == "VirtualBox":
engine = "virtualbox"
vmname = vm_settings.get("vmname", "")
else:
engine = "remote"
# In case of remote server we match the compute with url parameter
for compute in self._computes.values():
if compute.host == vm_settings.get("remote_vm_host") and compute.port == vm_settings.get("remote_vm_port"):
vmname = compute.name
if vm_settings.get("auto_stop", True):
when_exit = "stop"
else:
when_exit = "keep"
self.gns3vm.settings = {
"engine": engine,
"enable": vm_settings.get("auto_start", False),
"when_exit": when_exit,
"headless": vm_settings.get("headless", False),
"vmname": vmname
}
self._settings = {} | [
"def",
"_import_gns3_gui_conf",
"(",
"self",
")",
":",
"config_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"_config_file",
")",
",",
"\"gns3_gui.conf\"",
")",
"if",
"os",
".",
"path",
".",
"exis... | Import old config from GNS3 GUI | [
"Import",
"old",
"config",
"from",
"GNS3",
"GUI"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/__init__.py#L351-L400 | train | 221,495 |
GNS3/gns3-server | gns3server/controller/__init__.py | Controller.add_compute | def add_compute(self, compute_id=None, name=None, force=False, connect=True, **kwargs):
"""
Add a server to the dictionary of compute servers controlled by this controller
:param compute_id: Compute server identifier
:param name: Compute name
:param force: True skip security check
:param connect: True connect to the compute immediately
:param kwargs: See the documentation of Compute
"""
if compute_id not in self._computes:
# We disallow to create from the outside the local and VM server
if (compute_id == 'local' or compute_id == 'vm') and not force:
return None
# It seem we have error with a gns3vm imported as a remote server and conflict
# with GNS3 VM settings. That's why we ignore server name gns3vm
if name == 'gns3vm':
return None
for compute in self._computes.values():
if name and compute.name == name and not force:
raise aiohttp.web.HTTPConflict(text='Compute name "{}" already exists'.format(name))
compute = Compute(compute_id=compute_id, controller=self, name=name, **kwargs)
self._computes[compute.id] = compute
self.save()
if connect:
yield from compute.connect()
self.notification.emit("compute.created", compute.__json__())
return compute
else:
if connect:
yield from self._computes[compute_id].connect()
self.notification.emit("compute.updated", self._computes[compute_id].__json__())
return self._computes[compute_id] | python | def add_compute(self, compute_id=None, name=None, force=False, connect=True, **kwargs):
"""
Add a server to the dictionary of compute servers controlled by this controller
:param compute_id: Compute server identifier
:param name: Compute name
:param force: True skip security check
:param connect: True connect to the compute immediately
:param kwargs: See the documentation of Compute
"""
if compute_id not in self._computes:
# We disallow to create from the outside the local and VM server
if (compute_id == 'local' or compute_id == 'vm') and not force:
return None
# It seem we have error with a gns3vm imported as a remote server and conflict
# with GNS3 VM settings. That's why we ignore server name gns3vm
if name == 'gns3vm':
return None
for compute in self._computes.values():
if name and compute.name == name and not force:
raise aiohttp.web.HTTPConflict(text='Compute name "{}" already exists'.format(name))
compute = Compute(compute_id=compute_id, controller=self, name=name, **kwargs)
self._computes[compute.id] = compute
self.save()
if connect:
yield from compute.connect()
self.notification.emit("compute.created", compute.__json__())
return compute
else:
if connect:
yield from self._computes[compute_id].connect()
self.notification.emit("compute.updated", self._computes[compute_id].__json__())
return self._computes[compute_id] | [
"def",
"add_compute",
"(",
"self",
",",
"compute_id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"force",
"=",
"False",
",",
"connect",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"compute_id",
"not",
"in",
"self",
".",
"_computes",
":",
... | Add a server to the dictionary of compute servers controlled by this controller
:param compute_id: Compute server identifier
:param name: Compute name
:param force: True skip security check
:param connect: True connect to the compute immediately
:param kwargs: See the documentation of Compute | [
"Add",
"a",
"server",
"to",
"the",
"dictionary",
"of",
"compute",
"servers",
"controlled",
"by",
"this",
"controller"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/__init__.py#L418-L455 | train | 221,496 |
GNS3/gns3-server | gns3server/controller/__init__.py | Controller.close_compute_projects | def close_compute_projects(self, compute):
"""
Close projects running on a compute
"""
for project in self._projects.values():
if compute in project.computes:
yield from project.close() | python | def close_compute_projects(self, compute):
"""
Close projects running on a compute
"""
for project in self._projects.values():
if compute in project.computes:
yield from project.close() | [
"def",
"close_compute_projects",
"(",
"self",
",",
"compute",
")",
":",
"for",
"project",
"in",
"self",
".",
"_projects",
".",
"values",
"(",
")",
":",
"if",
"compute",
"in",
"project",
".",
"computes",
":",
"yield",
"from",
"project",
".",
"close",
"(",... | Close projects running on a compute | [
"Close",
"projects",
"running",
"on",
"a",
"compute"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/__init__.py#L458-L464 | train | 221,497 |
GNS3/gns3-server | gns3server/controller/__init__.py | Controller.delete_compute | def delete_compute(self, compute_id):
"""
Delete a compute node. Project using this compute will be close
:param compute_id: Compute server identifier
"""
try:
compute = self.get_compute(compute_id)
except aiohttp.web.HTTPNotFound:
return
yield from self.close_compute_projects(compute)
yield from compute.close()
del self._computes[compute_id]
self.save()
self.notification.emit("compute.deleted", compute.__json__()) | python | def delete_compute(self, compute_id):
"""
Delete a compute node. Project using this compute will be close
:param compute_id: Compute server identifier
"""
try:
compute = self.get_compute(compute_id)
except aiohttp.web.HTTPNotFound:
return
yield from self.close_compute_projects(compute)
yield from compute.close()
del self._computes[compute_id]
self.save()
self.notification.emit("compute.deleted", compute.__json__()) | [
"def",
"delete_compute",
"(",
"self",
",",
"compute_id",
")",
":",
"try",
":",
"compute",
"=",
"self",
".",
"get_compute",
"(",
"compute_id",
")",
"except",
"aiohttp",
".",
"web",
".",
"HTTPNotFound",
":",
"return",
"yield",
"from",
"self",
".",
"close_com... | Delete a compute node. Project using this compute will be close
:param compute_id: Compute server identifier | [
"Delete",
"a",
"compute",
"node",
".",
"Project",
"using",
"this",
"compute",
"will",
"be",
"close"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/__init__.py#L467-L481 | train | 221,498 |
GNS3/gns3-server | gns3server/controller/__init__.py | Controller.get_compute | def get_compute(self, compute_id):
"""
Returns a compute server or raise a 404 error.
"""
try:
return self._computes[compute_id]
except KeyError:
if compute_id == "vm":
raise aiohttp.web.HTTPNotFound(text="You try to use a node on the GNS3 VM server but the GNS3 VM is not configured")
raise aiohttp.web.HTTPNotFound(text="Compute ID {} doesn't exist".format(compute_id)) | python | def get_compute(self, compute_id):
"""
Returns a compute server or raise a 404 error.
"""
try:
return self._computes[compute_id]
except KeyError:
if compute_id == "vm":
raise aiohttp.web.HTTPNotFound(text="You try to use a node on the GNS3 VM server but the GNS3 VM is not configured")
raise aiohttp.web.HTTPNotFound(text="Compute ID {} doesn't exist".format(compute_id)) | [
"def",
"get_compute",
"(",
"self",
",",
"compute_id",
")",
":",
"try",
":",
"return",
"self",
".",
"_computes",
"[",
"compute_id",
"]",
"except",
"KeyError",
":",
"if",
"compute_id",
"==",
"\"vm\"",
":",
"raise",
"aiohttp",
".",
"web",
".",
"HTTPNotFound",... | Returns a compute server or raise a 404 error. | [
"Returns",
"a",
"compute",
"server",
"or",
"raise",
"a",
"404",
"error",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/__init__.py#L497-L506 | train | 221,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.