id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
226,300 | fhamborg/news-please | newsplease/helper_classes/savepath_parser.py | SavepathParser.append_md5_if_too_long | def append_md5_if_too_long(component, size):
"""
Trims the component if it is longer than size and appends the
component's md5. Total must be of length size.
:param str component: component to work on
:param int size: component's size limit
:return str: component and appended md5 trimmed to be of length size
"""
if len(component) > size:
if size > 32:
component_size = size - 32 - 1
return "%s_%s" % (component[:component_size],
hashlib.md5(component.encode('utf-8')).hexdigest())
else:
return hashlib.md5(component.encode('utf-8')).hexdigest()[:size]
else:
return component | python | def append_md5_if_too_long(component, size):
"""
Trims the component if it is longer than size and appends the
component's md5. Total must be of length size.
:param str component: component to work on
:param int size: component's size limit
:return str: component and appended md5 trimmed to be of length size
"""
if len(component) > size:
if size > 32:
component_size = size - 32 - 1
return "%s_%s" % (component[:component_size],
hashlib.md5(component.encode('utf-8')).hexdigest())
else:
return hashlib.md5(component.encode('utf-8')).hexdigest()[:size]
else:
return component | [
"def",
"append_md5_if_too_long",
"(",
"component",
",",
"size",
")",
":",
"if",
"len",
"(",
"component",
")",
">",
"size",
":",
"if",
"size",
">",
"32",
":",
"component_size",
"=",
"size",
"-",
"32",
"-",
"1",
"return",
"\"%s_%s\"",
"%",
"(",
"componen... | Trims the component if it is longer than size and appends the
component's md5. Total must be of length size.
:param str component: component to work on
:param int size: component's size limit
:return str: component and appended md5 trimmed to be of length size | [
"Trims",
"the",
"component",
"if",
"it",
"is",
"longer",
"than",
"size",
"and",
"appends",
"the",
"component",
"s",
"md5",
".",
"Total",
"must",
"be",
"of",
"length",
"size",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/savepath_parser.py#L90-L108 |
226,301 | fhamborg/news-please | newsplease/helper_classes/savepath_parser.py | SavepathParser.remove_not_allowed_chars | def remove_not_allowed_chars(savepath):
"""
Removes invalid filepath characters from the savepath.
:param str savepath: the savepath to work on
:return str: the savepath without invalid filepath characters
"""
split_savepath = os.path.splitdrive(savepath)
# https://msdn.microsoft.com/en-us/library/aa365247.aspx
savepath_without_invalid_chars = re.sub(r'<|>|:|\"|\||\?|\*', '_',
split_savepath[1])
return split_savepath[0] + savepath_without_invalid_chars | python | def remove_not_allowed_chars(savepath):
"""
Removes invalid filepath characters from the savepath.
:param str savepath: the savepath to work on
:return str: the savepath without invalid filepath characters
"""
split_savepath = os.path.splitdrive(savepath)
# https://msdn.microsoft.com/en-us/library/aa365247.aspx
savepath_without_invalid_chars = re.sub(r'<|>|:|\"|\||\?|\*', '_',
split_savepath[1])
return split_savepath[0] + savepath_without_invalid_chars | [
"def",
"remove_not_allowed_chars",
"(",
"savepath",
")",
":",
"split_savepath",
"=",
"os",
".",
"path",
".",
"splitdrive",
"(",
"savepath",
")",
"# https://msdn.microsoft.com/en-us/library/aa365247.aspx",
"savepath_without_invalid_chars",
"=",
"re",
".",
"sub",
"(",
"r'... | Removes invalid filepath characters from the savepath.
:param str savepath: the savepath to work on
:return str: the savepath without invalid filepath characters | [
"Removes",
"invalid",
"filepath",
"characters",
"from",
"the",
"savepath",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/savepath_parser.py#L219-L230 |
226,302 | fhamborg/news-please | newsplease/helper_classes/savepath_parser.py | SavepathParser.get_abs_path_static | def get_abs_path_static(savepath, relative_to_path):
"""
Figures out the savepath's absolute version.
:param str savepath: the savepath to return an absolute version of
:param str relative_to_path: the file path this savepath should be
relative to
:return str: absolute version of savepath
"""
if os.path.isabs(savepath):
return os.path.abspath(savepath)
else:
return os.path.abspath(
os.path.join(relative_to_path, (savepath))
) | python | def get_abs_path_static(savepath, relative_to_path):
"""
Figures out the savepath's absolute version.
:param str savepath: the savepath to return an absolute version of
:param str relative_to_path: the file path this savepath should be
relative to
:return str: absolute version of savepath
"""
if os.path.isabs(savepath):
return os.path.abspath(savepath)
else:
return os.path.abspath(
os.path.join(relative_to_path, (savepath))
) | [
"def",
"get_abs_path_static",
"(",
"savepath",
",",
"relative_to_path",
")",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"savepath",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"savepath",
")",
"else",
":",
"return",
"os",
".",
"pa... | Figures out the savepath's absolute version.
:param str savepath: the savepath to return an absolute version of
:param str relative_to_path: the file path this savepath should be
relative to
:return str: absolute version of savepath | [
"Figures",
"out",
"the",
"savepath",
"s",
"absolute",
"version",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/savepath_parser.py#L233-L247 |
226,303 | fhamborg/news-please | newsplease/helper_classes/savepath_parser.py | SavepathParser.get_base_path | def get_base_path(path):
"""
Determines the longest possible beginning of a path that does not
contain a %-Symbol.
/this/is/a/pa%th would become /this/is/a
:param str path: the path to get the base from
:return: the path's base
"""
if "%" not in path:
return path
path = os.path.split(path)[0]
while "%" in path:
path = os.path.split(path)[0]
return path | python | def get_base_path(path):
"""
Determines the longest possible beginning of a path that does not
contain a %-Symbol.
/this/is/a/pa%th would become /this/is/a
:param str path: the path to get the base from
:return: the path's base
"""
if "%" not in path:
return path
path = os.path.split(path)[0]
while "%" in path:
path = os.path.split(path)[0]
return path | [
"def",
"get_base_path",
"(",
"path",
")",
":",
"if",
"\"%\"",
"not",
"in",
"path",
":",
"return",
"path",
"path",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"[",
"0",
"]",
"while",
"\"%\"",
"in",
"path",
":",
"path",
"=",
"os",
".",
... | Determines the longest possible beginning of a path that does not
contain a %-Symbol.
/this/is/a/pa%th would become /this/is/a
:param str path: the path to get the base from
:return: the path's base | [
"Determines",
"the",
"longest",
"possible",
"beginning",
"of",
"a",
"path",
"that",
"does",
"not",
"contain",
"a",
"%",
"-",
"Symbol",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/savepath_parser.py#L260-L278 |
226,304 | fhamborg/news-please | newsplease/helper_classes/savepath_parser.py | SavepathParser.get_max_url_file_name_length | def get_max_url_file_name_length(savepath):
"""
Determines the max length for any max... parts.
:param str savepath: absolute savepath to work on
:return: max. allowed number of chars for any of the max... parts
"""
number_occurrences = savepath.count('%max_url_file_name')
number_occurrences += savepath.count('%appendmd5_max_url_file_name')
savepath_copy = savepath
size_without_max_url_file_name = len(
savepath_copy.replace('%max_url_file_name', '')
.replace('%appendmd5_max_url_file_name', '')
)
# Windows: max file path length is 260 characters including
# NULL (string end)
max_size = 260 - 1 - size_without_max_url_file_name
max_size_per_occurrence = max_size / number_occurrences
return max_size_per_occurrence | python | def get_max_url_file_name_length(savepath):
"""
Determines the max length for any max... parts.
:param str savepath: absolute savepath to work on
:return: max. allowed number of chars for any of the max... parts
"""
number_occurrences = savepath.count('%max_url_file_name')
number_occurrences += savepath.count('%appendmd5_max_url_file_name')
savepath_copy = savepath
size_without_max_url_file_name = len(
savepath_copy.replace('%max_url_file_name', '')
.replace('%appendmd5_max_url_file_name', '')
)
# Windows: max file path length is 260 characters including
# NULL (string end)
max_size = 260 - 1 - size_without_max_url_file_name
max_size_per_occurrence = max_size / number_occurrences
return max_size_per_occurrence | [
"def",
"get_max_url_file_name_length",
"(",
"savepath",
")",
":",
"number_occurrences",
"=",
"savepath",
".",
"count",
"(",
"'%max_url_file_name'",
")",
"number_occurrences",
"+=",
"savepath",
".",
"count",
"(",
"'%appendmd5_max_url_file_name'",
")",
"savepath_copy",
"=... | Determines the max length for any max... parts.
:param str savepath: absolute savepath to work on
:return: max. allowed number of chars for any of the max... parts | [
"Determines",
"the",
"max",
"length",
"for",
"any",
"max",
"...",
"parts",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/savepath_parser.py#L295-L316 |
226,305 | fhamborg/news-please | newsplease/pipeline/extractor/extractors/readability_extractor.py | ReadabilityExtractor.extract | def extract(self, item):
"""Creates an readability document and returns an ArticleCandidate containing article title and text.
:param item: A NewscrawlerItem to parse.
:return: ArticleCandidate containing the recovered article data.
"""
doc = Document(deepcopy(item['spider_response'].body))
description = doc.summary()
article_candidate = ArticleCandidate()
article_candidate.extractor = self._name
article_candidate.title = doc.short_title()
article_candidate.description = description
article_candidate.text = self._text(item)
article_candidate.topimage = self._topimage(item)
article_candidate.author = self._author(item)
article_candidate.publish_date = self._publish_date(item)
article_candidate.language = self._language(item)
return article_candidate | python | def extract(self, item):
"""Creates an readability document and returns an ArticleCandidate containing article title and text.
:param item: A NewscrawlerItem to parse.
:return: ArticleCandidate containing the recovered article data.
"""
doc = Document(deepcopy(item['spider_response'].body))
description = doc.summary()
article_candidate = ArticleCandidate()
article_candidate.extractor = self._name
article_candidate.title = doc.short_title()
article_candidate.description = description
article_candidate.text = self._text(item)
article_candidate.topimage = self._topimage(item)
article_candidate.author = self._author(item)
article_candidate.publish_date = self._publish_date(item)
article_candidate.language = self._language(item)
return article_candidate | [
"def",
"extract",
"(",
"self",
",",
"item",
")",
":",
"doc",
"=",
"Document",
"(",
"deepcopy",
"(",
"item",
"[",
"'spider_response'",
"]",
".",
"body",
")",
")",
"description",
"=",
"doc",
".",
"summary",
"(",
")",
"article_candidate",
"=",
"ArticleCandi... | Creates an readability document and returns an ArticleCandidate containing article title and text.
:param item: A NewscrawlerItem to parse.
:return: ArticleCandidate containing the recovered article data. | [
"Creates",
"an",
"readability",
"document",
"and",
"returns",
"an",
"ArticleCandidate",
"containing",
"article",
"title",
"and",
"text",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/extractors/readability_extractor.py#L18-L38 |
226,306 | fhamborg/news-please | newsplease/pipeline/extractor/article_extractor.py | Extractor.extract | def extract(self, item):
"""Runs the HTML-response trough a list of initialized extractors, a cleaner and compares the results.
:param item: NewscrawlerItem to be processed.
:return: An updated NewscrawlerItem including the results of the extraction
"""
article_candidates = []
for extractor in self.extractor_list:
article_candidates.append(extractor.extract(item))
article_candidates = self.cleaner.clean(article_candidates)
article = self.comparer.compare(item, article_candidates)
item['article_title'] = article.title
item['article_description'] = article.description
item['article_text'] = article.text
item['article_image'] = article.topimage
item['article_author'] = article.author
item['article_publish_date'] = article.publish_date
item['article_language'] = article.language
return item | python | def extract(self, item):
"""Runs the HTML-response trough a list of initialized extractors, a cleaner and compares the results.
:param item: NewscrawlerItem to be processed.
:return: An updated NewscrawlerItem including the results of the extraction
"""
article_candidates = []
for extractor in self.extractor_list:
article_candidates.append(extractor.extract(item))
article_candidates = self.cleaner.clean(article_candidates)
article = self.comparer.compare(item, article_candidates)
item['article_title'] = article.title
item['article_description'] = article.description
item['article_text'] = article.text
item['article_image'] = article.topimage
item['article_author'] = article.author
item['article_publish_date'] = article.publish_date
item['article_language'] = article.language
return item | [
"def",
"extract",
"(",
"self",
",",
"item",
")",
":",
"article_candidates",
"=",
"[",
"]",
"for",
"extractor",
"in",
"self",
".",
"extractor_list",
":",
"article_candidates",
".",
"append",
"(",
"extractor",
".",
"extract",
"(",
"item",
")",
")",
"article_... | Runs the HTML-response trough a list of initialized extractors, a cleaner and compares the results.
:param item: NewscrawlerItem to be processed.
:return: An updated NewscrawlerItem including the results of the extraction | [
"Runs",
"the",
"HTML",
"-",
"response",
"trough",
"a",
"list",
"of",
"initialized",
"extractors",
"a",
"cleaner",
"and",
"compares",
"the",
"results",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/article_extractor.py#L43-L66 |
226,307 | fhamborg/news-please | newsplease/helper_classes/parse_crawler.py | ParseCrawler.pass_to_pipeline_if_article | def pass_to_pipeline_if_article(
self,
response,
source_domain,
original_url,
rss_title=None
):
"""
Responsible for passing a NewscrawlerItem to the pipeline if the
response contains an article.
:param obj response: the scrapy response to work on
:param str source_domain: the response's domain as set for the crawler
:param str original_url: the url set in the json file
:param str rss_title: the title extracted by an rssCrawler
:return NewscrawlerItem: NewscrawlerItem to pass to the pipeline
"""
if self.helper.heuristics.is_article(response, original_url):
return self.pass_to_pipeline(
response, source_domain, rss_title=None) | python | def pass_to_pipeline_if_article(
self,
response,
source_domain,
original_url,
rss_title=None
):
"""
Responsible for passing a NewscrawlerItem to the pipeline if the
response contains an article.
:param obj response: the scrapy response to work on
:param str source_domain: the response's domain as set for the crawler
:param str original_url: the url set in the json file
:param str rss_title: the title extracted by an rssCrawler
:return NewscrawlerItem: NewscrawlerItem to pass to the pipeline
"""
if self.helper.heuristics.is_article(response, original_url):
return self.pass_to_pipeline(
response, source_domain, rss_title=None) | [
"def",
"pass_to_pipeline_if_article",
"(",
"self",
",",
"response",
",",
"source_domain",
",",
"original_url",
",",
"rss_title",
"=",
"None",
")",
":",
"if",
"self",
".",
"helper",
".",
"heuristics",
".",
"is_article",
"(",
"response",
",",
"original_url",
")"... | Responsible for passing a NewscrawlerItem to the pipeline if the
response contains an article.
:param obj response: the scrapy response to work on
:param str source_domain: the response's domain as set for the crawler
:param str original_url: the url set in the json file
:param str rss_title: the title extracted by an rssCrawler
:return NewscrawlerItem: NewscrawlerItem to pass to the pipeline | [
"Responsible",
"for",
"passing",
"a",
"NewscrawlerItem",
"to",
"the",
"pipeline",
"if",
"the",
"response",
"contains",
"an",
"article",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/parse_crawler.py#L27-L46 |
226,308 | fhamborg/news-please | newsplease/helper_classes/parse_crawler.py | ParseCrawler.recursive_requests | def recursive_requests(response, spider, ignore_regex='',
ignore_file_extensions='pdf'):
"""
Manages recursive requests.
Determines urls to recursivly crawl if they do not match certain file
extensions and do not match a certain regex set in the config file.
:param obj response: the response to extract any urls from
:param obj spider: the crawler the callback should be called on
:param str ignore_regex: a regex that should that any extracted url
shouldn't match
:param str ignore_file_extensions: a regex of file extensions that the
end of any url may not match
:return list: Scrapy Requests
"""
# Recursivly crawl all URLs on the current page
# that do not point to irrelevant file types
# or contain any of the given ignore_regex regexes
return [
scrapy.Request(response.urljoin(href), callback=spider.parse)
for href in response.css("a::attr('href')").extract() if re.match(
r'.*\.' + ignore_file_extensions +
r'$', response.urljoin(href), re.IGNORECASE
) is None
and len(re.match(ignore_regex, response.urljoin(href)).group(0)) == 0
] | python | def recursive_requests(response, spider, ignore_regex='',
ignore_file_extensions='pdf'):
"""
Manages recursive requests.
Determines urls to recursivly crawl if they do not match certain file
extensions and do not match a certain regex set in the config file.
:param obj response: the response to extract any urls from
:param obj spider: the crawler the callback should be called on
:param str ignore_regex: a regex that should that any extracted url
shouldn't match
:param str ignore_file_extensions: a regex of file extensions that the
end of any url may not match
:return list: Scrapy Requests
"""
# Recursivly crawl all URLs on the current page
# that do not point to irrelevant file types
# or contain any of the given ignore_regex regexes
return [
scrapy.Request(response.urljoin(href), callback=spider.parse)
for href in response.css("a::attr('href')").extract() if re.match(
r'.*\.' + ignore_file_extensions +
r'$', response.urljoin(href), re.IGNORECASE
) is None
and len(re.match(ignore_regex, response.urljoin(href)).group(0)) == 0
] | [
"def",
"recursive_requests",
"(",
"response",
",",
"spider",
",",
"ignore_regex",
"=",
"''",
",",
"ignore_file_extensions",
"=",
"'pdf'",
")",
":",
"# Recursivly crawl all URLs on the current page",
"# that do not point to irrelevant file types",
"# or contain any of the given ig... | Manages recursive requests.
Determines urls to recursivly crawl if they do not match certain file
extensions and do not match a certain regex set in the config file.
:param obj response: the response to extract any urls from
:param obj spider: the crawler the callback should be called on
:param str ignore_regex: a regex that should that any extracted url
shouldn't match
:param str ignore_file_extensions: a regex of file extensions that the
end of any url may not match
:return list: Scrapy Requests | [
"Manages",
"recursive",
"requests",
".",
"Determines",
"urls",
"to",
"recursivly",
"crawl",
"if",
"they",
"do",
"not",
"match",
"certain",
"file",
"extensions",
"and",
"do",
"not",
"match",
"a",
"certain",
"regex",
"set",
"in",
"the",
"config",
"file",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/parse_crawler.py#L87-L112 |
226,309 | fhamborg/news-please | newsplease/helper_classes/parse_crawler.py | ParseCrawler.content_type | def content_type(self, response):
"""
Ensures the response is of type
:param obj response: The scrapy response
:return bool: Determines wether the response is of the correct type
"""
if not re_html.match(response.headers.get('Content-Type').decode('utf-8')):
self.log.warn(
"Dropped: %s's content is not of type "
"text/html but %s", response.url, response.headers.get('Content-Type')
)
return False
else:
return True | python | def content_type(self, response):
"""
Ensures the response is of type
:param obj response: The scrapy response
:return bool: Determines wether the response is of the correct type
"""
if not re_html.match(response.headers.get('Content-Type').decode('utf-8')):
self.log.warn(
"Dropped: %s's content is not of type "
"text/html but %s", response.url, response.headers.get('Content-Type')
)
return False
else:
return True | [
"def",
"content_type",
"(",
"self",
",",
"response",
")",
":",
"if",
"not",
"re_html",
".",
"match",
"(",
"response",
".",
"headers",
".",
"get",
"(",
"'Content-Type'",
")",
".",
"decode",
"(",
"'utf-8'",
")",
")",
":",
"self",
".",
"log",
".",
"warn... | Ensures the response is of type
:param obj response: The scrapy response
:return bool: Determines wether the response is of the correct type | [
"Ensures",
"the",
"response",
"is",
"of",
"type"
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/parse_crawler.py#L114-L128 |
226,310 | fhamborg/news-please | newsplease/pipeline/extractor/comparer/comparer_topimage.py | ComparerTopimage.extract | def extract(self, item, list_article_candidate):
"""Compares the extracted top images.
:param item: The corresponding NewscrawlerItem
:param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted
:return: A string (url), the most likely top image
"""
list_topimage = []
for article_candidate in list_article_candidate:
if article_candidate.topimage is not None:
# Changes a relative path of an image to the absolute path of the given url.
article_candidate.topimage = self.image_absoulte_path(item['url'], article_candidate.topimage)
list_topimage.append((article_candidate.topimage, article_candidate.extractor))
# If there is no value in the list, return None.
if len(list_topimage) == 0:
return None
# If there are more options than one, return the result from newspaper.
list_newspaper = [x for x in list_topimage if x[1] == "newspaper"]
if len(list_newspaper) == 0:
# If there is no topimage extracted by newspaper, return the first result of list_topimage.
return list_topimage[0][0]
else:
return list_newspaper[0][0] | python | def extract(self, item, list_article_candidate):
"""Compares the extracted top images.
:param item: The corresponding NewscrawlerItem
:param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted
:return: A string (url), the most likely top image
"""
list_topimage = []
for article_candidate in list_article_candidate:
if article_candidate.topimage is not None:
# Changes a relative path of an image to the absolute path of the given url.
article_candidate.topimage = self.image_absoulte_path(item['url'], article_candidate.topimage)
list_topimage.append((article_candidate.topimage, article_candidate.extractor))
# If there is no value in the list, return None.
if len(list_topimage) == 0:
return None
# If there are more options than one, return the result from newspaper.
list_newspaper = [x for x in list_topimage if x[1] == "newspaper"]
if len(list_newspaper) == 0:
# If there is no topimage extracted by newspaper, return the first result of list_topimage.
return list_topimage[0][0]
else:
return list_newspaper[0][0] | [
"def",
"extract",
"(",
"self",
",",
"item",
",",
"list_article_candidate",
")",
":",
"list_topimage",
"=",
"[",
"]",
"for",
"article_candidate",
"in",
"list_article_candidate",
":",
"if",
"article_candidate",
".",
"topimage",
"is",
"not",
"None",
":",
"# Changes... | Compares the extracted top images.
:param item: The corresponding NewscrawlerItem
:param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted
:return: A string (url), the most likely top image | [
"Compares",
"the",
"extracted",
"top",
"images",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/comparer/comparer_topimage.py#L15-L41 |
226,311 | fhamborg/news-please | newsplease/pipeline/extractor/comparer/comparer_text.py | ComparerText.extract | def extract(self, item, article_candidate_list):
"""Compares the extracted texts.
:param item: The corresponding NewscrawlerItem
:param article_candidate_list: A list, the list of ArticleCandidate-Objects which have been extracted
:return: A string, the most likely text
"""
list_text = []
# The minimal number of words a text needs to have
min_number_words = 15
# The texts of the article candidates and the respective extractors are saved in a tuple in list_text.
for article_candidate in article_candidate_list:
if article_candidate.text != None:
list_text.append((article_candidate.text, article_candidate.extractor))
# Remove texts that are shorter than min_number_words.
for text_tuple in list_text:
if len(text_tuple[0].split()) < min_number_words:
list_text.remove(text_tuple)
# If there is no value in the list, return None.
if len(list_text) == 0:
return None
# If there is only one solution, return it.
if len(list_text) < 2:
return list_text[0][0]
else:
# If there is more than one solution, do the following:
# Create a list which holds triple of the score and the two extractors
list_score = []
# Compare every text with all other texts at least once
for a, b, in itertools.combinations(list_text, 2):
# Create sets from the texts
set_a = set(a[0].split())
set_b = set(b[0].split())
symmetric_difference_a_b = set_a ^ set_b
intersection_a_b = set_a & set_b
# Replace 0 with -1 in order to elude division by zero
if intersection_a_b == 0:
intersection_a_b = -1
# Create the score. It divides the number of words which are not in both texts by the number of words which
# are in both texts and subtracts the result from 1. The closer to 1 the more similiar they are.
score = 1 - ((len(symmetric_difference_a_b)) / (2 * len(intersection_a_b)))
list_score.append((score, a[1], b[1]))
# Find out which is the highest score
best_score = max(list_score, key=lambda item: item[0])
# If one of the solutions is newspaper return it
if "newspaper" in best_score:
return (list(filter(lambda x: x[1] == "newspaper", list_text))[0][0])
else:
# If not, return the text that is longer
# A list that holds the extracted texts and their extractors which were most similar
top_candidates = []
for tuple in list_text:
if tuple[1] == best_score[1] or tuple[1] == best_score[2]:
top_candidates.append(tuple)
if len(top_candidates[0][0]) > len(top_candidates[1][0]):
return (top_candidates[0][0])
else:
return (top_candidates[1][0]) | python | def extract(self, item, article_candidate_list):
"""Compares the extracted texts.
:param item: The corresponding NewscrawlerItem
:param article_candidate_list: A list, the list of ArticleCandidate-Objects which have been extracted
:return: A string, the most likely text
"""
list_text = []
# The minimal number of words a text needs to have
min_number_words = 15
# The texts of the article candidates and the respective extractors are saved in a tuple in list_text.
for article_candidate in article_candidate_list:
if article_candidate.text != None:
list_text.append((article_candidate.text, article_candidate.extractor))
# Remove texts that are shorter than min_number_words.
for text_tuple in list_text:
if len(text_tuple[0].split()) < min_number_words:
list_text.remove(text_tuple)
# If there is no value in the list, return None.
if len(list_text) == 0:
return None
# If there is only one solution, return it.
if len(list_text) < 2:
return list_text[0][0]
else:
# If there is more than one solution, do the following:
# Create a list which holds triple of the score and the two extractors
list_score = []
# Compare every text with all other texts at least once
for a, b, in itertools.combinations(list_text, 2):
# Create sets from the texts
set_a = set(a[0].split())
set_b = set(b[0].split())
symmetric_difference_a_b = set_a ^ set_b
intersection_a_b = set_a & set_b
# Replace 0 with -1 in order to elude division by zero
if intersection_a_b == 0:
intersection_a_b = -1
# Create the score. It divides the number of words which are not in both texts by the number of words which
# are in both texts and subtracts the result from 1. The closer to 1 the more similiar they are.
score = 1 - ((len(symmetric_difference_a_b)) / (2 * len(intersection_a_b)))
list_score.append((score, a[1], b[1]))
# Find out which is the highest score
best_score = max(list_score, key=lambda item: item[0])
# If one of the solutions is newspaper return it
if "newspaper" in best_score:
return (list(filter(lambda x: x[1] == "newspaper", list_text))[0][0])
else:
# If not, return the text that is longer
# A list that holds the extracted texts and their extractors which were most similar
top_candidates = []
for tuple in list_text:
if tuple[1] == best_score[1] or tuple[1] == best_score[2]:
top_candidates.append(tuple)
if len(top_candidates[0][0]) > len(top_candidates[1][0]):
return (top_candidates[0][0])
else:
return (top_candidates[1][0]) | [
"def",
"extract",
"(",
"self",
",",
"item",
",",
"article_candidate_list",
")",
":",
"list_text",
"=",
"[",
"]",
"# The minimal number of words a text needs to have",
"min_number_words",
"=",
"15",
"# The texts of the article candidates and the respective extractors are saved in ... | Compares the extracted texts.
:param item: The corresponding NewscrawlerItem
:param article_candidate_list: A list, the list of ArticleCandidate-Objects which have been extracted
:return: A string, the most likely text | [
"Compares",
"the",
"extracted",
"texts",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/comparer/comparer_text.py#L7-L79 |
226,312 | fhamborg/news-please | newsplease/helper_classes/sub_classes/heuristics_manager.py | HeuristicsManager.is_article | def is_article(self, response, url):
"""
Tests if the given response is an article by calling and checking
the heuristics set in config.cfg and sitelist.json
:param obj response: The response of the site.
:param str url: The base_url (needed to get the site-specific config
from the JSON-file)
:return bool: true if the heuristics match the site as an article
"""
site = self.__sites_object[url]
heuristics = self.__get_enabled_heuristics(url)
self.log.info("Checking site: %s", response.url)
statement = self.__get_condition(url)
self.log.debug("Condition (original): %s", statement)
for heuristic, condition in heuristics.items():
heuristic_func = getattr(self, heuristic)
result = heuristic_func(response, site)
check = self.__evaluate_result(result, condition)
statement = re.sub(r"\b%s\b" % heuristic, str(check), statement)
self.log.debug("Checking heuristic (%s)"
" result (%s) on condition (%s): %s",
heuristic, result, condition, check)
self.log.debug("Condition (evaluated): %s", statement)
is_article = eval(statement)
self.log.debug("Article accepted: %s", is_article)
return is_article | python | def is_article(self, response, url):
"""
Tests if the given response is an article by calling and checking
the heuristics set in config.cfg and sitelist.json
:param obj response: The response of the site.
:param str url: The base_url (needed to get the site-specific config
from the JSON-file)
:return bool: true if the heuristics match the site as an article
"""
site = self.__sites_object[url]
heuristics = self.__get_enabled_heuristics(url)
self.log.info("Checking site: %s", response.url)
statement = self.__get_condition(url)
self.log.debug("Condition (original): %s", statement)
for heuristic, condition in heuristics.items():
heuristic_func = getattr(self, heuristic)
result = heuristic_func(response, site)
check = self.__evaluate_result(result, condition)
statement = re.sub(r"\b%s\b" % heuristic, str(check), statement)
self.log.debug("Checking heuristic (%s)"
" result (%s) on condition (%s): %s",
heuristic, result, condition, check)
self.log.debug("Condition (evaluated): %s", statement)
is_article = eval(statement)
self.log.debug("Article accepted: %s", is_article)
return is_article | [
"def",
"is_article",
"(",
"self",
",",
"response",
",",
"url",
")",
":",
"site",
"=",
"self",
".",
"__sites_object",
"[",
"url",
"]",
"heuristics",
"=",
"self",
".",
"__get_enabled_heuristics",
"(",
"url",
")",
"self",
".",
"log",
".",
"info",
"(",
"\"... | Tests if the given response is an article by calling and checking
the heuristics set in config.cfg and sitelist.json
:param obj response: The response of the site.
:param str url: The base_url (needed to get the site-specific config
from the JSON-file)
:return bool: true if the heuristics match the site as an article | [
"Tests",
"if",
"the",
"given",
"response",
"is",
"an",
"article",
"by",
"calling",
"and",
"checking",
"the",
"heuristics",
"set",
"in",
"config",
".",
"cfg",
"and",
"sitelist",
".",
"json"
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/sub_classes/heuristics_manager.py#L36-L67 |
226,313 | fhamborg/news-please | newsplease/helper_classes/sub_classes/heuristics_manager.py | HeuristicsManager.__get_condition | def __get_condition(self, url):
"""
Gets the condition for a url and validates it.
:param str url: The url to get the condition for
"""
if self.__heuristics_condition is not None:
return self.__heuristics_condition
if "pass_heuristics_condition" in self.__sites_object[url]:
condition = \
self.__sites_object[url]["pass_heuristics_condition"]
else:
condition = \
self.cfg_heuristics["pass_heuristics_condition"]
# Because the condition will be eval-ed (Yeah, eval is evil, BUT only
# when not filtered properly), we are filtering it here.
# Anyway, if that filter-method is not perfect: This is not any
# random user-input thats evaled. This is (hopefully still when you
# read this) not a webtool, where you need to filter everything 100%
# properly.
disalloweds = condition
heuristics = self.__get_enabled_heuristics(url)
for allowed in self.__condition_allowed:
disalloweds = disalloweds.replace(allowed, " ")
for heuristic, _ in heuristics.items():
disalloweds = re.sub(r"\b%s\b" % heuristic, " ", disalloweds)
disalloweds = disalloweds.split(" ")
for disallowed in disalloweds:
if disallowed != "":
self.log.error("Misconfiguration: In the condition,"
" an unknown heuristic was found and"
" will be ignored: %s", disallowed)
condition = re.sub(r"\b%s\b" % disallowed, "True", condition)
self.__heuristics_condition = condition
# Now condition should just consits of not, and, or, (, ), and all
# enabled heuristics.
return condition | python | def __get_condition(self, url):
"""
Gets the condition for a url and validates it.
:param str url: The url to get the condition for
"""
if self.__heuristics_condition is not None:
return self.__heuristics_condition
if "pass_heuristics_condition" in self.__sites_object[url]:
condition = \
self.__sites_object[url]["pass_heuristics_condition"]
else:
condition = \
self.cfg_heuristics["pass_heuristics_condition"]
# Because the condition will be eval-ed (Yeah, eval is evil, BUT only
# when not filtered properly), we are filtering it here.
# Anyway, if that filter-method is not perfect: This is not any
# random user-input thats evaled. This is (hopefully still when you
# read this) not a webtool, where you need to filter everything 100%
# properly.
disalloweds = condition
heuristics = self.__get_enabled_heuristics(url)
for allowed in self.__condition_allowed:
disalloweds = disalloweds.replace(allowed, " ")
for heuristic, _ in heuristics.items():
disalloweds = re.sub(r"\b%s\b" % heuristic, " ", disalloweds)
disalloweds = disalloweds.split(" ")
for disallowed in disalloweds:
if disallowed != "":
self.log.error("Misconfiguration: In the condition,"
" an unknown heuristic was found and"
" will be ignored: %s", disallowed)
condition = re.sub(r"\b%s\b" % disallowed, "True", condition)
self.__heuristics_condition = condition
# Now condition should just consits of not, and, or, (, ), and all
# enabled heuristics.
return condition | [
"def",
"__get_condition",
"(",
"self",
",",
"url",
")",
":",
"if",
"self",
".",
"__heuristics_condition",
"is",
"not",
"None",
":",
"return",
"self",
".",
"__heuristics_condition",
"if",
"\"pass_heuristics_condition\"",
"in",
"self",
".",
"__sites_object",
"[",
... | Gets the condition for a url and validates it.
:param str url: The url to get the condition for | [
"Gets",
"the",
"condition",
"for",
"a",
"url",
"and",
"validates",
"it",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/sub_classes/heuristics_manager.py#L69-L110 |
226,314 | fhamborg/news-please | newsplease/helper_classes/sub_classes/heuristics_manager.py | HeuristicsManager.__evaluate_result | def __evaluate_result(self, result, condition):
"""
Evaluates a result of a heuristic
with the condition given in the config.
:param mixed result: The result of the heuristic
:param mixed condition: The condition string to evaluate on the result
:return bool: Whether the heuristic result matches the condition
"""
# If result is bool this means, that the heuristic
# is bool as well or has a special situation
# (for example some condition [e.g. in config] is [not] met, thus
# just pass it)
if isinstance(result, bool):
return result
# Check if the condition is a String condition,
# allowing <=, >=, <, >, = conditions or string
# when they start with " or '
if isinstance(condition, basestring):
# Check if result should match a string
if (condition.startswith("'") and condition.endswith("'")) or \
(condition.startswith('"') and condition.endswith('"')):
if isinstance(result, basestring):
self.log.debug("Condition %s recognized as string.",
condition)
return result == condition[1:-1]
return self.__evaluation_error(
result, condition, "Result not string")
# Only number-comparision following
if not isinstance(result, (float, int)):
return self.__evaluation_error(
result, condition, "Result not number on comparision")
# Check if result should match a number
if condition.startswith("="):
number = self.__try_parse_number(condition[1:])
if isinstance(number, bool):
return self.__evaluation_error(
result, condition, "Number not parsable (=)")
return result == number
# Check if result should be >= then a number
if condition.startswith(">="):
number = self.__try_parse_number(condition[2:])
if isinstance(number, bool):
return self.__evaluation_error(
result, condition, "Number not parsable (>=)")
return result >= number
# Check if result should be <= then a number
if condition.startswith("<="):
number = self.__try_parse_number(condition[2:])
if isinstance(number, bool):
return self.__evaluation_error(
result, condition, "Number not parsable (<=)")
return result <= number
# Check if result should be > then a number
if condition.startswith(">"):
number = self.__try_parse_number(condition[1:])
if isinstance(number, bool):
return self.__evaluation_error(
result, condition, "Number not parsable (>)")
return result > number
# Check if result should be < then a number
if condition.startswith("<"):
number = self.__try_parse_number(condition[1:])
if isinstance(number, bool):
return self.__evaluation_error(
result, condition, "Number not parsable (<)")
return result < number
# Check if result should be equal a number
number = self.__try_parse_number(condition)
if isinstance(number, bool):
return self.__evaluation_error(
result, condition, "Number not parsable")
return result == number
# Check if the condition is a number and matches the result
if isinstance(condition, (float, int)) and isinstance(result, (float, int)):
return condition == result
return self.__evaluation_error(result, condition, "Unknown") | python | def __evaluate_result(self, result, condition):
"""
Evaluates a result of a heuristic
with the condition given in the config.
:param mixed result: The result of the heuristic
:param mixed condition: The condition string to evaluate on the result
:return bool: Whether the heuristic result matches the condition
"""
# If result is bool this means, that the heuristic
# is bool as well or has a special situation
# (for example some condition [e.g. in config] is [not] met, thus
# just pass it)
if isinstance(result, bool):
return result
# Check if the condition is a String condition,
# allowing <=, >=, <, >, = conditions or string
# when they start with " or '
if isinstance(condition, basestring):
# Check if result should match a string
if (condition.startswith("'") and condition.endswith("'")) or \
(condition.startswith('"') and condition.endswith('"')):
if isinstance(result, basestring):
self.log.debug("Condition %s recognized as string.",
condition)
return result == condition[1:-1]
return self.__evaluation_error(
result, condition, "Result not string")
# Only number-comparision following
if not isinstance(result, (float, int)):
return self.__evaluation_error(
result, condition, "Result not number on comparision")
# Check if result should match a number
if condition.startswith("="):
number = self.__try_parse_number(condition[1:])
if isinstance(number, bool):
return self.__evaluation_error(
result, condition, "Number not parsable (=)")
return result == number
# Check if result should be >= then a number
if condition.startswith(">="):
number = self.__try_parse_number(condition[2:])
if isinstance(number, bool):
return self.__evaluation_error(
result, condition, "Number not parsable (>=)")
return result >= number
# Check if result should be <= then a number
if condition.startswith("<="):
number = self.__try_parse_number(condition[2:])
if isinstance(number, bool):
return self.__evaluation_error(
result, condition, "Number not parsable (<=)")
return result <= number
# Check if result should be > then a number
if condition.startswith(">"):
number = self.__try_parse_number(condition[1:])
if isinstance(number, bool):
return self.__evaluation_error(
result, condition, "Number not parsable (>)")
return result > number
# Check if result should be < then a number
if condition.startswith("<"):
number = self.__try_parse_number(condition[1:])
if isinstance(number, bool):
return self.__evaluation_error(
result, condition, "Number not parsable (<)")
return result < number
# Check if result should be equal a number
number = self.__try_parse_number(condition)
if isinstance(number, bool):
return self.__evaluation_error(
result, condition, "Number not parsable")
return result == number
# Check if the condition is a number and matches the result
if isinstance(condition, (float, int)) and isinstance(result, (float, int)):
return condition == result
return self.__evaluation_error(result, condition, "Unknown") | [
"def",
"__evaluate_result",
"(",
"self",
",",
"result",
",",
"condition",
")",
":",
"# If result is bool this means, that the heuristic",
"# is bool as well or has a special situation",
"# (for example some condition [e.g. in config] is [not] met, thus",
"# just pass it)",
"if",
"isin... | Evaluates a result of a heuristic
with the condition given in the config.
:param mixed result: The result of the heuristic
:param mixed condition: The condition string to evaluate on the result
:return bool: Whether the heuristic result matches the condition | [
"Evaluates",
"a",
"result",
"of",
"a",
"heuristic",
"with",
"the",
"condition",
"given",
"in",
"the",
"config",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/sub_classes/heuristics_manager.py#L112-L200 |
226,315 | fhamborg/news-please | newsplease/helper_classes/sub_classes/heuristics_manager.py | HeuristicsManager.__evaluation_error | def __evaluation_error(self, result, condition, throw):
"""Helper-method for easy error-logging"""
self.log.error("Result does not match condition, dropping item. "
"Result %s; Condition: %s; Throw: %s",
result, condition, throw)
return False | python | def __evaluation_error(self, result, condition, throw):
"""Helper-method for easy error-logging"""
self.log.error("Result does not match condition, dropping item. "
"Result %s; Condition: %s; Throw: %s",
result, condition, throw)
return False | [
"def",
"__evaluation_error",
"(",
"self",
",",
"result",
",",
"condition",
",",
"throw",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"\"Result does not match condition, dropping item. \"",
"\"Result %s; Condition: %s; Throw: %s\"",
",",
"result",
",",
"condition",
... | Helper-method for easy error-logging | [
"Helper",
"-",
"method",
"for",
"easy",
"error",
"-",
"logging"
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/sub_classes/heuristics_manager.py#L202-L207 |
226,316 | fhamborg/news-please | newsplease/helper_classes/sub_classes/heuristics_manager.py | HeuristicsManager.__try_parse_number | def __try_parse_number(self, string):
"""Try to parse a string to a number, else return False."""
try:
return int(string)
except ValueError:
try:
return float(string)
except ValueError:
return False | python | def __try_parse_number(self, string):
"""Try to parse a string to a number, else return False."""
try:
return int(string)
except ValueError:
try:
return float(string)
except ValueError:
return False | [
"def",
"__try_parse_number",
"(",
"self",
",",
"string",
")",
":",
"try",
":",
"return",
"int",
"(",
"string",
")",
"except",
"ValueError",
":",
"try",
":",
"return",
"float",
"(",
"string",
")",
"except",
"ValueError",
":",
"return",
"False"
] | Try to parse a string to a number, else return False. | [
"Try",
"to",
"parse",
"a",
"string",
"to",
"a",
"number",
"else",
"return",
"False",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/sub_classes/heuristics_manager.py#L209-L217 |
226,317 | fhamborg/news-please | newsplease/helper_classes/sub_classes/heuristics_manager.py | HeuristicsManager.__get_enabled_heuristics | def __get_enabled_heuristics(self, url):
"""
Get the enabled heuristics for a site, merging the default and the
overwrite together.
The config will only be read once and the merged site-config will be
cached.
:param str url: The url to get the heuristics for.
"""
if url in self.__sites_heuristics:
return self.__sites_heuristics[url]
site = self.__sites_object[url]
heuristics = dict(self.cfg_heuristics["enabled_heuristics"])
if "overwrite_heuristics" in site:
for heuristic, value in site["overwrite_heuristics"].items():
if value is False and heuristic in heuristics:
del heuristics[heuristic]
else:
heuristics[heuristic] = value
self.__sites_heuristics[site["url"]] = heuristics
self.log.debug(
"Enabled heuristics for %s: %s", site["url"], heuristics
)
return heuristics | python | def __get_enabled_heuristics(self, url):
"""
Get the enabled heuristics for a site, merging the default and the
overwrite together.
The config will only be read once and the merged site-config will be
cached.
:param str url: The url to get the heuristics for.
"""
if url in self.__sites_heuristics:
return self.__sites_heuristics[url]
site = self.__sites_object[url]
heuristics = dict(self.cfg_heuristics["enabled_heuristics"])
if "overwrite_heuristics" in site:
for heuristic, value in site["overwrite_heuristics"].items():
if value is False and heuristic in heuristics:
del heuristics[heuristic]
else:
heuristics[heuristic] = value
self.__sites_heuristics[site["url"]] = heuristics
self.log.debug(
"Enabled heuristics for %s: %s", site["url"], heuristics
)
return heuristics | [
"def",
"__get_enabled_heuristics",
"(",
"self",
",",
"url",
")",
":",
"if",
"url",
"in",
"self",
".",
"__sites_heuristics",
":",
"return",
"self",
".",
"__sites_heuristics",
"[",
"url",
"]",
"site",
"=",
"self",
".",
"__sites_object",
"[",
"url",
"]",
"heu... | Get the enabled heuristics for a site, merging the default and the
overwrite together.
The config will only be read once and the merged site-config will be
cached.
:param str url: The url to get the heuristics for. | [
"Get",
"the",
"enabled",
"heuristics",
"for",
"a",
"site",
"merging",
"the",
"default",
"and",
"the",
"overwrite",
"together",
".",
"The",
"config",
"will",
"only",
"be",
"read",
"once",
"and",
"the",
"merged",
"site",
"-",
"config",
"will",
"be",
"cached"... | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/sub_classes/heuristics_manager.py#L219-L245 |
226,318 | fhamborg/news-please | newsplease/pipeline/extractor/extractors/abstract_extractor.py | AbstractExtractor.extract | def extract(self, item):
"""Executes all implemented functions on the given article and returns an
object containing the recovered data.
:param item: A NewscrawlerItem to parse.
:return: ArticleCandidate containing the recovered article data.
"""
article_candidate = ArticleCandidate()
article_candidate.extractor = self._name()
article_candidate.title = self._title(item)
article_candidate.description = self._description(item)
article_candidate.text = self._text(item)
article_candidate.topimage = self._topimage(item)
article_candidate.author = self._author(item)
article_candidate.publish_date = self._publish_date(item)
article_candidate.language = self._language(item)
return article_candidate | python | def extract(self, item):
"""Executes all implemented functions on the given article and returns an
object containing the recovered data.
:param item: A NewscrawlerItem to parse.
:return: ArticleCandidate containing the recovered article data.
"""
article_candidate = ArticleCandidate()
article_candidate.extractor = self._name()
article_candidate.title = self._title(item)
article_candidate.description = self._description(item)
article_candidate.text = self._text(item)
article_candidate.topimage = self._topimage(item)
article_candidate.author = self._author(item)
article_candidate.publish_date = self._publish_date(item)
article_candidate.language = self._language(item)
return article_candidate | [
"def",
"extract",
"(",
"self",
",",
"item",
")",
":",
"article_candidate",
"=",
"ArticleCandidate",
"(",
")",
"article_candidate",
".",
"extractor",
"=",
"self",
".",
"_name",
"(",
")",
"article_candidate",
".",
"title",
"=",
"self",
".",
"_title",
"(",
"i... | Executes all implemented functions on the given article and returns an
object containing the recovered data.
:param item: A NewscrawlerItem to parse.
:return: ArticleCandidate containing the recovered article data. | [
"Executes",
"all",
"implemented",
"functions",
"on",
"the",
"given",
"article",
"and",
"returns",
"an",
"object",
"containing",
"the",
"recovered",
"data",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/extractors/abstract_extractor.py#L48-L66 |
226,319 | fhamborg/news-please | newsplease/pipeline/extractor/extractors/newspaper_extractor.py | NewspaperExtractor.extract | def extract(self, item):
"""Creates an instance of Article without a Download and returns an ArticleCandidate with the results of
parsing the HTML-Code.
:param item: A NewscrawlerItem to parse.
:return: ArticleCandidate containing the recovered article data.
"""
article_candidate = ArticleCandidate()
article_candidate.extractor = self._name()
article = Article('')
article.set_html(item['spider_response'].body)
article.parse()
article_candidate.title = article.title
article_candidate.description = article.meta_description
article_candidate.text = article.text
article_candidate.topimage = article.top_image
article_candidate.author = article.authors
if article.publish_date is not None:
try:
article_candidate.publish_date = article.publish_date.strftime('%Y-%m-%d %H:%M:%S')
except ValueError as exception:
self.log.debug('%s: Newspaper failed to extract the date in the supported format,'
'Publishing date set to None' % item['url'])
article_candidate.language = article.meta_lang
return article_candidate | python | def extract(self, item):
"""Creates an instance of Article without a Download and returns an ArticleCandidate with the results of
parsing the HTML-Code.
:param item: A NewscrawlerItem to parse.
:return: ArticleCandidate containing the recovered article data.
"""
article_candidate = ArticleCandidate()
article_candidate.extractor = self._name()
article = Article('')
article.set_html(item['spider_response'].body)
article.parse()
article_candidate.title = article.title
article_candidate.description = article.meta_description
article_candidate.text = article.text
article_candidate.topimage = article.top_image
article_candidate.author = article.authors
if article.publish_date is not None:
try:
article_candidate.publish_date = article.publish_date.strftime('%Y-%m-%d %H:%M:%S')
except ValueError as exception:
self.log.debug('%s: Newspaper failed to extract the date in the supported format,'
'Publishing date set to None' % item['url'])
article_candidate.language = article.meta_lang
return article_candidate | [
"def",
"extract",
"(",
"self",
",",
"item",
")",
":",
"article_candidate",
"=",
"ArticleCandidate",
"(",
")",
"article_candidate",
".",
"extractor",
"=",
"self",
".",
"_name",
"(",
")",
"article",
"=",
"Article",
"(",
"''",
")",
"article",
".",
"set_html",... | Creates an instance of Article without a Download and returns an ArticleCandidate with the results of
parsing the HTML-Code.
:param item: A NewscrawlerItem to parse.
:return: ArticleCandidate containing the recovered article data. | [
"Creates",
"an",
"instance",
"of",
"Article",
"without",
"a",
"Download",
"and",
"returns",
"an",
"ArticleCandidate",
"with",
"the",
"results",
"of",
"parsing",
"the",
"HTML",
"-",
"Code",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/extractors/newspaper_extractor.py#L18-L44 |
226,320 | fhamborg/news-please | newsplease/pipeline/extractor/comparer/comparer_author.py | ComparerAuthor.extract | def extract(self, item, list_article_candidate):
"""Compares the extracted authors.
:param item: The corresponding NewscrawlerItem
:param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted
:return: A string, the most likely authors
"""
list_author = []
# The authors of the ArticleCandidates and the respective extractors are saved in a tuple in list_author.
for article_candidate in list_article_candidate:
if (article_candidate.author is not None) and (article_candidate.author != '[]'):
list_author.append((article_candidate.author, article_candidate.extractor))
# If there is no value in the list, return None.
if len(list_author) == 0:
return None
# If there are more options than one, return the result from newspaper.
list_newspaper = [x for x in list_author if x[1] == "newspaper"]
if len(list_newspaper) == 0:
# If there is no author extracted by newspaper, return the first result of list_author.
return list_author[0][0]
else:
return list_newspaper[0][0] | python | def extract(self, item, list_article_candidate):
"""Compares the extracted authors.
:param item: The corresponding NewscrawlerItem
:param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted
:return: A string, the most likely authors
"""
list_author = []
# The authors of the ArticleCandidates and the respective extractors are saved in a tuple in list_author.
for article_candidate in list_article_candidate:
if (article_candidate.author is not None) and (article_candidate.author != '[]'):
list_author.append((article_candidate.author, article_candidate.extractor))
# If there is no value in the list, return None.
if len(list_author) == 0:
return None
# If there are more options than one, return the result from newspaper.
list_newspaper = [x for x in list_author if x[1] == "newspaper"]
if len(list_newspaper) == 0:
# If there is no author extracted by newspaper, return the first result of list_author.
return list_author[0][0]
else:
return list_newspaper[0][0] | [
"def",
"extract",
"(",
"self",
",",
"item",
",",
"list_article_candidate",
")",
":",
"list_author",
"=",
"[",
"]",
"# The authors of the ArticleCandidates and the respective extractors are saved in a tuple in list_author.",
"for",
"article_candidate",
"in",
"list_article_candidat... | Compares the extracted authors.
:param item: The corresponding NewscrawlerItem
:param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted
:return: A string, the most likely authors | [
"Compares",
"the",
"extracted",
"authors",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/comparer/comparer_author.py#L4-L29 |
226,321 | GNS3/gns3-server | gns3server/utils/asyncio/serial.py | _asyncio_open_serial_windows | def _asyncio_open_serial_windows(path):
"""
Open a windows named pipe
:returns: An IO like object
"""
try:
yield from wait_for_named_pipe_creation(path)
except asyncio.TimeoutError:
raise NodeError('Pipe file "{}" is missing'.format(path))
return WindowsPipe(path) | python | def _asyncio_open_serial_windows(path):
"""
Open a windows named pipe
:returns: An IO like object
"""
try:
yield from wait_for_named_pipe_creation(path)
except asyncio.TimeoutError:
raise NodeError('Pipe file "{}" is missing'.format(path))
return WindowsPipe(path) | [
"def",
"_asyncio_open_serial_windows",
"(",
"path",
")",
":",
"try",
":",
"yield",
"from",
"wait_for_named_pipe_creation",
"(",
"path",
")",
"except",
"asyncio",
".",
"TimeoutError",
":",
"raise",
"NodeError",
"(",
"'Pipe file \"{}\" is missing'",
".",
"format",
"("... | Open a windows named pipe
:returns: An IO like object | [
"Open",
"a",
"windows",
"named",
"pipe"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/serial.py#L99-L110 |
226,322 | GNS3/gns3-server | gns3server/utils/asyncio/serial.py | _asyncio_open_serial_unix | def _asyncio_open_serial_unix(path):
"""
Open a unix socket or a windows named pipe
:returns: An IO like object
"""
try:
# wait for VM to create the pipe file.
yield from wait_for_file_creation(path)
except asyncio.TimeoutError:
raise NodeError('Pipe file "{}" is missing'.format(path))
output = SerialReaderWriterProtocol()
try:
yield from asyncio.get_event_loop().create_unix_connection(lambda: output, path)
except ConnectionRefusedError:
raise NodeError('Can\'t open pipe file "{}"'.format(path))
return output | python | def _asyncio_open_serial_unix(path):
"""
Open a unix socket or a windows named pipe
:returns: An IO like object
"""
try:
# wait for VM to create the pipe file.
yield from wait_for_file_creation(path)
except asyncio.TimeoutError:
raise NodeError('Pipe file "{}" is missing'.format(path))
output = SerialReaderWriterProtocol()
try:
yield from asyncio.get_event_loop().create_unix_connection(lambda: output, path)
except ConnectionRefusedError:
raise NodeError('Can\'t open pipe file "{}"'.format(path))
return output | [
"def",
"_asyncio_open_serial_unix",
"(",
"path",
")",
":",
"try",
":",
"# wait for VM to create the pipe file.",
"yield",
"from",
"wait_for_file_creation",
"(",
"path",
")",
"except",
"asyncio",
".",
"TimeoutError",
":",
"raise",
"NodeError",
"(",
"'Pipe file \"{}\" is ... | Open a unix socket or a windows named pipe
:returns: An IO like object | [
"Open",
"a",
"unix",
"socket",
"or",
"a",
"windows",
"named",
"pipe"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/serial.py#L114-L132 |
226,323 | GNS3/gns3-server | gns3server/controller/udp_link.py | UDPLink.create | def create(self):
"""
Create the link on the nodes
"""
node1 = self._nodes[0]["node"]
adapter_number1 = self._nodes[0]["adapter_number"]
port_number1 = self._nodes[0]["port_number"]
node2 = self._nodes[1]["node"]
adapter_number2 = self._nodes[1]["adapter_number"]
port_number2 = self._nodes[1]["port_number"]
# Get an IP allowing communication between both host
try:
(node1_host, node2_host) = yield from node1.compute.get_ip_on_same_subnet(node2.compute)
except ValueError as e:
raise aiohttp.web.HTTPConflict(text=str(e))
# Reserve a UDP port on both side
response = yield from node1.compute.post("/projects/{}/ports/udp".format(self._project.id))
self._node1_port = response.json["udp_port"]
response = yield from node2.compute.post("/projects/{}/ports/udp".format(self._project.id))
self._node2_port = response.json["udp_port"]
node1_filters = {}
node2_filters = {}
filter_node = self._get_filter_node()
if filter_node == node1:
node1_filters = self.get_active_filters()
elif filter_node == node2:
node2_filters = self.get_active_filters()
# Create the tunnel on both side
self._link_data.append({
"lport": self._node1_port,
"rhost": node2_host,
"rport": self._node2_port,
"type": "nio_udp",
"filters": node1_filters
})
yield from node1.post("/adapters/{adapter_number}/ports/{port_number}/nio".format(adapter_number=adapter_number1, port_number=port_number1), data=self._link_data[0], timeout=120)
self._link_data.append({
"lport": self._node2_port,
"rhost": node1_host,
"rport": self._node1_port,
"type": "nio_udp",
"filters": node2_filters
})
try:
yield from node2.post("/adapters/{adapter_number}/ports/{port_number}/nio".format(adapter_number=adapter_number2, port_number=port_number2), data=self._link_data[1], timeout=120)
except Exception as e:
# We clean the first NIO
yield from node1.delete("/adapters/{adapter_number}/ports/{port_number}/nio".format(adapter_number=adapter_number1, port_number=port_number1), timeout=120)
raise e
self._created = True | python | def create(self):
"""
Create the link on the nodes
"""
node1 = self._nodes[0]["node"]
adapter_number1 = self._nodes[0]["adapter_number"]
port_number1 = self._nodes[0]["port_number"]
node2 = self._nodes[1]["node"]
adapter_number2 = self._nodes[1]["adapter_number"]
port_number2 = self._nodes[1]["port_number"]
# Get an IP allowing communication between both host
try:
(node1_host, node2_host) = yield from node1.compute.get_ip_on_same_subnet(node2.compute)
except ValueError as e:
raise aiohttp.web.HTTPConflict(text=str(e))
# Reserve a UDP port on both side
response = yield from node1.compute.post("/projects/{}/ports/udp".format(self._project.id))
self._node1_port = response.json["udp_port"]
response = yield from node2.compute.post("/projects/{}/ports/udp".format(self._project.id))
self._node2_port = response.json["udp_port"]
node1_filters = {}
node2_filters = {}
filter_node = self._get_filter_node()
if filter_node == node1:
node1_filters = self.get_active_filters()
elif filter_node == node2:
node2_filters = self.get_active_filters()
# Create the tunnel on both side
self._link_data.append({
"lport": self._node1_port,
"rhost": node2_host,
"rport": self._node2_port,
"type": "nio_udp",
"filters": node1_filters
})
yield from node1.post("/adapters/{adapter_number}/ports/{port_number}/nio".format(adapter_number=adapter_number1, port_number=port_number1), data=self._link_data[0], timeout=120)
self._link_data.append({
"lport": self._node2_port,
"rhost": node1_host,
"rport": self._node1_port,
"type": "nio_udp",
"filters": node2_filters
})
try:
yield from node2.post("/adapters/{adapter_number}/ports/{port_number}/nio".format(adapter_number=adapter_number2, port_number=port_number2), data=self._link_data[1], timeout=120)
except Exception as e:
# We clean the first NIO
yield from node1.delete("/adapters/{adapter_number}/ports/{port_number}/nio".format(adapter_number=adapter_number1, port_number=port_number1), timeout=120)
raise e
self._created = True | [
"def",
"create",
"(",
"self",
")",
":",
"node1",
"=",
"self",
".",
"_nodes",
"[",
"0",
"]",
"[",
"\"node\"",
"]",
"adapter_number1",
"=",
"self",
".",
"_nodes",
"[",
"0",
"]",
"[",
"\"adapter_number\"",
"]",
"port_number1",
"=",
"self",
".",
"_nodes",
... | Create the link on the nodes | [
"Create",
"the",
"link",
"on",
"the",
"nodes"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/udp_link.py#L41-L96 |
226,324 | GNS3/gns3-server | gns3server/controller/udp_link.py | UDPLink.delete | def delete(self):
"""
Delete the link and free the resources
"""
if not self._created:
return
try:
node1 = self._nodes[0]["node"]
adapter_number1 = self._nodes[0]["adapter_number"]
port_number1 = self._nodes[0]["port_number"]
except IndexError:
return
try:
yield from node1.delete("/adapters/{adapter_number}/ports/{port_number}/nio".format(adapter_number=adapter_number1, port_number=port_number1), timeout=120)
# If the node is already delete (user selected multiple element and delete all in the same time)
except aiohttp.web.HTTPNotFound:
pass
try:
node2 = self._nodes[1]["node"]
adapter_number2 = self._nodes[1]["adapter_number"]
port_number2 = self._nodes[1]["port_number"]
except IndexError:
return
try:
yield from node2.delete("/adapters/{adapter_number}/ports/{port_number}/nio".format(adapter_number=adapter_number2, port_number=port_number2), timeout=120)
# If the node is already delete (user selected multiple element and delete all in the same time)
except aiohttp.web.HTTPNotFound:
pass
yield from super().delete() | python | def delete(self):
"""
Delete the link and free the resources
"""
if not self._created:
return
try:
node1 = self._nodes[0]["node"]
adapter_number1 = self._nodes[0]["adapter_number"]
port_number1 = self._nodes[0]["port_number"]
except IndexError:
return
try:
yield from node1.delete("/adapters/{adapter_number}/ports/{port_number}/nio".format(adapter_number=adapter_number1, port_number=port_number1), timeout=120)
# If the node is already delete (user selected multiple element and delete all in the same time)
except aiohttp.web.HTTPNotFound:
pass
try:
node2 = self._nodes[1]["node"]
adapter_number2 = self._nodes[1]["adapter_number"]
port_number2 = self._nodes[1]["port_number"]
except IndexError:
return
try:
yield from node2.delete("/adapters/{adapter_number}/ports/{port_number}/nio".format(adapter_number=adapter_number2, port_number=port_number2), timeout=120)
# If the node is already delete (user selected multiple element and delete all in the same time)
except aiohttp.web.HTTPNotFound:
pass
yield from super().delete() | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_created",
":",
"return",
"try",
":",
"node1",
"=",
"self",
".",
"_nodes",
"[",
"0",
"]",
"[",
"\"node\"",
"]",
"adapter_number1",
"=",
"self",
".",
"_nodes",
"[",
"0",
"]",
"[",
... | Delete the link and free the resources | [
"Delete",
"the",
"link",
"and",
"free",
"the",
"resources"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/udp_link.py#L118-L147 |
226,325 | GNS3/gns3-server | gns3server/controller/udp_link.py | UDPLink.start_capture | def start_capture(self, data_link_type="DLT_EN10MB", capture_file_name=None):
"""
Start capture on a link
"""
if not capture_file_name:
capture_file_name = self.default_capture_file_name()
self._capture_node = self._choose_capture_side()
data = {
"capture_file_name": capture_file_name,
"data_link_type": data_link_type
}
yield from self._capture_node["node"].post("/adapters/{adapter_number}/ports/{port_number}/start_capture".format(adapter_number=self._capture_node["adapter_number"], port_number=self._capture_node["port_number"]), data=data)
yield from super().start_capture(data_link_type=data_link_type, capture_file_name=capture_file_name) | python | def start_capture(self, data_link_type="DLT_EN10MB", capture_file_name=None):
"""
Start capture on a link
"""
if not capture_file_name:
capture_file_name = self.default_capture_file_name()
self._capture_node = self._choose_capture_side()
data = {
"capture_file_name": capture_file_name,
"data_link_type": data_link_type
}
yield from self._capture_node["node"].post("/adapters/{adapter_number}/ports/{port_number}/start_capture".format(adapter_number=self._capture_node["adapter_number"], port_number=self._capture_node["port_number"]), data=data)
yield from super().start_capture(data_link_type=data_link_type, capture_file_name=capture_file_name) | [
"def",
"start_capture",
"(",
"self",
",",
"data_link_type",
"=",
"\"DLT_EN10MB\"",
",",
"capture_file_name",
"=",
"None",
")",
":",
"if",
"not",
"capture_file_name",
":",
"capture_file_name",
"=",
"self",
".",
"default_capture_file_name",
"(",
")",
"self",
".",
... | Start capture on a link | [
"Start",
"capture",
"on",
"a",
"link"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/udp_link.py#L150-L162 |
226,326 | GNS3/gns3-server | gns3server/controller/udp_link.py | UDPLink.stop_capture | def stop_capture(self):
"""
Stop capture on a link
"""
if self._capture_node:
yield from self._capture_node["node"].post("/adapters/{adapter_number}/ports/{port_number}/stop_capture".format(adapter_number=self._capture_node["adapter_number"], port_number=self._capture_node["port_number"]))
self._capture_node = None
yield from super().stop_capture() | python | def stop_capture(self):
"""
Stop capture on a link
"""
if self._capture_node:
yield from self._capture_node["node"].post("/adapters/{adapter_number}/ports/{port_number}/stop_capture".format(adapter_number=self._capture_node["adapter_number"], port_number=self._capture_node["port_number"]))
self._capture_node = None
yield from super().stop_capture() | [
"def",
"stop_capture",
"(",
"self",
")",
":",
"if",
"self",
".",
"_capture_node",
":",
"yield",
"from",
"self",
".",
"_capture_node",
"[",
"\"node\"",
"]",
".",
"post",
"(",
"\"/adapters/{adapter_number}/ports/{port_number}/stop_capture\"",
".",
"format",
"(",
"ad... | Stop capture on a link | [
"Stop",
"capture",
"on",
"a",
"link"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/udp_link.py#L165-L172 |
226,327 | GNS3/gns3-server | gns3server/controller/udp_link.py | UDPLink._choose_capture_side | def _choose_capture_side(self):
"""
Run capture on the best candidate.
The ideal candidate is a node who on controller server and always
running (capture will not be cut off)
:returns: Node where the capture should run
"""
ALWAYS_RUNNING_NODES_TYPE = ("cloud", "nat", "ethernet_switch", "ethernet_hub")
for node in self._nodes:
if node["node"].compute.id == "local" and node["node"].node_type in ALWAYS_RUNNING_NODES_TYPE and node["node"].status == "started":
return node
for node in self._nodes:
if node["node"].node_type in ALWAYS_RUNNING_NODES_TYPE and node["node"].status == "started":
return node
for node in self._nodes:
if node["node"].compute.id == "local" and node["node"].status == "started":
return node
for node in self._nodes:
if node["node"].node_type and node["node"].status == "started":
return node
raise aiohttp.web.HTTPConflict(text="Cannot capture because there is no running device on this link") | python | def _choose_capture_side(self):
"""
Run capture on the best candidate.
The ideal candidate is a node who on controller server and always
running (capture will not be cut off)
:returns: Node where the capture should run
"""
ALWAYS_RUNNING_NODES_TYPE = ("cloud", "nat", "ethernet_switch", "ethernet_hub")
for node in self._nodes:
if node["node"].compute.id == "local" and node["node"].node_type in ALWAYS_RUNNING_NODES_TYPE and node["node"].status == "started":
return node
for node in self._nodes:
if node["node"].node_type in ALWAYS_RUNNING_NODES_TYPE and node["node"].status == "started":
return node
for node in self._nodes:
if node["node"].compute.id == "local" and node["node"].status == "started":
return node
for node in self._nodes:
if node["node"].node_type and node["node"].status == "started":
return node
raise aiohttp.web.HTTPConflict(text="Cannot capture because there is no running device on this link") | [
"def",
"_choose_capture_side",
"(",
"self",
")",
":",
"ALWAYS_RUNNING_NODES_TYPE",
"=",
"(",
"\"cloud\"",
",",
"\"nat\"",
",",
"\"ethernet_switch\"",
",",
"\"ethernet_hub\"",
")",
"for",
"node",
"in",
"self",
".",
"_nodes",
":",
"if",
"node",
"[",
"\"node\"",
... | Run capture on the best candidate.
The ideal candidate is a node who on controller server and always
running (capture will not be cut off)
:returns: Node where the capture should run | [
"Run",
"capture",
"on",
"the",
"best",
"candidate",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/udp_link.py#L174-L202 |
226,328 | GNS3/gns3-server | gns3server/controller/udp_link.py | UDPLink.read_pcap_from_source | def read_pcap_from_source(self):
"""
Return a FileStream of the Pcap from the compute node
"""
if self._capture_node:
compute = self._capture_node["node"].compute
return compute.stream_file(self._project, "tmp/captures/" + self._capture_file_name) | python | def read_pcap_from_source(self):
"""
Return a FileStream of the Pcap from the compute node
"""
if self._capture_node:
compute = self._capture_node["node"].compute
return compute.stream_file(self._project, "tmp/captures/" + self._capture_file_name) | [
"def",
"read_pcap_from_source",
"(",
"self",
")",
":",
"if",
"self",
".",
"_capture_node",
":",
"compute",
"=",
"self",
".",
"_capture_node",
"[",
"\"node\"",
"]",
".",
"compute",
"return",
"compute",
".",
"stream_file",
"(",
"self",
".",
"_project",
",",
... | Return a FileStream of the Pcap from the compute node | [
"Return",
"a",
"FileStream",
"of",
"the",
"Pcap",
"from",
"the",
"compute",
"node"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/udp_link.py#L205-L211 |
226,329 | GNS3/gns3-server | gns3server/controller/udp_link.py | UDPLink.node_updated | def node_updated(self, node):
"""
Called when a node member of the link is updated
"""
if self._capture_node and node == self._capture_node["node"] and node.status != "started":
yield from self.stop_capture() | python | def node_updated(self, node):
"""
Called when a node member of the link is updated
"""
if self._capture_node and node == self._capture_node["node"] and node.status != "started":
yield from self.stop_capture() | [
"def",
"node_updated",
"(",
"self",
",",
"node",
")",
":",
"if",
"self",
".",
"_capture_node",
"and",
"node",
"==",
"self",
".",
"_capture_node",
"[",
"\"node\"",
"]",
"and",
"node",
".",
"status",
"!=",
"\"started\"",
":",
"yield",
"from",
"self",
".",
... | Called when a node member of the link is updated | [
"Called",
"when",
"a",
"node",
"member",
"of",
"the",
"link",
"is",
"updated"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/udp_link.py#L214-L219 |
226,330 | GNS3/gns3-server | gns3server/utils/vmnet.py | parse_networking_file | def parse_networking_file():
"""
Parse the VMware networking file.
"""
pairs = dict()
allocated_subnets = []
try:
with open(VMWARE_NETWORKING_FILE, "r", encoding="utf-8") as f:
version = f.readline()
for line in f.read().splitlines():
try:
_, key, value = line.split(' ', 3)
key = key.strip()
value = value.strip()
pairs[key] = value
if key.endswith("HOSTONLY_SUBNET"):
allocated_subnets.append(value)
except ValueError:
raise SystemExit("Error while parsing {}".format(VMWARE_NETWORKING_FILE))
except OSError as e:
raise SystemExit("Cannot open {}: {}".format(VMWARE_NETWORKING_FILE, e))
return version, pairs, allocated_subnets | python | def parse_networking_file():
"""
Parse the VMware networking file.
"""
pairs = dict()
allocated_subnets = []
try:
with open(VMWARE_NETWORKING_FILE, "r", encoding="utf-8") as f:
version = f.readline()
for line in f.read().splitlines():
try:
_, key, value = line.split(' ', 3)
key = key.strip()
value = value.strip()
pairs[key] = value
if key.endswith("HOSTONLY_SUBNET"):
allocated_subnets.append(value)
except ValueError:
raise SystemExit("Error while parsing {}".format(VMWARE_NETWORKING_FILE))
except OSError as e:
raise SystemExit("Cannot open {}: {}".format(VMWARE_NETWORKING_FILE, e))
return version, pairs, allocated_subnets | [
"def",
"parse_networking_file",
"(",
")",
":",
"pairs",
"=",
"dict",
"(",
")",
"allocated_subnets",
"=",
"[",
"]",
"try",
":",
"with",
"open",
"(",
"VMWARE_NETWORKING_FILE",
",",
"\"r\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"f",
":",
"version",
... | Parse the VMware networking file. | [
"Parse",
"the",
"VMware",
"networking",
"file",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/vmnet.py#L39-L61 |
226,331 | GNS3/gns3-server | gns3server/utils/vmnet.py | write_networking_file | def write_networking_file(version, pairs):
"""
Write the VMware networking file.
"""
vmnets = OrderedDict(sorted(pairs.items(), key=lambda t: t[0]))
try:
with open(VMWARE_NETWORKING_FILE, "w", encoding="utf-8") as f:
f.write(version)
for key, value in vmnets.items():
f.write("answer {} {}\n".format(key, value))
except OSError as e:
raise SystemExit("Cannot open {}: {}".format(VMWARE_NETWORKING_FILE, e))
# restart VMware networking service
if sys.platform.startswith("darwin"):
if not os.path.exists("/Applications/VMware Fusion.app/Contents/Library/vmnet-cli"):
raise SystemExit("VMware Fusion is not installed in Applications")
os.system(r"/Applications/VMware\ Fusion.app/Contents/Library/vmnet-cli --configure")
os.system(r"/Applications/VMware\ Fusion.app/Contents/Library/vmnet-cli --stop")
os.system(r"/Applications/VMware\ Fusion.app/Contents/Library/vmnet-cli --start")
else:
os.system("vmware-networks --stop")
os.system("vmware-networks --start") | python | def write_networking_file(version, pairs):
"""
Write the VMware networking file.
"""
vmnets = OrderedDict(sorted(pairs.items(), key=lambda t: t[0]))
try:
with open(VMWARE_NETWORKING_FILE, "w", encoding="utf-8") as f:
f.write(version)
for key, value in vmnets.items():
f.write("answer {} {}\n".format(key, value))
except OSError as e:
raise SystemExit("Cannot open {}: {}".format(VMWARE_NETWORKING_FILE, e))
# restart VMware networking service
if sys.platform.startswith("darwin"):
if not os.path.exists("/Applications/VMware Fusion.app/Contents/Library/vmnet-cli"):
raise SystemExit("VMware Fusion is not installed in Applications")
os.system(r"/Applications/VMware\ Fusion.app/Contents/Library/vmnet-cli --configure")
os.system(r"/Applications/VMware\ Fusion.app/Contents/Library/vmnet-cli --stop")
os.system(r"/Applications/VMware\ Fusion.app/Contents/Library/vmnet-cli --start")
else:
os.system("vmware-networks --stop")
os.system("vmware-networks --start") | [
"def",
"write_networking_file",
"(",
"version",
",",
"pairs",
")",
":",
"vmnets",
"=",
"OrderedDict",
"(",
"sorted",
"(",
"pairs",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"t",
":",
"t",
"[",
"0",
"]",
")",
")",
"try",
":",
"with",
"open"... | Write the VMware networking file. | [
"Write",
"the",
"VMware",
"networking",
"file",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/vmnet.py#L64-L87 |
226,332 | GNS3/gns3-server | gns3server/utils/vmnet.py | parse_vmnet_range | def parse_vmnet_range(start, end):
"""
Parse the vmnet range on the command line.
"""
class Range(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
if len(values) != 2:
raise argparse.ArgumentTypeError("vmnet range must consist of 2 numbers")
if not start <= values[0] or not values[1] <= end:
raise argparse.ArgumentTypeError("vmnet range must be between {} and {}".format(start, end))
setattr(args, self.dest, values)
return Range | python | def parse_vmnet_range(start, end):
"""
Parse the vmnet range on the command line.
"""
class Range(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
if len(values) != 2:
raise argparse.ArgumentTypeError("vmnet range must consist of 2 numbers")
if not start <= values[0] or not values[1] <= end:
raise argparse.ArgumentTypeError("vmnet range must be between {} and {}".format(start, end))
setattr(args, self.dest, values)
return Range | [
"def",
"parse_vmnet_range",
"(",
"start",
",",
"end",
")",
":",
"class",
"Range",
"(",
"argparse",
".",
"Action",
")",
":",
"def",
"__call__",
"(",
"self",
",",
"parser",
",",
"args",
",",
"values",
",",
"option_string",
"=",
"None",
")",
":",
"if",
... | Parse the vmnet range on the command line. | [
"Parse",
"the",
"vmnet",
"range",
"on",
"the",
"command",
"line",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/vmnet.py#L90-L103 |
226,333 | GNS3/gns3-server | gns3server/utils/vmnet.py | vmnet_unix | def vmnet_unix(args, vmnet_range_start, vmnet_range_end):
"""
Implementation on Linux and Mac OS X.
"""
if not os.path.exists(VMWARE_NETWORKING_FILE):
raise SystemExit("VMware Player, Workstation or Fusion is not installed")
if not os.access(VMWARE_NETWORKING_FILE, os.W_OK):
raise SystemExit("You must run this script as root")
version, pairs, allocated_subnets = parse_networking_file()
if args.list and not sys.platform.startswith("win"):
for vmnet_number in range(1, 256):
vmnet_name = "VNET_{}_VIRTUAL_ADAPTER".format(vmnet_number)
if vmnet_name in pairs:
print("vmnet{}".format(vmnet_number))
return
if args.clean:
# clean all vmnets but vmnet1 and vmnet8
for key in pairs.copy().keys():
if key.startswith("VNET_1_") or key.startswith("VNET_8_"):
continue
del pairs[key]
else:
for vmnet_number in range(vmnet_range_start, vmnet_range_end + 1):
vmnet_name = "VNET_{}_VIRTUAL_ADAPTER".format(vmnet_number)
if vmnet_name in pairs:
continue
allocated_subnet = None
for subnet in ipaddress.ip_network("172.16.0.0/16").subnets(prefixlen_diff=8):
subnet = str(subnet.network_address)
if subnet not in allocated_subnets:
allocated_subnet = subnet
allocated_subnets.append(allocated_subnet)
break
if allocated_subnet is None:
print("Couldn't allocate a subnet for vmnet{}".format(vmnet_number))
continue
print("Adding vmnet{}...".format(vmnet_number))
pairs["VNET_{}_HOSTONLY_NETMASK".format(vmnet_number)] = "255.255.255.0"
pairs["VNET_{}_HOSTONLY_SUBNET".format(vmnet_number)] = allocated_subnet
pairs["VNET_{}_VIRTUAL_ADAPTER".format(vmnet_number)] = "yes"
write_networking_file(version, pairs) | python | def vmnet_unix(args, vmnet_range_start, vmnet_range_end):
"""
Implementation on Linux and Mac OS X.
"""
if not os.path.exists(VMWARE_NETWORKING_FILE):
raise SystemExit("VMware Player, Workstation or Fusion is not installed")
if not os.access(VMWARE_NETWORKING_FILE, os.W_OK):
raise SystemExit("You must run this script as root")
version, pairs, allocated_subnets = parse_networking_file()
if args.list and not sys.platform.startswith("win"):
for vmnet_number in range(1, 256):
vmnet_name = "VNET_{}_VIRTUAL_ADAPTER".format(vmnet_number)
if vmnet_name in pairs:
print("vmnet{}".format(vmnet_number))
return
if args.clean:
# clean all vmnets but vmnet1 and vmnet8
for key in pairs.copy().keys():
if key.startswith("VNET_1_") or key.startswith("VNET_8_"):
continue
del pairs[key]
else:
for vmnet_number in range(vmnet_range_start, vmnet_range_end + 1):
vmnet_name = "VNET_{}_VIRTUAL_ADAPTER".format(vmnet_number)
if vmnet_name in pairs:
continue
allocated_subnet = None
for subnet in ipaddress.ip_network("172.16.0.0/16").subnets(prefixlen_diff=8):
subnet = str(subnet.network_address)
if subnet not in allocated_subnets:
allocated_subnet = subnet
allocated_subnets.append(allocated_subnet)
break
if allocated_subnet is None:
print("Couldn't allocate a subnet for vmnet{}".format(vmnet_number))
continue
print("Adding vmnet{}...".format(vmnet_number))
pairs["VNET_{}_HOSTONLY_NETMASK".format(vmnet_number)] = "255.255.255.0"
pairs["VNET_{}_HOSTONLY_SUBNET".format(vmnet_number)] = allocated_subnet
pairs["VNET_{}_VIRTUAL_ADAPTER".format(vmnet_number)] = "yes"
write_networking_file(version, pairs) | [
"def",
"vmnet_unix",
"(",
"args",
",",
"vmnet_range_start",
",",
"vmnet_range_end",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"VMWARE_NETWORKING_FILE",
")",
":",
"raise",
"SystemExit",
"(",
"\"VMware Player, Workstation or Fusion is not installed\"... | Implementation on Linux and Mac OS X. | [
"Implementation",
"on",
"Linux",
"and",
"Mac",
"OS",
"X",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/vmnet.py#L183-L229 |
226,334 | GNS3/gns3-server | gns3server/utils/vmnet.py | main | def main():
"""
Entry point for the VMNET tool.
"""
parser = argparse.ArgumentParser(description='%(prog)s add/remove vmnet interfaces')
parser.add_argument('-r', "--range", nargs='+', action=parse_vmnet_range(1, 255),
type=int, help="vmnet range to add (default is {} {})".format(DEFAULT_RANGE[0], DEFAULT_RANGE[1]))
parser.add_argument("-C", "--clean", action="store_true", help="remove all vmnets excepting vmnet1 and vmnet8")
parser.add_argument("-l", "--list", action="store_true", help="list all existing vmnets (UNIX only)")
try:
args = parser.parse_args()
except argparse.ArgumentTypeError as e:
raise SystemExit(e)
vmnet_range = args.range if args.range is not None else DEFAULT_RANGE
if sys.platform.startswith("win"):
try:
vmnet_windows(args, vmnet_range[0], vmnet_range[1])
except SystemExit:
os.system("pause")
raise
else:
vmnet_unix(args, vmnet_range[0], vmnet_range[1]) | python | def main():
"""
Entry point for the VMNET tool.
"""
parser = argparse.ArgumentParser(description='%(prog)s add/remove vmnet interfaces')
parser.add_argument('-r', "--range", nargs='+', action=parse_vmnet_range(1, 255),
type=int, help="vmnet range to add (default is {} {})".format(DEFAULT_RANGE[0], DEFAULT_RANGE[1]))
parser.add_argument("-C", "--clean", action="store_true", help="remove all vmnets excepting vmnet1 and vmnet8")
parser.add_argument("-l", "--list", action="store_true", help="list all existing vmnets (UNIX only)")
try:
args = parser.parse_args()
except argparse.ArgumentTypeError as e:
raise SystemExit(e)
vmnet_range = args.range if args.range is not None else DEFAULT_RANGE
if sys.platform.startswith("win"):
try:
vmnet_windows(args, vmnet_range[0], vmnet_range[1])
except SystemExit:
os.system("pause")
raise
else:
vmnet_unix(args, vmnet_range[0], vmnet_range[1]) | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'%(prog)s add/remove vmnet interfaces'",
")",
"parser",
".",
"add_argument",
"(",
"'-r'",
",",
"\"--range\"",
",",
"nargs",
"=",
"'+'",
",",
"action",
"="... | Entry point for the VMNET tool. | [
"Entry",
"point",
"for",
"the",
"VMNET",
"tool",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/vmnet.py#L232-L256 |
226,335 | GNS3/gns3-server | gns3server/utils/asyncio/telnet_server.py | AsyncioTelnetServer._get_reader | def _get_reader(self, network_reader):
"""
Get a reader or None if another reader is already reading.
"""
with (yield from self._lock):
if self._reader_process is None:
self._reader_process = network_reader
if self._reader:
if self._reader_process == network_reader:
self._current_read = asyncio.async(self._reader.read(READ_SIZE))
return self._current_read
return None | python | def _get_reader(self, network_reader):
"""
Get a reader or None if another reader is already reading.
"""
with (yield from self._lock):
if self._reader_process is None:
self._reader_process = network_reader
if self._reader:
if self._reader_process == network_reader:
self._current_read = asyncio.async(self._reader.read(READ_SIZE))
return self._current_read
return None | [
"def",
"_get_reader",
"(",
"self",
",",
"network_reader",
")",
":",
"with",
"(",
"yield",
"from",
"self",
".",
"_lock",
")",
":",
"if",
"self",
".",
"_reader_process",
"is",
"None",
":",
"self",
".",
"_reader_process",
"=",
"network_reader",
"if",
"self",
... | Get a reader or None if another reader is already reading. | [
"Get",
"a",
"reader",
"or",
"None",
"if",
"another",
"reader",
"is",
"already",
"reading",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/telnet_server.py#L223-L234 |
226,336 | GNS3/gns3-server | gns3server/utils/asyncio/telnet_server.py | AsyncioTelnetServer._read | def _read(self, cmd, buffer, location, reader):
""" Reads next op from the buffer or reader"""
try:
op = buffer[location]
cmd.append(op)
return op
except IndexError:
op = yield from reader.read(1)
buffer.extend(op)
cmd.append(buffer[location])
return op | python | def _read(self, cmd, buffer, location, reader):
""" Reads next op from the buffer or reader"""
try:
op = buffer[location]
cmd.append(op)
return op
except IndexError:
op = yield from reader.read(1)
buffer.extend(op)
cmd.append(buffer[location])
return op | [
"def",
"_read",
"(",
"self",
",",
"cmd",
",",
"buffer",
",",
"location",
",",
"reader",
")",
":",
"try",
":",
"op",
"=",
"buffer",
"[",
"location",
"]",
"cmd",
".",
"append",
"(",
"op",
")",
"return",
"op",
"except",
"IndexError",
":",
"op",
"=",
... | Reads next op from the buffer or reader | [
"Reads",
"next",
"op",
"from",
"the",
"buffer",
"or",
"reader"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/telnet_server.py#L295-L305 |
226,337 | GNS3/gns3-server | gns3server/utils/asyncio/telnet_server.py | AsyncioTelnetServer._negotiate | def _negotiate(self, data, connection):
""" Performs negotiation commands"""
command, payload = data[0], data[1:]
if command == NAWS:
if len(payload) == 4:
columns, rows = struct.unpack(str('!HH'), bytes(payload))
connection.window_size_changed(columns, rows)
else:
log.warning('Wrong number of NAWS bytes')
else:
log.debug("Not supported negotiation sequence, received {} bytes", len(data)) | python | def _negotiate(self, data, connection):
""" Performs negotiation commands"""
command, payload = data[0], data[1:]
if command == NAWS:
if len(payload) == 4:
columns, rows = struct.unpack(str('!HH'), bytes(payload))
connection.window_size_changed(columns, rows)
else:
log.warning('Wrong number of NAWS bytes')
else:
log.debug("Not supported negotiation sequence, received {} bytes", len(data)) | [
"def",
"_negotiate",
"(",
"self",
",",
"data",
",",
"connection",
")",
":",
"command",
",",
"payload",
"=",
"data",
"[",
"0",
"]",
",",
"data",
"[",
"1",
":",
"]",
"if",
"command",
"==",
"NAWS",
":",
"if",
"len",
"(",
"payload",
")",
"==",
"4",
... | Performs negotiation commands | [
"Performs",
"negotiation",
"commands"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/telnet_server.py#L307-L318 |
226,338 | GNS3/gns3-server | gns3server/utils/ping_stats.py | PingStats.get | def get(cls):
"""
Get ping statistics
:returns: hash
"""
stats = {}
cur_time = time.time()
# minimum interval for getting CPU and memory statistics
if cur_time < cls._last_measurement or \
cur_time > cls._last_measurement + 1.9:
cls._last_measurement = cur_time
# Non blocking call to get cpu usage. First call will return 0
cls._last_cpu_percent = psutil.cpu_percent(interval=None)
cls._last_mem_percent = psutil.virtual_memory().percent
stats["cpu_usage_percent"] = cls._last_cpu_percent
stats["memory_usage_percent"] = cls._last_mem_percent
return stats | python | def get(cls):
"""
Get ping statistics
:returns: hash
"""
stats = {}
cur_time = time.time()
# minimum interval for getting CPU and memory statistics
if cur_time < cls._last_measurement or \
cur_time > cls._last_measurement + 1.9:
cls._last_measurement = cur_time
# Non blocking call to get cpu usage. First call will return 0
cls._last_cpu_percent = psutil.cpu_percent(interval=None)
cls._last_mem_percent = psutil.virtual_memory().percent
stats["cpu_usage_percent"] = cls._last_cpu_percent
stats["memory_usage_percent"] = cls._last_mem_percent
return stats | [
"def",
"get",
"(",
"cls",
")",
":",
"stats",
"=",
"{",
"}",
"cur_time",
"=",
"time",
".",
"time",
"(",
")",
"# minimum interval for getting CPU and memory statistics",
"if",
"cur_time",
"<",
"cls",
".",
"_last_measurement",
"or",
"cur_time",
">",
"cls",
".",
... | Get ping statistics
:returns: hash | [
"Get",
"ping",
"statistics"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/ping_stats.py#L33-L50 |
226,339 | GNS3/gns3-server | gns3server/ubridge/ubridge_hypervisor.py | UBridgeHypervisor.send | def send(self, command):
"""
Sends commands to this hypervisor.
:param command: a uBridge hypervisor command
:returns: results as a list
"""
# uBridge responses are of the form:
# 1xx yyyyyy\r\n
# 1xx yyyyyy\r\n
# ...
# 100-yyyy\r\n
# or
# 2xx-yyyy\r\n
#
# Where 1xx is a code from 100-199 for a success or 200-299 for an error
# The result might be multiple lines and might be less than the buffer size
# but still have more data. The only thing we know for sure is the last line
# will begin with '100-' or a '2xx-' and end with '\r\n'
if self._writer is None or self._reader is None:
raise UbridgeError("Not connected")
try:
command = command.strip() + '\n'
log.debug("sending {}".format(command))
self._writer.write(command.encode())
yield from self._writer.drain()
except OSError as e:
raise UbridgeError("Lost communication with {host}:{port} :{error}, Dynamips process running: {run}"
.format(host=self._host, port=self._port, error=e, run=self.is_running()))
# Now retrieve the result
data = []
buf = ''
retries = 0
max_retries = 10
while True:
try:
try:
chunk = yield from self._reader.read(1024)
except asyncio.CancelledError:
# task has been canceled but continue to read
# any remaining data sent by the hypervisor
continue
except ConnectionResetError as e:
# Sometimes WinError 64 (ERROR_NETNAME_DELETED) is returned here on Windows.
# These happen if connection reset is received before IOCP could complete
# a previous operation. Ignore and try again....
log.warning("Connection reset received while reading uBridge response: {}".format(e))
continue
if not chunk:
if retries > max_retries:
raise UbridgeError("No data returned from {host}:{port}, uBridge process running: {run}"
.format(host=self._host, port=self._port, run=self.is_running()))
else:
retries += 1
yield from asyncio.sleep(0.1)
continue
retries = 0
buf += chunk.decode("utf-8")
except OSError as e:
raise UbridgeError("Lost communication with {host}:{port} :{error}, uBridge process running: {run}"
.format(host=self._host, port=self._port, error=e, run=self.is_running()))
# If the buffer doesn't end in '\n' then we can't be done
try:
if buf[-1] != '\n':
continue
except IndexError:
raise UbridgeError("Could not communicate with {host}:{port}, uBridge process running: {run}"
.format(host=self._host, port=self._port, run=self.is_running()))
data += buf.split('\r\n')
if data[-1] == '':
data.pop()
buf = ''
# Does it contain an error code?
if self.error_re.search(data[-1]):
raise UbridgeError(data[-1][4:])
# Or does the last line begin with '100-'? Then we are done!
if data[-1][:4] == '100-':
data[-1] = data[-1][4:]
if data[-1] == 'OK':
data.pop()
break
# Remove success responses codes
for index in range(len(data)):
if self.success_re.search(data[index]):
data[index] = data[index][4:]
log.debug("returned result {}".format(data))
return data | python | def send(self, command):
"""
Sends commands to this hypervisor.
:param command: a uBridge hypervisor command
:returns: results as a list
"""
# uBridge responses are of the form:
# 1xx yyyyyy\r\n
# 1xx yyyyyy\r\n
# ...
# 100-yyyy\r\n
# or
# 2xx-yyyy\r\n
#
# Where 1xx is a code from 100-199 for a success or 200-299 for an error
# The result might be multiple lines and might be less than the buffer size
# but still have more data. The only thing we know for sure is the last line
# will begin with '100-' or a '2xx-' and end with '\r\n'
if self._writer is None or self._reader is None:
raise UbridgeError("Not connected")
try:
command = command.strip() + '\n'
log.debug("sending {}".format(command))
self._writer.write(command.encode())
yield from self._writer.drain()
except OSError as e:
raise UbridgeError("Lost communication with {host}:{port} :{error}, Dynamips process running: {run}"
.format(host=self._host, port=self._port, error=e, run=self.is_running()))
# Now retrieve the result
data = []
buf = ''
retries = 0
max_retries = 10
while True:
try:
try:
chunk = yield from self._reader.read(1024)
except asyncio.CancelledError:
# task has been canceled but continue to read
# any remaining data sent by the hypervisor
continue
except ConnectionResetError as e:
# Sometimes WinError 64 (ERROR_NETNAME_DELETED) is returned here on Windows.
# These happen if connection reset is received before IOCP could complete
# a previous operation. Ignore and try again....
log.warning("Connection reset received while reading uBridge response: {}".format(e))
continue
if not chunk:
if retries > max_retries:
raise UbridgeError("No data returned from {host}:{port}, uBridge process running: {run}"
.format(host=self._host, port=self._port, run=self.is_running()))
else:
retries += 1
yield from asyncio.sleep(0.1)
continue
retries = 0
buf += chunk.decode("utf-8")
except OSError as e:
raise UbridgeError("Lost communication with {host}:{port} :{error}, uBridge process running: {run}"
.format(host=self._host, port=self._port, error=e, run=self.is_running()))
# If the buffer doesn't end in '\n' then we can't be done
try:
if buf[-1] != '\n':
continue
except IndexError:
raise UbridgeError("Could not communicate with {host}:{port}, uBridge process running: {run}"
.format(host=self._host, port=self._port, run=self.is_running()))
data += buf.split('\r\n')
if data[-1] == '':
data.pop()
buf = ''
# Does it contain an error code?
if self.error_re.search(data[-1]):
raise UbridgeError(data[-1][4:])
# Or does the last line begin with '100-'? Then we are done!
if data[-1][:4] == '100-':
data[-1] = data[-1][4:]
if data[-1] == 'OK':
data.pop()
break
# Remove success responses codes
for index in range(len(data)):
if self.success_re.search(data[index]):
data[index] = data[index][4:]
log.debug("returned result {}".format(data))
return data | [
"def",
"send",
"(",
"self",
",",
"command",
")",
":",
"# uBridge responses are of the form:",
"# 1xx yyyyyy\\r\\n",
"# 1xx yyyyyy\\r\\n",
"# ...",
"# 100-yyyy\\r\\n",
"# or",
"# 2xx-yyyy\\r\\n",
"#",
"# Where 1xx is a code from 100-199 for a success or 200-299 for an error"... | Sends commands to this hypervisor.
:param command: a uBridge hypervisor command
:returns: results as a list | [
"Sends",
"commands",
"to",
"this",
"hypervisor",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/ubridge/ubridge_hypervisor.py#L180-L277 |
226,340 | GNS3/gns3-server | gns3server/web/route.py | parse_request | def parse_request(request, input_schema, raw):
"""Parse body of request and raise HTTP errors in case of problems"""
request.json = {}
if not raw:
body = yield from request.read()
if body:
try:
request.json = json.loads(body.decode('utf-8'))
except ValueError as e:
request.json = {"malformed_json": body.decode('utf-8')}
raise aiohttp.web.HTTPBadRequest(text="Invalid JSON {}".format(e))
# Parse the query string
if len(request.query_string) > 0:
for (k, v) in urllib.parse.parse_qs(request.query_string).items():
request.json[k] = v[0]
if input_schema:
try:
jsonschema.validate(request.json, input_schema)
except jsonschema.ValidationError as e:
log.error("Invalid input query. JSON schema error: {}".format(e.message))
raise aiohttp.web.HTTPBadRequest(text="Invalid JSON: {} in schema: {}".format(
e.message,
json.dumps(e.schema)))
return request | python | def parse_request(request, input_schema, raw):
"""Parse body of request and raise HTTP errors in case of problems"""
request.json = {}
if not raw:
body = yield from request.read()
if body:
try:
request.json = json.loads(body.decode('utf-8'))
except ValueError as e:
request.json = {"malformed_json": body.decode('utf-8')}
raise aiohttp.web.HTTPBadRequest(text="Invalid JSON {}".format(e))
# Parse the query string
if len(request.query_string) > 0:
for (k, v) in urllib.parse.parse_qs(request.query_string).items():
request.json[k] = v[0]
if input_schema:
try:
jsonschema.validate(request.json, input_schema)
except jsonschema.ValidationError as e:
log.error("Invalid input query. JSON schema error: {}".format(e.message))
raise aiohttp.web.HTTPBadRequest(text="Invalid JSON: {} in schema: {}".format(
e.message,
json.dumps(e.schema)))
return request | [
"def",
"parse_request",
"(",
"request",
",",
"input_schema",
",",
"raw",
")",
":",
"request",
".",
"json",
"=",
"{",
"}",
"if",
"not",
"raw",
":",
"body",
"=",
"yield",
"from",
"request",
".",
"read",
"(",
")",
"if",
"body",
":",
"try",
":",
"reque... | Parse body of request and raise HTTP errors in case of problems | [
"Parse",
"body",
"of",
"request",
"and",
"raise",
"HTTP",
"errors",
"in",
"case",
"of",
"problems"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/web/route.py#L40-L67 |
226,341 | GNS3/gns3-server | gns3server/web/route.py | Route.authenticate | def authenticate(cls, request, route, server_config):
"""
Ask user for authentication
:returns: Response if you need to auth the user otherwise None
"""
if not server_config.getboolean("auth", False):
return
user = server_config.get("user", "").strip()
password = server_config.get("password", "").strip()
if len(user) == 0:
return
if "AUTHORIZATION" in request.headers:
if request.headers["AUTHORIZATION"] == aiohttp.helpers.BasicAuth(user, password, "utf-8").encode():
return
log.error("Invalid auth. Username should %s", user)
response = Response(request=request, route=route)
response.set_status(401)
response.headers["WWW-Authenticate"] = 'Basic realm="GNS3 server"'
# Force close the keep alive. Work around a Qt issue where Qt timeout instead of handling the 401
# this happen only for the first query send by the client.
response.force_close()
return response | python | def authenticate(cls, request, route, server_config):
"""
Ask user for authentication
:returns: Response if you need to auth the user otherwise None
"""
if not server_config.getboolean("auth", False):
return
user = server_config.get("user", "").strip()
password = server_config.get("password", "").strip()
if len(user) == 0:
return
if "AUTHORIZATION" in request.headers:
if request.headers["AUTHORIZATION"] == aiohttp.helpers.BasicAuth(user, password, "utf-8").encode():
return
log.error("Invalid auth. Username should %s", user)
response = Response(request=request, route=route)
response.set_status(401)
response.headers["WWW-Authenticate"] = 'Basic realm="GNS3 server"'
# Force close the keep alive. Work around a Qt issue where Qt timeout instead of handling the 401
# this happen only for the first query send by the client.
response.force_close()
return response | [
"def",
"authenticate",
"(",
"cls",
",",
"request",
",",
"route",
",",
"server_config",
")",
":",
"if",
"not",
"server_config",
".",
"getboolean",
"(",
"\"auth\"",
",",
"False",
")",
":",
"return",
"user",
"=",
"server_config",
".",
"get",
"(",
"\"user\"",
... | Ask user for authentication
:returns: Response if you need to auth the user otherwise None | [
"Ask",
"user",
"for",
"authentication"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/web/route.py#L100-L127 |
226,342 | GNS3/gns3-server | gns3server/notification_queue.py | NotificationQueue.get | def get(self, timeout):
"""
When timeout is expire we send a ping notification with server information
"""
# At first get we return a ping so the client immediately receives data
if self._first:
self._first = False
return ("ping", PingStats.get(), {})
try:
(action, msg, kwargs) = yield from asyncio.wait_for(super().get(), timeout)
except asyncio.futures.TimeoutError:
return ("ping", PingStats.get(), {})
return (action, msg, kwargs) | python | def get(self, timeout):
"""
When timeout is expire we send a ping notification with server information
"""
# At first get we return a ping so the client immediately receives data
if self._first:
self._first = False
return ("ping", PingStats.get(), {})
try:
(action, msg, kwargs) = yield from asyncio.wait_for(super().get(), timeout)
except asyncio.futures.TimeoutError:
return ("ping", PingStats.get(), {})
return (action, msg, kwargs) | [
"def",
"get",
"(",
"self",
",",
"timeout",
")",
":",
"# At first get we return a ping so the client immediately receives data",
"if",
"self",
".",
"_first",
":",
"self",
".",
"_first",
"=",
"False",
"return",
"(",
"\"ping\"",
",",
"PingStats",
".",
"get",
"(",
"... | When timeout is expire we send a ping notification with server information | [
"When",
"timeout",
"is",
"expire",
"we",
"send",
"a",
"ping",
"notification",
"with",
"server",
"information"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/notification_queue.py#L34-L48 |
226,343 | GNS3/gns3-server | gns3server/notification_queue.py | NotificationQueue.get_json | def get_json(self, timeout):
"""
Get a message as a JSON
"""
(action, msg, kwargs) = yield from self.get(timeout)
if hasattr(msg, "__json__"):
msg = {"action": action, "event": msg.__json__()}
else:
msg = {"action": action, "event": msg}
msg.update(kwargs)
return json.dumps(msg, sort_keys=True) | python | def get_json(self, timeout):
"""
Get a message as a JSON
"""
(action, msg, kwargs) = yield from self.get(timeout)
if hasattr(msg, "__json__"):
msg = {"action": action, "event": msg.__json__()}
else:
msg = {"action": action, "event": msg}
msg.update(kwargs)
return json.dumps(msg, sort_keys=True) | [
"def",
"get_json",
"(",
"self",
",",
"timeout",
")",
":",
"(",
"action",
",",
"msg",
",",
"kwargs",
")",
"=",
"yield",
"from",
"self",
".",
"get",
"(",
"timeout",
")",
"if",
"hasattr",
"(",
"msg",
",",
"\"__json__\"",
")",
":",
"msg",
"=",
"{",
"... | Get a message as a JSON | [
"Get",
"a",
"message",
"as",
"a",
"JSON"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/notification_queue.py#L51-L61 |
226,344 | GNS3/gns3-server | gns3server/compute/vpcs/vpcs_vm.py | VPCSVM.close | def close(self):
"""
Closes this VPCS VM.
"""
if not (yield from super().close()):
return False
nio = self._ethernet_adapter.get_nio(0)
if isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
if self._local_udp_tunnel:
self.manager.port_manager.release_udp_port(self._local_udp_tunnel[0].lport, self._project)
self.manager.port_manager.release_udp_port(self._local_udp_tunnel[1].lport, self._project)
self._local_udp_tunnel = None
yield from self._stop_ubridge()
if self.is_running():
self._terminate_process()
return True | python | def close(self):
"""
Closes this VPCS VM.
"""
if not (yield from super().close()):
return False
nio = self._ethernet_adapter.get_nio(0)
if isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
if self._local_udp_tunnel:
self.manager.port_manager.release_udp_port(self._local_udp_tunnel[0].lport, self._project)
self.manager.port_manager.release_udp_port(self._local_udp_tunnel[1].lport, self._project)
self._local_udp_tunnel = None
yield from self._stop_ubridge()
if self.is_running():
self._terminate_process()
return True | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"(",
"yield",
"from",
"super",
"(",
")",
".",
"close",
"(",
")",
")",
":",
"return",
"False",
"nio",
"=",
"self",
".",
"_ethernet_adapter",
".",
"get_nio",
"(",
"0",
")",
"if",
"isinstance",
"(",
... | Closes this VPCS VM. | [
"Closes",
"this",
"VPCS",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L81-L103 |
226,345 | GNS3/gns3-server | gns3server/compute/vpcs/vpcs_vm.py | VPCSVM._check_requirements | def _check_requirements(self):
"""
Check if VPCS is available with the correct version.
"""
path = self._vpcs_path()
if not path:
raise VPCSError("No path to a VPCS executable has been set")
# This raise an error if ubridge is not available
self.ubridge_path
if not os.path.isfile(path):
raise VPCSError("VPCS program '{}' is not accessible".format(path))
if not os.access(path, os.X_OK):
raise VPCSError("VPCS program '{}' is not executable".format(path))
yield from self._check_vpcs_version() | python | def _check_requirements(self):
"""
Check if VPCS is available with the correct version.
"""
path = self._vpcs_path()
if not path:
raise VPCSError("No path to a VPCS executable has been set")
# This raise an error if ubridge is not available
self.ubridge_path
if not os.path.isfile(path):
raise VPCSError("VPCS program '{}' is not accessible".format(path))
if not os.access(path, os.X_OK):
raise VPCSError("VPCS program '{}' is not executable".format(path))
yield from self._check_vpcs_version() | [
"def",
"_check_requirements",
"(",
"self",
")",
":",
"path",
"=",
"self",
".",
"_vpcs_path",
"(",
")",
"if",
"not",
"path",
":",
"raise",
"VPCSError",
"(",
"\"No path to a VPCS executable has been set\"",
")",
"# This raise an error if ubridge is not available",
"self",... | Check if VPCS is available with the correct version. | [
"Check",
"if",
"VPCS",
"is",
"available",
"with",
"the",
"correct",
"version",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L106-L124 |
226,346 | GNS3/gns3-server | gns3server/compute/vpcs/vpcs_vm.py | VPCSVM._vpcs_path | def _vpcs_path(self):
"""
Returns the VPCS executable path.
:returns: path to VPCS
"""
search_path = self._manager.config.get_section_config("VPCS").get("vpcs_path", "vpcs")
path = shutil.which(search_path)
# shutil.which return None if the path doesn't exists
if not path:
return search_path
return path | python | def _vpcs_path(self):
"""
Returns the VPCS executable path.
:returns: path to VPCS
"""
search_path = self._manager.config.get_section_config("VPCS").get("vpcs_path", "vpcs")
path = shutil.which(search_path)
# shutil.which return None if the path doesn't exists
if not path:
return search_path
return path | [
"def",
"_vpcs_path",
"(",
"self",
")",
":",
"search_path",
"=",
"self",
".",
"_manager",
".",
"config",
".",
"get_section_config",
"(",
"\"VPCS\"",
")",
".",
"get",
"(",
"\"vpcs_path\"",
",",
"\"vpcs\"",
")",
"path",
"=",
"shutil",
".",
"which",
"(",
"se... | Returns the VPCS executable path.
:returns: path to VPCS | [
"Returns",
"the",
"VPCS",
"executable",
"path",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L137-L149 |
226,347 | GNS3/gns3-server | gns3server/compute/vpcs/vpcs_vm.py | VPCSVM.name | def name(self, new_name):
"""
Sets the name of this VPCS VM.
:param new_name: name
"""
if self.script_file:
content = self.startup_script
content = content.replace(self._name, new_name)
escaped_name = new_name.replace('\\', '')
content = re.sub(r"^set pcname .+$", "set pcname " + escaped_name, content, flags=re.MULTILINE)
self.startup_script = content
super(VPCSVM, VPCSVM).name.__set__(self, new_name) | python | def name(self, new_name):
"""
Sets the name of this VPCS VM.
:param new_name: name
"""
if self.script_file:
content = self.startup_script
content = content.replace(self._name, new_name)
escaped_name = new_name.replace('\\', '')
content = re.sub(r"^set pcname .+$", "set pcname " + escaped_name, content, flags=re.MULTILINE)
self.startup_script = content
super(VPCSVM, VPCSVM).name.__set__(self, new_name) | [
"def",
"name",
"(",
"self",
",",
"new_name",
")",
":",
"if",
"self",
".",
"script_file",
":",
"content",
"=",
"self",
".",
"startup_script",
"content",
"=",
"content",
".",
"replace",
"(",
"self",
".",
"_name",
",",
"new_name",
")",
"escaped_name",
"=",
... | Sets the name of this VPCS VM.
:param new_name: name | [
"Sets",
"the",
"name",
"of",
"this",
"VPCS",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L152-L166 |
226,348 | GNS3/gns3-server | gns3server/compute/vpcs/vpcs_vm.py | VPCSVM.startup_script | def startup_script(self):
"""
Returns the content of the current startup script
"""
script_file = self.script_file
if script_file is None:
return None
try:
with open(script_file, "rb") as f:
return f.read().decode("utf-8", errors="replace")
except OSError as e:
raise VPCSError('Cannot read the startup script file "{}": {}'.format(script_file, e)) | python | def startup_script(self):
"""
Returns the content of the current startup script
"""
script_file = self.script_file
if script_file is None:
return None
try:
with open(script_file, "rb") as f:
return f.read().decode("utf-8", errors="replace")
except OSError as e:
raise VPCSError('Cannot read the startup script file "{}": {}'.format(script_file, e)) | [
"def",
"startup_script",
"(",
"self",
")",
":",
"script_file",
"=",
"self",
".",
"script_file",
"if",
"script_file",
"is",
"None",
":",
"return",
"None",
"try",
":",
"with",
"open",
"(",
"script_file",
",",
"\"rb\"",
")",
"as",
"f",
":",
"return",
"f",
... | Returns the content of the current startup script | [
"Returns",
"the",
"content",
"of",
"the",
"current",
"startup",
"script"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L169-L182 |
226,349 | GNS3/gns3-server | gns3server/compute/vpcs/vpcs_vm.py | VPCSVM.startup_script | def startup_script(self, startup_script):
"""
Updates the startup script.
:param startup_script: content of the startup script
"""
try:
startup_script_path = os.path.join(self.working_dir, 'startup.vpc')
with open(startup_script_path, "w+", encoding='utf-8') as f:
if startup_script is None:
f.write('')
else:
startup_script = startup_script.replace("%h", self._name)
f.write(startup_script)
except OSError as e:
raise VPCSError('Cannot write the startup script file "{}": {}'.format(startup_script_path, e)) | python | def startup_script(self, startup_script):
"""
Updates the startup script.
:param startup_script: content of the startup script
"""
try:
startup_script_path = os.path.join(self.working_dir, 'startup.vpc')
with open(startup_script_path, "w+", encoding='utf-8') as f:
if startup_script is None:
f.write('')
else:
startup_script = startup_script.replace("%h", self._name)
f.write(startup_script)
except OSError as e:
raise VPCSError('Cannot write the startup script file "{}": {}'.format(startup_script_path, e)) | [
"def",
"startup_script",
"(",
"self",
",",
"startup_script",
")",
":",
"try",
":",
"startup_script_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"working_dir",
",",
"'startup.vpc'",
")",
"with",
"open",
"(",
"startup_script_path",
",",
"\"w+\... | Updates the startup script.
:param startup_script: content of the startup script | [
"Updates",
"the",
"startup",
"script",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L185-L201 |
226,350 | GNS3/gns3-server | gns3server/compute/vpcs/vpcs_vm.py | VPCSVM._check_vpcs_version | def _check_vpcs_version(self):
"""
Checks if the VPCS executable version is >= 0.8b or == 0.6.1.
"""
try:
output = yield from subprocess_check_output(self._vpcs_path(), "-v", cwd=self.working_dir)
match = re.search("Welcome to Virtual PC Simulator, version ([0-9a-z\.]+)", output)
if match:
version = match.group(1)
self._vpcs_version = parse_version(version)
if self._vpcs_version < parse_version("0.6.1"):
raise VPCSError("VPCS executable version must be >= 0.6.1 but not a 0.8")
else:
raise VPCSError("Could not determine the VPCS version for {}".format(self._vpcs_path()))
except (OSError, subprocess.SubprocessError) as e:
raise VPCSError("Error while looking for the VPCS version: {}".format(e)) | python | def _check_vpcs_version(self):
"""
Checks if the VPCS executable version is >= 0.8b or == 0.6.1.
"""
try:
output = yield from subprocess_check_output(self._vpcs_path(), "-v", cwd=self.working_dir)
match = re.search("Welcome to Virtual PC Simulator, version ([0-9a-z\.]+)", output)
if match:
version = match.group(1)
self._vpcs_version = parse_version(version)
if self._vpcs_version < parse_version("0.6.1"):
raise VPCSError("VPCS executable version must be >= 0.6.1 but not a 0.8")
else:
raise VPCSError("Could not determine the VPCS version for {}".format(self._vpcs_path()))
except (OSError, subprocess.SubprocessError) as e:
raise VPCSError("Error while looking for the VPCS version: {}".format(e)) | [
"def",
"_check_vpcs_version",
"(",
"self",
")",
":",
"try",
":",
"output",
"=",
"yield",
"from",
"subprocess_check_output",
"(",
"self",
".",
"_vpcs_path",
"(",
")",
",",
"\"-v\"",
",",
"cwd",
"=",
"self",
".",
"working_dir",
")",
"match",
"=",
"re",
"."... | Checks if the VPCS executable version is >= 0.8b or == 0.6.1. | [
"Checks",
"if",
"the",
"VPCS",
"executable",
"version",
"is",
">",
"=",
"0",
".",
"8b",
"or",
"==",
"0",
".",
"6",
".",
"1",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L204-L219 |
226,351 | GNS3/gns3-server | gns3server/compute/vpcs/vpcs_vm.py | VPCSVM.start | def start(self):
"""
Starts the VPCS process.
"""
yield from self._check_requirements()
if not self.is_running():
nio = self._ethernet_adapter.get_nio(0)
command = self._build_command()
try:
log.info("Starting VPCS: {}".format(command))
self._vpcs_stdout_file = os.path.join(self.working_dir, "vpcs.log")
log.info("Logging to {}".format(self._vpcs_stdout_file))
flags = 0
if sys.platform.startswith("win32"):
flags = subprocess.CREATE_NEW_PROCESS_GROUP
with open(self._vpcs_stdout_file, "w", encoding="utf-8") as fd:
self.command_line = ' '.join(command)
self._process = yield from asyncio.create_subprocess_exec(*command,
stdout=fd,
stderr=subprocess.STDOUT,
cwd=self.working_dir,
creationflags=flags)
monitor_process(self._process, self._termination_callback)
yield from self._start_ubridge()
if nio:
yield from self.add_ubridge_udp_connection("VPCS-{}".format(self._id), self._local_udp_tunnel[1], nio)
yield from self.start_wrap_console()
log.info("VPCS instance {} started PID={}".format(self.name, self._process.pid))
self._started = True
self.status = "started"
except (OSError, subprocess.SubprocessError) as e:
vpcs_stdout = self.read_vpcs_stdout()
log.error("Could not start VPCS {}: {}\n{}".format(self._vpcs_path(), e, vpcs_stdout))
raise VPCSError("Could not start VPCS {}: {}\n{}".format(self._vpcs_path(), e, vpcs_stdout)) | python | def start(self):
"""
Starts the VPCS process.
"""
yield from self._check_requirements()
if not self.is_running():
nio = self._ethernet_adapter.get_nio(0)
command = self._build_command()
try:
log.info("Starting VPCS: {}".format(command))
self._vpcs_stdout_file = os.path.join(self.working_dir, "vpcs.log")
log.info("Logging to {}".format(self._vpcs_stdout_file))
flags = 0
if sys.platform.startswith("win32"):
flags = subprocess.CREATE_NEW_PROCESS_GROUP
with open(self._vpcs_stdout_file, "w", encoding="utf-8") as fd:
self.command_line = ' '.join(command)
self._process = yield from asyncio.create_subprocess_exec(*command,
stdout=fd,
stderr=subprocess.STDOUT,
cwd=self.working_dir,
creationflags=flags)
monitor_process(self._process, self._termination_callback)
yield from self._start_ubridge()
if nio:
yield from self.add_ubridge_udp_connection("VPCS-{}".format(self._id), self._local_udp_tunnel[1], nio)
yield from self.start_wrap_console()
log.info("VPCS instance {} started PID={}".format(self.name, self._process.pid))
self._started = True
self.status = "started"
except (OSError, subprocess.SubprocessError) as e:
vpcs_stdout = self.read_vpcs_stdout()
log.error("Could not start VPCS {}: {}\n{}".format(self._vpcs_path(), e, vpcs_stdout))
raise VPCSError("Could not start VPCS {}: {}\n{}".format(self._vpcs_path(), e, vpcs_stdout)) | [
"def",
"start",
"(",
"self",
")",
":",
"yield",
"from",
"self",
".",
"_check_requirements",
"(",
")",
"if",
"not",
"self",
".",
"is_running",
"(",
")",
":",
"nio",
"=",
"self",
".",
"_ethernet_adapter",
".",
"get_nio",
"(",
"0",
")",
"command",
"=",
... | Starts the VPCS process. | [
"Starts",
"the",
"VPCS",
"process",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L222-L259 |
226,352 | GNS3/gns3-server | gns3server/compute/vpcs/vpcs_vm.py | VPCSVM.stop | def stop(self):
"""
Stops the VPCS process.
"""
yield from self._stop_ubridge()
if self.is_running():
self._terminate_process()
if self._process.returncode is None:
try:
yield from wait_for_process_termination(self._process, timeout=3)
except asyncio.TimeoutError:
if self._process.returncode is None:
try:
self._process.kill()
except OSError as e:
log.error("Cannot stop the VPCS process: {}".format(e))
if self._process.returncode is None:
log.warn('VPCS VM "{}" with PID={} is still running'.format(self._name, self._process.pid))
self._process = None
self._started = False
yield from super().stop() | python | def stop(self):
"""
Stops the VPCS process.
"""
yield from self._stop_ubridge()
if self.is_running():
self._terminate_process()
if self._process.returncode is None:
try:
yield from wait_for_process_termination(self._process, timeout=3)
except asyncio.TimeoutError:
if self._process.returncode is None:
try:
self._process.kill()
except OSError as e:
log.error("Cannot stop the VPCS process: {}".format(e))
if self._process.returncode is None:
log.warn('VPCS VM "{}" with PID={} is still running'.format(self._name, self._process.pid))
self._process = None
self._started = False
yield from super().stop() | [
"def",
"stop",
"(",
"self",
")",
":",
"yield",
"from",
"self",
".",
"_stop_ubridge",
"(",
")",
"if",
"self",
".",
"is_running",
"(",
")",
":",
"self",
".",
"_terminate_process",
"(",
")",
"if",
"self",
".",
"_process",
".",
"returncode",
"is",
"None",
... | Stops the VPCS process. | [
"Stops",
"the",
"VPCS",
"process",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L276-L298 |
226,353 | GNS3/gns3-server | gns3server/compute/vpcs/vpcs_vm.py | VPCSVM._terminate_process | def _terminate_process(self):
"""
Terminate the process if running
"""
log.info("Stopping VPCS instance {} PID={}".format(self.name, self._process.pid))
if sys.platform.startswith("win32"):
self._process.send_signal(signal.CTRL_BREAK_EVENT)
else:
try:
self._process.terminate()
# Sometime the process may already be dead when we garbage collect
except ProcessLookupError:
pass | python | def _terminate_process(self):
"""
Terminate the process if running
"""
log.info("Stopping VPCS instance {} PID={}".format(self.name, self._process.pid))
if sys.platform.startswith("win32"):
self._process.send_signal(signal.CTRL_BREAK_EVENT)
else:
try:
self._process.terminate()
# Sometime the process may already be dead when we garbage collect
except ProcessLookupError:
pass | [
"def",
"_terminate_process",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"\"Stopping VPCS instance {} PID={}\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"self",
".",
"_process",
".",
"pid",
")",
")",
"if",
"sys",
".",
"platform",
".",
"startswith... | Terminate the process if running | [
"Terminate",
"the",
"process",
"if",
"running"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L309-L322 |
226,354 | GNS3/gns3-server | gns3server/compute/vpcs/vpcs_vm.py | VPCSVM.read_vpcs_stdout | def read_vpcs_stdout(self):
"""
Reads the standard output of the VPCS process.
Only use when the process has been stopped or has crashed.
"""
output = ""
if self._vpcs_stdout_file:
try:
with open(self._vpcs_stdout_file, "rb") as file:
output = file.read().decode("utf-8", errors="replace")
except OSError as e:
log.warn("Could not read {}: {}".format(self._vpcs_stdout_file, e))
return output | python | def read_vpcs_stdout(self):
"""
Reads the standard output of the VPCS process.
Only use when the process has been stopped or has crashed.
"""
output = ""
if self._vpcs_stdout_file:
try:
with open(self._vpcs_stdout_file, "rb") as file:
output = file.read().decode("utf-8", errors="replace")
except OSError as e:
log.warn("Could not read {}: {}".format(self._vpcs_stdout_file, e))
return output | [
"def",
"read_vpcs_stdout",
"(",
"self",
")",
":",
"output",
"=",
"\"\"",
"if",
"self",
".",
"_vpcs_stdout_file",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"_vpcs_stdout_file",
",",
"\"rb\"",
")",
"as",
"file",
":",
"output",
"=",
"file",
".",
... | Reads the standard output of the VPCS process.
Only use when the process has been stopped or has crashed. | [
"Reads",
"the",
"standard",
"output",
"of",
"the",
"VPCS",
"process",
".",
"Only",
"use",
"when",
"the",
"process",
"has",
"been",
"stopped",
"or",
"has",
"crashed",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L324-L337 |
226,355 | GNS3/gns3-server | gns3server/compute/vpcs/vpcs_vm.py | VPCSVM.script_file | def script_file(self):
"""
Returns the startup script file for this VPCS VM.
:returns: path to startup script file
"""
# use the default VPCS file if it exists
path = os.path.join(self.working_dir, 'startup.vpc')
if os.path.exists(path):
return path
else:
return None | python | def script_file(self):
"""
Returns the startup script file for this VPCS VM.
:returns: path to startup script file
"""
# use the default VPCS file if it exists
path = os.path.join(self.working_dir, 'startup.vpc')
if os.path.exists(path):
return path
else:
return None | [
"def",
"script_file",
"(",
"self",
")",
":",
"# use the default VPCS file if it exists",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"working_dir",
",",
"'startup.vpc'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",... | Returns the startup script file for this VPCS VM.
:returns: path to startup script file | [
"Returns",
"the",
"startup",
"script",
"file",
"for",
"this",
"VPCS",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L539-L551 |
226,356 | GNS3/gns3-server | gns3server/utils/interfaces.py | get_windows_interfaces | def get_windows_interfaces():
"""
Get Windows interfaces.
:returns: list of windows interfaces
"""
import win32com.client
import pywintypes
interfaces = []
try:
locator = win32com.client.Dispatch("WbemScripting.SWbemLocator")
service = locator.ConnectServer(".", "root\cimv2")
network_configs = service.InstancesOf("Win32_NetworkAdapterConfiguration")
# more info on Win32_NetworkAdapter: http://msdn.microsoft.com/en-us/library/aa394216%28v=vs.85%29.aspx
for adapter in service.InstancesOf("Win32_NetworkAdapter"):
if adapter.NetConnectionStatus == 2 or adapter.NetConnectionStatus == 7:
# adapter is connected or media disconnected
ip_address = ""
netmask = ""
for network_config in network_configs:
if network_config.InterfaceIndex == adapter.InterfaceIndex:
if network_config.IPAddress:
# get the first IPv4 address only
ip_address = network_config.IPAddress[0]
netmask = network_config.IPSubnet[0]
break
npf_interface = "\\Device\\NPF_{guid}".format(guid=adapter.GUID)
interfaces.append({"id": npf_interface,
"name": adapter.NetConnectionID,
"ip_address": ip_address,
"mac_address": adapter.MACAddress,
"netcard": adapter.name,
"netmask": netmask,
"type": "ethernet"})
except (AttributeError, pywintypes.com_error):
log.warn("Could not use the COM service to retrieve interface info, trying using the registry...")
return _get_windows_interfaces_from_registry()
return interfaces | python | def get_windows_interfaces():
"""
Get Windows interfaces.
:returns: list of windows interfaces
"""
import win32com.client
import pywintypes
interfaces = []
try:
locator = win32com.client.Dispatch("WbemScripting.SWbemLocator")
service = locator.ConnectServer(".", "root\cimv2")
network_configs = service.InstancesOf("Win32_NetworkAdapterConfiguration")
# more info on Win32_NetworkAdapter: http://msdn.microsoft.com/en-us/library/aa394216%28v=vs.85%29.aspx
for adapter in service.InstancesOf("Win32_NetworkAdapter"):
if adapter.NetConnectionStatus == 2 or adapter.NetConnectionStatus == 7:
# adapter is connected or media disconnected
ip_address = ""
netmask = ""
for network_config in network_configs:
if network_config.InterfaceIndex == adapter.InterfaceIndex:
if network_config.IPAddress:
# get the first IPv4 address only
ip_address = network_config.IPAddress[0]
netmask = network_config.IPSubnet[0]
break
npf_interface = "\\Device\\NPF_{guid}".format(guid=adapter.GUID)
interfaces.append({"id": npf_interface,
"name": adapter.NetConnectionID,
"ip_address": ip_address,
"mac_address": adapter.MACAddress,
"netcard": adapter.name,
"netmask": netmask,
"type": "ethernet"})
except (AttributeError, pywintypes.com_error):
log.warn("Could not use the COM service to retrieve interface info, trying using the registry...")
return _get_windows_interfaces_from_registry()
return interfaces | [
"def",
"get_windows_interfaces",
"(",
")",
":",
"import",
"win32com",
".",
"client",
"import",
"pywintypes",
"interfaces",
"=",
"[",
"]",
"try",
":",
"locator",
"=",
"win32com",
".",
"client",
".",
"Dispatch",
"(",
"\"WbemScripting.SWbemLocator\"",
")",
"service... | Get Windows interfaces.
:returns: list of windows interfaces | [
"Get",
"Windows",
"interfaces",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/interfaces.py#L79-L119 |
226,357 | GNS3/gns3-server | gns3server/utils/interfaces.py | has_netmask | def has_netmask(interface_name):
"""
Checks if an interface has a netmask.
:param interface: interface name
:returns: boolean
"""
for interface in interfaces():
if interface["name"] == interface_name:
if interface["netmask"] and len(interface["netmask"]) > 0:
return True
return False
return False | python | def has_netmask(interface_name):
"""
Checks if an interface has a netmask.
:param interface: interface name
:returns: boolean
"""
for interface in interfaces():
if interface["name"] == interface_name:
if interface["netmask"] and len(interface["netmask"]) > 0:
return True
return False
return False | [
"def",
"has_netmask",
"(",
"interface_name",
")",
":",
"for",
"interface",
"in",
"interfaces",
"(",
")",
":",
"if",
"interface",
"[",
"\"name\"",
"]",
"==",
"interface_name",
":",
"if",
"interface",
"[",
"\"netmask\"",
"]",
"and",
"len",
"(",
"interface",
... | Checks if an interface has a netmask.
:param interface: interface name
:returns: boolean | [
"Checks",
"if",
"an",
"interface",
"has",
"a",
"netmask",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/interfaces.py#L122-L135 |
226,358 | GNS3/gns3-server | gns3server/utils/interfaces.py | is_interface_up | def is_interface_up(interface):
"""
Checks if an interface is up.
:param interface: interface name
:returns: boolean
"""
if sys.platform.startswith("linux"):
if interface not in psutil.net_if_addrs():
return False
import fcntl
SIOCGIFFLAGS = 0x8913
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
result = fcntl.ioctl(s.fileno(), SIOCGIFFLAGS, interface + '\0' * 256)
flags, = struct.unpack('H', result[16:18])
if flags & 1: # check if the up bit is set
return True
return False
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Exception when checking if {} is up: {}".format(interface, e))
else:
# TODO: Windows & OSX support
return True | python | def is_interface_up(interface):
"""
Checks if an interface is up.
:param interface: interface name
:returns: boolean
"""
if sys.platform.startswith("linux"):
if interface not in psutil.net_if_addrs():
return False
import fcntl
SIOCGIFFLAGS = 0x8913
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
result = fcntl.ioctl(s.fileno(), SIOCGIFFLAGS, interface + '\0' * 256)
flags, = struct.unpack('H', result[16:18])
if flags & 1: # check if the up bit is set
return True
return False
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Exception when checking if {} is up: {}".format(interface, e))
else:
# TODO: Windows & OSX support
return True | [
"def",
"is_interface_up",
"(",
"interface",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"linux\"",
")",
":",
"if",
"interface",
"not",
"in",
"psutil",
".",
"net_if_addrs",
"(",
")",
":",
"return",
"False",
"import",
"fcntl",
"SIOCGIFF... | Checks if an interface is up.
:param interface: interface name
:returns: boolean | [
"Checks",
"if",
"an",
"interface",
"is",
"up",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/interfaces.py#L138-L165 |
226,359 | GNS3/gns3-server | gns3server/utils/interfaces.py | interfaces | def interfaces():
"""
Gets the network interfaces on this server.
:returns: list of network interfaces
"""
results = []
if not sys.platform.startswith("win"):
net_if_addrs = psutil.net_if_addrs()
for interface in sorted(net_if_addrs.keys()):
ip_address = ""
mac_address = ""
netmask = ""
interface_type = "ethernet"
for addr in net_if_addrs[interface]:
# get the first available IPv4 address only
if addr.family == socket.AF_INET:
ip_address = addr.address
netmask = addr.netmask
if addr.family == psutil.AF_LINK:
mac_address = addr.address
if interface.startswith("tap"):
# found no way to reliably detect a TAP interface
interface_type = "tap"
results.append({"id": interface,
"name": interface,
"ip_address": ip_address,
"netmask": netmask,
"mac_address": mac_address,
"type": interface_type})
else:
try:
service_installed = True
if not _check_windows_service("npf") and not _check_windows_service("npcap"):
service_installed = False
else:
results = get_windows_interfaces()
except ImportError:
message = "pywin32 module is not installed, please install it on the server to get the available interface names"
raise aiohttp.web.HTTPInternalServerError(text=message)
except Exception as e:
log.error("uncaught exception {type}".format(type=type(e)), exc_info=1)
raise aiohttp.web.HTTPInternalServerError(text="uncaught exception: {}".format(e))
if service_installed is False:
raise aiohttp.web.HTTPInternalServerError(text="The Winpcap or Npcap is not installed or running")
# This interface have special behavior
for result in results:
result["special"] = False
for special_interface in ("lo", "vmnet", "vboxnet", "docker", "lxcbr",
"virbr", "ovs-system", "veth", "fw", "p2p",
"bridge", "vmware", "virtualbox", "gns3"):
if result["name"].lower().startswith(special_interface):
result["special"] = True
for special_interface in ("-nic"):
if result["name"].lower().endswith(special_interface):
result["special"] = True
return results | python | def interfaces():
"""
Gets the network interfaces on this server.
:returns: list of network interfaces
"""
results = []
if not sys.platform.startswith("win"):
net_if_addrs = psutil.net_if_addrs()
for interface in sorted(net_if_addrs.keys()):
ip_address = ""
mac_address = ""
netmask = ""
interface_type = "ethernet"
for addr in net_if_addrs[interface]:
# get the first available IPv4 address only
if addr.family == socket.AF_INET:
ip_address = addr.address
netmask = addr.netmask
if addr.family == psutil.AF_LINK:
mac_address = addr.address
if interface.startswith("tap"):
# found no way to reliably detect a TAP interface
interface_type = "tap"
results.append({"id": interface,
"name": interface,
"ip_address": ip_address,
"netmask": netmask,
"mac_address": mac_address,
"type": interface_type})
else:
try:
service_installed = True
if not _check_windows_service("npf") and not _check_windows_service("npcap"):
service_installed = False
else:
results = get_windows_interfaces()
except ImportError:
message = "pywin32 module is not installed, please install it on the server to get the available interface names"
raise aiohttp.web.HTTPInternalServerError(text=message)
except Exception as e:
log.error("uncaught exception {type}".format(type=type(e)), exc_info=1)
raise aiohttp.web.HTTPInternalServerError(text="uncaught exception: {}".format(e))
if service_installed is False:
raise aiohttp.web.HTTPInternalServerError(text="The Winpcap or Npcap is not installed or running")
# This interface have special behavior
for result in results:
result["special"] = False
for special_interface in ("lo", "vmnet", "vboxnet", "docker", "lxcbr",
"virbr", "ovs-system", "veth", "fw", "p2p",
"bridge", "vmware", "virtualbox", "gns3"):
if result["name"].lower().startswith(special_interface):
result["special"] = True
for special_interface in ("-nic"):
if result["name"].lower().endswith(special_interface):
result["special"] = True
return results | [
"def",
"interfaces",
"(",
")",
":",
"results",
"=",
"[",
"]",
"if",
"not",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"net_if_addrs",
"=",
"psutil",
".",
"net_if_addrs",
"(",
")",
"for",
"interface",
"in",
"sorted",
"(",
"net_... | Gets the network interfaces on this server.
:returns: list of network interfaces | [
"Gets",
"the",
"network",
"interfaces",
"on",
"this",
"server",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/interfaces.py#L192-L251 |
226,360 | GNS3/gns3-server | gns3server/controller/gns3vm/vmware_gns3_vm.py | VMwareGNS3VM._set_vcpus_ram | def _set_vcpus_ram(self, vcpus, ram):
"""
Set the number of vCPU cores and amount of RAM for the GNS3 VM.
:param vcpus: number of vCPU cores
:param ram: amount of RAM
"""
# memory must be a multiple of 4 (VMware requirement)
if ram % 4 != 0:
raise GNS3VMError("Allocated memory {} for the GNS3 VM must be a multiple of 4".format(ram))
available_vcpus = psutil.cpu_count(logical=False)
if vcpus > available_vcpus:
raise GNS3VMError("You have allocated too many vCPUs for the GNS3 VM! (max available is {} vCPUs)".format(available_vcpus))
try:
pairs = VMware.parse_vmware_file(self._vmx_path)
pairs["numvcpus"] = str(vcpus)
pairs["memsize"] = str(ram)
VMware.write_vmx_file(self._vmx_path, pairs)
log.info("GNS3 VM vCPU count set to {} and RAM amount set to {}".format(vcpus, ram))
except OSError as e:
raise GNS3VMError('Could not read/write VMware VMX file "{}": {}'.format(self._vmx_path, e)) | python | def _set_vcpus_ram(self, vcpus, ram):
"""
Set the number of vCPU cores and amount of RAM for the GNS3 VM.
:param vcpus: number of vCPU cores
:param ram: amount of RAM
"""
# memory must be a multiple of 4 (VMware requirement)
if ram % 4 != 0:
raise GNS3VMError("Allocated memory {} for the GNS3 VM must be a multiple of 4".format(ram))
available_vcpus = psutil.cpu_count(logical=False)
if vcpus > available_vcpus:
raise GNS3VMError("You have allocated too many vCPUs for the GNS3 VM! (max available is {} vCPUs)".format(available_vcpus))
try:
pairs = VMware.parse_vmware_file(self._vmx_path)
pairs["numvcpus"] = str(vcpus)
pairs["memsize"] = str(ram)
VMware.write_vmx_file(self._vmx_path, pairs)
log.info("GNS3 VM vCPU count set to {} and RAM amount set to {}".format(vcpus, ram))
except OSError as e:
raise GNS3VMError('Could not read/write VMware VMX file "{}": {}'.format(self._vmx_path, e)) | [
"def",
"_set_vcpus_ram",
"(",
"self",
",",
"vcpus",
",",
"ram",
")",
":",
"# memory must be a multiple of 4 (VMware requirement)",
"if",
"ram",
"%",
"4",
"!=",
"0",
":",
"raise",
"GNS3VMError",
"(",
"\"Allocated memory {} for the GNS3 VM must be a multiple of 4\"",
".",
... | Set the number of vCPU cores and amount of RAM for the GNS3 VM.
:param vcpus: number of vCPU cores
:param ram: amount of RAM | [
"Set",
"the",
"number",
"of",
"vCPU",
"cores",
"and",
"amount",
"of",
"RAM",
"for",
"the",
"GNS3",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/vmware_gns3_vm.py#L63-L86 |
226,361 | GNS3/gns3-server | gns3server/controller/gns3vm/vmware_gns3_vm.py | VMwareGNS3VM.list | def list(self):
"""
List all VMware VMs
"""
try:
return (yield from self._vmware_manager.list_vms())
except VMwareError as e:
raise GNS3VMError("Could not list VMware VMs: {}".format(str(e))) | python | def list(self):
"""
List all VMware VMs
"""
try:
return (yield from self._vmware_manager.list_vms())
except VMwareError as e:
raise GNS3VMError("Could not list VMware VMs: {}".format(str(e))) | [
"def",
"list",
"(",
"self",
")",
":",
"try",
":",
"return",
"(",
"yield",
"from",
"self",
".",
"_vmware_manager",
".",
"list_vms",
"(",
")",
")",
"except",
"VMwareError",
"as",
"e",
":",
"raise",
"GNS3VMError",
"(",
"\"Could not list VMware VMs: {}\"",
".",
... | List all VMware VMs | [
"List",
"all",
"VMware",
"VMs"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/vmware_gns3_vm.py#L113-L120 |
226,362 | GNS3/gns3-server | gns3server/compute/vmware/vmware_vm.py | VMwareVM._read_vmx_file | def _read_vmx_file(self):
"""
Reads from the VMware VMX file corresponding to this VM.
"""
try:
self._vmx_pairs = self.manager.parse_vmware_file(self._vmx_path)
except OSError as e:
raise VMwareError('Could not read VMware VMX file "{}": {}'.format(self._vmx_path, e)) | python | def _read_vmx_file(self):
"""
Reads from the VMware VMX file corresponding to this VM.
"""
try:
self._vmx_pairs = self.manager.parse_vmware_file(self._vmx_path)
except OSError as e:
raise VMwareError('Could not read VMware VMX file "{}": {}'.format(self._vmx_path, e)) | [
"def",
"_read_vmx_file",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_vmx_pairs",
"=",
"self",
".",
"manager",
".",
"parse_vmware_file",
"(",
"self",
".",
"_vmx_path",
")",
"except",
"OSError",
"as",
"e",
":",
"raise",
"VMwareError",
"(",
"'Could not ... | Reads from the VMware VMX file corresponding to this VM. | [
"Reads",
"from",
"the",
"VMware",
"VMX",
"file",
"corresponding",
"to",
"this",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L107-L115 |
226,363 | GNS3/gns3-server | gns3server/compute/vmware/vmware_vm.py | VMwareVM._write_vmx_file | def _write_vmx_file(self):
"""
Writes pairs to the VMware VMX file corresponding to this VM.
"""
try:
self.manager.write_vmx_file(self._vmx_path, self._vmx_pairs)
except OSError as e:
raise VMwareError('Could not write VMware VMX file "{}": {}'.format(self._vmx_path, e)) | python | def _write_vmx_file(self):
"""
Writes pairs to the VMware VMX file corresponding to this VM.
"""
try:
self.manager.write_vmx_file(self._vmx_path, self._vmx_pairs)
except OSError as e:
raise VMwareError('Could not write VMware VMX file "{}": {}'.format(self._vmx_path, e)) | [
"def",
"_write_vmx_file",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"manager",
".",
"write_vmx_file",
"(",
"self",
".",
"_vmx_path",
",",
"self",
".",
"_vmx_pairs",
")",
"except",
"OSError",
"as",
"e",
":",
"raise",
"VMwareError",
"(",
"'Could not wr... | Writes pairs to the VMware VMX file corresponding to this VM. | [
"Writes",
"pairs",
"to",
"the",
"VMware",
"VMX",
"file",
"corresponding",
"to",
"this",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L117-L125 |
226,364 | GNS3/gns3-server | gns3server/compute/vmware/vmware_vm.py | VMwareVM.create | def create(self):
"""
Creates this VM and handle linked clones.
"""
if not self.linked_clone:
yield from self._check_duplicate_linked_clone()
yield from self.manager.check_vmrun_version()
if self.linked_clone and not os.path.exists(os.path.join(self.working_dir, os.path.basename(self._vmx_path))):
if self.manager.host_type == "player":
raise VMwareError("Linked clones are not supported by VMware Player")
# create the base snapshot for linked clones
base_snapshot_name = "GNS3 Linked Base for clones"
vmsd_path = os.path.splitext(self._vmx_path)[0] + ".vmsd"
if not os.path.exists(vmsd_path):
raise VMwareError("{} doesn't not exist".format(vmsd_path))
try:
vmsd_pairs = self.manager.parse_vmware_file(vmsd_path)
except OSError as e:
raise VMwareError('Could not read VMware VMSD file "{}": {}'.format(vmsd_path, e))
gns3_snapshot_exists = False
for value in vmsd_pairs.values():
if value == base_snapshot_name:
gns3_snapshot_exists = True
break
if not gns3_snapshot_exists:
log.info("Creating snapshot '{}'".format(base_snapshot_name))
yield from self._control_vm("snapshot", base_snapshot_name)
# create the linked clone based on the base snapshot
new_vmx_path = os.path.join(self.working_dir, self.name + ".vmx")
yield from self._control_vm("clone",
new_vmx_path,
"linked",
"-snapshot={}".format(base_snapshot_name),
"-cloneName={}".format(self.name))
try:
vmsd_pairs = self.manager.parse_vmware_file(vmsd_path)
except OSError as e:
raise VMwareError('Could not read VMware VMSD file "{}": {}'.format(vmsd_path, e))
snapshot_name = None
for name, value in vmsd_pairs.items():
if value == base_snapshot_name:
snapshot_name = name.split(".", 1)[0]
break
if snapshot_name is None:
raise VMwareError("Could not find the linked base snapshot in {}".format(vmsd_path))
num_clones_entry = "{}.numClones".format(snapshot_name)
if num_clones_entry in vmsd_pairs:
try:
nb_of_clones = int(vmsd_pairs[num_clones_entry])
except ValueError:
raise VMwareError("Value of {} in {} is not a number".format(num_clones_entry, vmsd_path))
vmsd_pairs[num_clones_entry] = str(nb_of_clones - 1)
for clone_nb in range(0, nb_of_clones):
clone_entry = "{}.clone{}".format(snapshot_name, clone_nb)
if clone_entry in vmsd_pairs:
del vmsd_pairs[clone_entry]
try:
self.manager.write_vmware_file(vmsd_path, vmsd_pairs)
except OSError as e:
raise VMwareError('Could not write VMware VMSD file "{}": {}'.format(vmsd_path, e))
# update the VMX file path
self._vmx_path = new_vmx_path | python | def create(self):
"""
Creates this VM and handle linked clones.
"""
if not self.linked_clone:
yield from self._check_duplicate_linked_clone()
yield from self.manager.check_vmrun_version()
if self.linked_clone and not os.path.exists(os.path.join(self.working_dir, os.path.basename(self._vmx_path))):
if self.manager.host_type == "player":
raise VMwareError("Linked clones are not supported by VMware Player")
# create the base snapshot for linked clones
base_snapshot_name = "GNS3 Linked Base for clones"
vmsd_path = os.path.splitext(self._vmx_path)[0] + ".vmsd"
if not os.path.exists(vmsd_path):
raise VMwareError("{} doesn't not exist".format(vmsd_path))
try:
vmsd_pairs = self.manager.parse_vmware_file(vmsd_path)
except OSError as e:
raise VMwareError('Could not read VMware VMSD file "{}": {}'.format(vmsd_path, e))
gns3_snapshot_exists = False
for value in vmsd_pairs.values():
if value == base_snapshot_name:
gns3_snapshot_exists = True
break
if not gns3_snapshot_exists:
log.info("Creating snapshot '{}'".format(base_snapshot_name))
yield from self._control_vm("snapshot", base_snapshot_name)
# create the linked clone based on the base snapshot
new_vmx_path = os.path.join(self.working_dir, self.name + ".vmx")
yield from self._control_vm("clone",
new_vmx_path,
"linked",
"-snapshot={}".format(base_snapshot_name),
"-cloneName={}".format(self.name))
try:
vmsd_pairs = self.manager.parse_vmware_file(vmsd_path)
except OSError as e:
raise VMwareError('Could not read VMware VMSD file "{}": {}'.format(vmsd_path, e))
snapshot_name = None
for name, value in vmsd_pairs.items():
if value == base_snapshot_name:
snapshot_name = name.split(".", 1)[0]
break
if snapshot_name is None:
raise VMwareError("Could not find the linked base snapshot in {}".format(vmsd_path))
num_clones_entry = "{}.numClones".format(snapshot_name)
if num_clones_entry in vmsd_pairs:
try:
nb_of_clones = int(vmsd_pairs[num_clones_entry])
except ValueError:
raise VMwareError("Value of {} in {} is not a number".format(num_clones_entry, vmsd_path))
vmsd_pairs[num_clones_entry] = str(nb_of_clones - 1)
for clone_nb in range(0, nb_of_clones):
clone_entry = "{}.clone{}".format(snapshot_name, clone_nb)
if clone_entry in vmsd_pairs:
del vmsd_pairs[clone_entry]
try:
self.manager.write_vmware_file(vmsd_path, vmsd_pairs)
except OSError as e:
raise VMwareError('Could not write VMware VMSD file "{}": {}'.format(vmsd_path, e))
# update the VMX file path
self._vmx_path = new_vmx_path | [
"def",
"create",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"linked_clone",
":",
"yield",
"from",
"self",
".",
"_check_duplicate_linked_clone",
"(",
")",
"yield",
"from",
"self",
".",
"manager",
".",
"check_vmrun_version",
"(",
")",
"if",
"self",
"."... | Creates this VM and handle linked clones. | [
"Creates",
"this",
"VM",
"and",
"handle",
"linked",
"clones",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L163-L233 |
226,365 | GNS3/gns3-server | gns3server/compute/vmware/vmware_vm.py | VMwareVM._set_network_options | def _set_network_options(self):
"""
Set up VMware networking.
"""
# first some sanity checks
for adapter_number in range(0, self._adapters):
# we want the vmnet interface to be connected when starting the VM
connected = "ethernet{}.startConnected".format(adapter_number)
if self._get_vmx_setting(connected):
del self._vmx_pairs[connected]
# then configure VMware network adapters
self.manager.refresh_vmnet_list()
for adapter_number in range(0, self._adapters):
# add/update the interface
if self._adapter_type == "default":
# force default to e1000 because some guest OS don't detect the adapter (i.e. Windows 2012 server)
# when 'virtualdev' is not set in the VMX file.
adapter_type = "e1000"
else:
adapter_type = self._adapter_type
ethernet_adapter = {"ethernet{}.present".format(adapter_number): "TRUE",
"ethernet{}.addresstype".format(adapter_number): "generated",
"ethernet{}.generatedaddressoffset".format(adapter_number): "0",
"ethernet{}.virtualdev".format(adapter_number): adapter_type}
self._vmx_pairs.update(ethernet_adapter)
connection_type = "ethernet{}.connectiontype".format(adapter_number)
if not self._use_any_adapter and connection_type in self._vmx_pairs and self._vmx_pairs[connection_type] in ("nat", "bridged", "hostonly"):
continue
self._vmx_pairs["ethernet{}.connectiontype".format(adapter_number)] = "custom"
# make sure we have a vmnet per adapter if we use uBridge
allocate_vmnet = False
# first check if a vmnet is already assigned to the adapter
vnet = "ethernet{}.vnet".format(adapter_number)
if vnet in self._vmx_pairs:
vmnet = os.path.basename(self._vmx_pairs[vnet])
if self.manager.is_managed_vmnet(vmnet) or vmnet in ("vmnet0", "vmnet1", "vmnet8"):
# vmnet already managed, try to allocate a new one
allocate_vmnet = True
else:
# otherwise allocate a new one
allocate_vmnet = True
if allocate_vmnet:
try:
vmnet = self.manager.allocate_vmnet()
except BaseException:
# clear everything up in case of error (e.g. no enough vmnets)
self._vmnets.clear()
raise
# mark the vmnet managed by us
if vmnet not in self._vmnets:
self._vmnets.append(vmnet)
self._vmx_pairs["ethernet{}.vnet".format(adapter_number)] = vmnet
# disable remaining network adapters
for adapter_number in range(self._adapters, self._maximum_adapters):
if self._get_vmx_setting("ethernet{}.present".format(adapter_number), "TRUE"):
log.debug("disabling remaining adapter {}".format(adapter_number))
self._vmx_pairs["ethernet{}.startconnected".format(adapter_number)] = "FALSE" | python | def _set_network_options(self):
"""
Set up VMware networking.
"""
# first some sanity checks
for adapter_number in range(0, self._adapters):
# we want the vmnet interface to be connected when starting the VM
connected = "ethernet{}.startConnected".format(adapter_number)
if self._get_vmx_setting(connected):
del self._vmx_pairs[connected]
# then configure VMware network adapters
self.manager.refresh_vmnet_list()
for adapter_number in range(0, self._adapters):
# add/update the interface
if self._adapter_type == "default":
# force default to e1000 because some guest OS don't detect the adapter (i.e. Windows 2012 server)
# when 'virtualdev' is not set in the VMX file.
adapter_type = "e1000"
else:
adapter_type = self._adapter_type
ethernet_adapter = {"ethernet{}.present".format(adapter_number): "TRUE",
"ethernet{}.addresstype".format(adapter_number): "generated",
"ethernet{}.generatedaddressoffset".format(adapter_number): "0",
"ethernet{}.virtualdev".format(adapter_number): adapter_type}
self._vmx_pairs.update(ethernet_adapter)
connection_type = "ethernet{}.connectiontype".format(adapter_number)
if not self._use_any_adapter and connection_type in self._vmx_pairs and self._vmx_pairs[connection_type] in ("nat", "bridged", "hostonly"):
continue
self._vmx_pairs["ethernet{}.connectiontype".format(adapter_number)] = "custom"
# make sure we have a vmnet per adapter if we use uBridge
allocate_vmnet = False
# first check if a vmnet is already assigned to the adapter
vnet = "ethernet{}.vnet".format(adapter_number)
if vnet in self._vmx_pairs:
vmnet = os.path.basename(self._vmx_pairs[vnet])
if self.manager.is_managed_vmnet(vmnet) or vmnet in ("vmnet0", "vmnet1", "vmnet8"):
# vmnet already managed, try to allocate a new one
allocate_vmnet = True
else:
# otherwise allocate a new one
allocate_vmnet = True
if allocate_vmnet:
try:
vmnet = self.manager.allocate_vmnet()
except BaseException:
# clear everything up in case of error (e.g. no enough vmnets)
self._vmnets.clear()
raise
# mark the vmnet managed by us
if vmnet not in self._vmnets:
self._vmnets.append(vmnet)
self._vmx_pairs["ethernet{}.vnet".format(adapter_number)] = vmnet
# disable remaining network adapters
for adapter_number in range(self._adapters, self._maximum_adapters):
if self._get_vmx_setting("ethernet{}.present".format(adapter_number), "TRUE"):
log.debug("disabling remaining adapter {}".format(adapter_number))
self._vmx_pairs["ethernet{}.startconnected".format(adapter_number)] = "FALSE" | [
"def",
"_set_network_options",
"(",
"self",
")",
":",
"# first some sanity checks",
"for",
"adapter_number",
"in",
"range",
"(",
"0",
",",
"self",
".",
"_adapters",
")",
":",
"# we want the vmnet interface to be connected when starting the VM",
"connected",
"=",
"\"ethern... | Set up VMware networking. | [
"Set",
"up",
"VMware",
"networking",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L245-L311 |
226,366 | GNS3/gns3-server | gns3server/compute/vmware/vmware_vm.py | VMwareVM._get_vnet | def _get_vnet(self, adapter_number):
"""
Return the vnet will use in ubridge
"""
vnet = "ethernet{}.vnet".format(adapter_number)
if vnet not in self._vmx_pairs:
raise VMwareError("vnet {} not in VMX file".format(vnet))
return vnet | python | def _get_vnet(self, adapter_number):
"""
Return the vnet will use in ubridge
"""
vnet = "ethernet{}.vnet".format(adapter_number)
if vnet not in self._vmx_pairs:
raise VMwareError("vnet {} not in VMX file".format(vnet))
return vnet | [
"def",
"_get_vnet",
"(",
"self",
",",
"adapter_number",
")",
":",
"vnet",
"=",
"\"ethernet{}.vnet\"",
".",
"format",
"(",
"adapter_number",
")",
"if",
"vnet",
"not",
"in",
"self",
".",
"_vmx_pairs",
":",
"raise",
"VMwareError",
"(",
"\"vnet {} not in VMX file\""... | Return the vnet will use in ubridge | [
"Return",
"the",
"vnet",
"will",
"use",
"in",
"ubridge"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L313-L320 |
226,367 | GNS3/gns3-server | gns3server/compute/vmware/vmware_vm.py | VMwareVM._update_ubridge_connection | def _update_ubridge_connection(self, adapter_number, nio):
"""
Update a connection in uBridge.
:param nio: NIO instance
:param adapter_number: adapter number
"""
try:
bridge_name = self._get_vnet(adapter_number)
except VMwareError:
return # vnet not yet available
yield from self._ubridge_apply_filters(bridge_name, nio.filters) | python | def _update_ubridge_connection(self, adapter_number, nio):
"""
Update a connection in uBridge.
:param nio: NIO instance
:param adapter_number: adapter number
"""
try:
bridge_name = self._get_vnet(adapter_number)
except VMwareError:
return # vnet not yet available
yield from self._ubridge_apply_filters(bridge_name, nio.filters) | [
"def",
"_update_ubridge_connection",
"(",
"self",
",",
"adapter_number",
",",
"nio",
")",
":",
"try",
":",
"bridge_name",
"=",
"self",
".",
"_get_vnet",
"(",
"adapter_number",
")",
"except",
"VMwareError",
":",
"return",
"# vnet not yet available",
"yield",
"from"... | Update a connection in uBridge.
:param nio: NIO instance
:param adapter_number: adapter number | [
"Update",
"a",
"connection",
"in",
"uBridge",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L355-L366 |
226,368 | GNS3/gns3-server | gns3server/compute/vmware/vmware_vm.py | VMwareVM.start | def start(self):
"""
Starts this VMware VM.
"""
if self.status == "started":
return
if (yield from self.is_running()):
raise VMwareError("The VM is already running in VMware")
ubridge_path = self.ubridge_path
if not ubridge_path or not os.path.isfile(ubridge_path):
raise VMwareError("ubridge is necessary to start a VMware VM")
yield from self._start_ubridge()
self._read_vmx_file()
# check if there is enough RAM to run
if "memsize" in self._vmx_pairs:
self.check_available_ram(int(self._vmx_pairs["memsize"]))
self._set_network_options()
self._set_serial_console()
self._write_vmx_file()
if self._headless:
yield from self._control_vm("start", "nogui")
else:
yield from self._control_vm("start")
try:
if self._ubridge_hypervisor:
for adapter_number in range(0, self._adapters):
nio = self._ethernet_adapters[adapter_number].get_nio(0)
if nio:
yield from self._add_ubridge_connection(nio, adapter_number)
yield from self._start_console()
except VMwareError:
yield from self.stop()
raise
if self._get_vmx_setting("vhv.enable", "TRUE"):
self._hw_virtualization = True
self._started = True
self.status = "started"
log.info("VMware VM '{name}' [{id}] started".format(name=self.name, id=self.id)) | python | def start(self):
"""
Starts this VMware VM.
"""
if self.status == "started":
return
if (yield from self.is_running()):
raise VMwareError("The VM is already running in VMware")
ubridge_path = self.ubridge_path
if not ubridge_path or not os.path.isfile(ubridge_path):
raise VMwareError("ubridge is necessary to start a VMware VM")
yield from self._start_ubridge()
self._read_vmx_file()
# check if there is enough RAM to run
if "memsize" in self._vmx_pairs:
self.check_available_ram(int(self._vmx_pairs["memsize"]))
self._set_network_options()
self._set_serial_console()
self._write_vmx_file()
if self._headless:
yield from self._control_vm("start", "nogui")
else:
yield from self._control_vm("start")
try:
if self._ubridge_hypervisor:
for adapter_number in range(0, self._adapters):
nio = self._ethernet_adapters[adapter_number].get_nio(0)
if nio:
yield from self._add_ubridge_connection(nio, adapter_number)
yield from self._start_console()
except VMwareError:
yield from self.stop()
raise
if self._get_vmx_setting("vhv.enable", "TRUE"):
self._hw_virtualization = True
self._started = True
self.status = "started"
log.info("VMware VM '{name}' [{id}] started".format(name=self.name, id=self.id)) | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"status",
"==",
"\"started\"",
":",
"return",
"if",
"(",
"yield",
"from",
"self",
".",
"is_running",
"(",
")",
")",
":",
"raise",
"VMwareError",
"(",
"\"The VM is already running in VMware\"",
")",
... | Starts this VMware VM. | [
"Starts",
"this",
"VMware",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L426-L472 |
226,369 | GNS3/gns3-server | gns3server/compute/vmware/vmware_vm.py | VMwareVM.stop | def stop(self):
"""
Stops this VMware VM.
"""
self._hw_virtualization = False
yield from self._stop_remote_console()
yield from self._stop_ubridge()
try:
if (yield from self.is_running()):
if self.acpi_shutdown:
# use ACPI to shutdown the VM
yield from self._control_vm("stop", "soft")
else:
yield from self._control_vm("stop")
finally:
self._started = False
self.status = "stopped"
self._read_vmx_file()
self._vmnets.clear()
# remove the adapters managed by GNS3
for adapter_number in range(0, self._adapters):
vnet = "ethernet{}.vnet".format(adapter_number)
if self._get_vmx_setting(vnet) or self._get_vmx_setting("ethernet{}.connectiontype".format(adapter_number)) is None:
if vnet in self._vmx_pairs:
vmnet = os.path.basename(self._vmx_pairs[vnet])
if not self.manager.is_managed_vmnet(vmnet):
continue
log.debug("removing adapter {}".format(adapter_number))
self._vmx_pairs[vnet] = "vmnet1"
self._vmx_pairs["ethernet{}.connectiontype".format(adapter_number)] = "custom"
# re-enable any remaining network adapters
for adapter_number in range(self._adapters, self._maximum_adapters):
if self._get_vmx_setting("ethernet{}.present".format(adapter_number), "TRUE"):
log.debug("enabling remaining adapter {}".format(adapter_number))
self._vmx_pairs["ethernet{}.startconnected".format(adapter_number)] = "TRUE"
self._write_vmx_file()
yield from super().stop()
log.info("VMware VM '{name}' [{id}] stopped".format(name=self.name, id=self.id)) | python | def stop(self):
"""
Stops this VMware VM.
"""
self._hw_virtualization = False
yield from self._stop_remote_console()
yield from self._stop_ubridge()
try:
if (yield from self.is_running()):
if self.acpi_shutdown:
# use ACPI to shutdown the VM
yield from self._control_vm("stop", "soft")
else:
yield from self._control_vm("stop")
finally:
self._started = False
self.status = "stopped"
self._read_vmx_file()
self._vmnets.clear()
# remove the adapters managed by GNS3
for adapter_number in range(0, self._adapters):
vnet = "ethernet{}.vnet".format(adapter_number)
if self._get_vmx_setting(vnet) or self._get_vmx_setting("ethernet{}.connectiontype".format(adapter_number)) is None:
if vnet in self._vmx_pairs:
vmnet = os.path.basename(self._vmx_pairs[vnet])
if not self.manager.is_managed_vmnet(vmnet):
continue
log.debug("removing adapter {}".format(adapter_number))
self._vmx_pairs[vnet] = "vmnet1"
self._vmx_pairs["ethernet{}.connectiontype".format(adapter_number)] = "custom"
# re-enable any remaining network adapters
for adapter_number in range(self._adapters, self._maximum_adapters):
if self._get_vmx_setting("ethernet{}.present".format(adapter_number), "TRUE"):
log.debug("enabling remaining adapter {}".format(adapter_number))
self._vmx_pairs["ethernet{}.startconnected".format(adapter_number)] = "TRUE"
self._write_vmx_file()
yield from super().stop()
log.info("VMware VM '{name}' [{id}] stopped".format(name=self.name, id=self.id)) | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"_hw_virtualization",
"=",
"False",
"yield",
"from",
"self",
".",
"_stop_remote_console",
"(",
")",
"yield",
"from",
"self",
".",
"_stop_ubridge",
"(",
")",
"try",
":",
"if",
"(",
"yield",
"from",
"self"... | Stops this VMware VM. | [
"Stops",
"this",
"VMware",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L475-L517 |
226,370 | GNS3/gns3-server | gns3server/compute/vmware/vmware_vm.py | VMwareVM.suspend | def suspend(self):
"""
Suspends this VMware VM.
"""
if self.manager.host_type != "ws":
raise VMwareError("Pausing a VM is only supported by VMware Workstation")
yield from self._control_vm("pause")
self.status = "suspended"
log.info("VMware VM '{name}' [{id}] paused".format(name=self.name, id=self.id)) | python | def suspend(self):
"""
Suspends this VMware VM.
"""
if self.manager.host_type != "ws":
raise VMwareError("Pausing a VM is only supported by VMware Workstation")
yield from self._control_vm("pause")
self.status = "suspended"
log.info("VMware VM '{name}' [{id}] paused".format(name=self.name, id=self.id)) | [
"def",
"suspend",
"(",
"self",
")",
":",
"if",
"self",
".",
"manager",
".",
"host_type",
"!=",
"\"ws\"",
":",
"raise",
"VMwareError",
"(",
"\"Pausing a VM is only supported by VMware Workstation\"",
")",
"yield",
"from",
"self",
".",
"_control_vm",
"(",
"\"pause\"... | Suspends this VMware VM. | [
"Suspends",
"this",
"VMware",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L520-L529 |
226,371 | GNS3/gns3-server | gns3server/compute/vmware/vmware_vm.py | VMwareVM.close | def close(self):
"""
Closes this VMware VM.
"""
if not (yield from super().close()):
return False
for adapter in self._ethernet_adapters.values():
if adapter is not None:
for nio in adapter.ports.values():
if nio and isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
try:
self.acpi_shutdown = False
yield from self.stop()
except VMwareError:
pass
if self.linked_clone:
yield from self.manager.remove_from_vmware_inventory(self._vmx_path) | python | def close(self):
"""
Closes this VMware VM.
"""
if not (yield from super().close()):
return False
for adapter in self._ethernet_adapters.values():
if adapter is not None:
for nio in adapter.ports.values():
if nio and isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
try:
self.acpi_shutdown = False
yield from self.stop()
except VMwareError:
pass
if self.linked_clone:
yield from self.manager.remove_from_vmware_inventory(self._vmx_path) | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"(",
"yield",
"from",
"super",
"(",
")",
".",
"close",
"(",
")",
")",
":",
"return",
"False",
"for",
"adapter",
"in",
"self",
".",
"_ethernet_adapters",
".",
"values",
"(",
")",
":",
"if",
"adapte... | Closes this VMware VM. | [
"Closes",
"this",
"VMware",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L553-L573 |
226,372 | GNS3/gns3-server | gns3server/compute/vmware/vmware_vm.py | VMwareVM.headless | def headless(self, headless):
"""
Sets either the VM will start in headless mode
:param headless: boolean
"""
if headless:
log.info("VMware VM '{name}' [{id}] has enabled the headless mode".format(name=self.name, id=self.id))
else:
log.info("VMware VM '{name}' [{id}] has disabled the headless mode".format(name=self.name, id=self.id))
self._headless = headless | python | def headless(self, headless):
"""
Sets either the VM will start in headless mode
:param headless: boolean
"""
if headless:
log.info("VMware VM '{name}' [{id}] has enabled the headless mode".format(name=self.name, id=self.id))
else:
log.info("VMware VM '{name}' [{id}] has disabled the headless mode".format(name=self.name, id=self.id))
self._headless = headless | [
"def",
"headless",
"(",
"self",
",",
"headless",
")",
":",
"if",
"headless",
":",
"log",
".",
"info",
"(",
"\"VMware VM '{name}' [{id}] has enabled the headless mode\"",
".",
"format",
"(",
"name",
"=",
"self",
".",
"name",
",",
"id",
"=",
"self",
".",
"id",... | Sets either the VM will start in headless mode
:param headless: boolean | [
"Sets",
"either",
"the",
"VM",
"will",
"start",
"in",
"headless",
"mode"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L586-L597 |
226,373 | GNS3/gns3-server | gns3server/compute/vmware/vmware_vm.py | VMwareVM.vmx_path | def vmx_path(self, vmx_path):
"""
Sets the path to the vmx file.
:param vmx_path: VMware vmx file
"""
log.info("VMware VM '{name}' [{id}] has set the vmx file path to '{vmx}'".format(name=self.name, id=self.id, vmx=vmx_path))
self._vmx_path = vmx_path | python | def vmx_path(self, vmx_path):
"""
Sets the path to the vmx file.
:param vmx_path: VMware vmx file
"""
log.info("VMware VM '{name}' [{id}] has set the vmx file path to '{vmx}'".format(name=self.name, id=self.id, vmx=vmx_path))
self._vmx_path = vmx_path | [
"def",
"vmx_path",
"(",
"self",
",",
"vmx_path",
")",
":",
"log",
".",
"info",
"(",
"\"VMware VM '{name}' [{id}] has set the vmx file path to '{vmx}'\"",
".",
"format",
"(",
"name",
"=",
"self",
".",
"name",
",",
"id",
"=",
"self",
".",
"id",
",",
"vmx",
"="... | Sets the path to the vmx file.
:param vmx_path: VMware vmx file | [
"Sets",
"the",
"path",
"to",
"the",
"vmx",
"file",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L634-L642 |
226,374 | GNS3/gns3-server | gns3server/compute/vmware/vmware_vm.py | VMwareVM.adapters | def adapters(self, adapters):
"""
Sets the number of Ethernet adapters for this VMware VM instance.
:param adapters: number of adapters
"""
# VMware VMs are limited to 10 adapters
if adapters > 10:
raise VMwareError("Number of adapters above the maximum supported of 10")
self._ethernet_adapters.clear()
for adapter_number in range(0, adapters):
self._ethernet_adapters[adapter_number] = EthernetAdapter()
self._adapters = len(self._ethernet_adapters)
log.info("VMware VM '{name}' [{id}] has changed the number of Ethernet adapters to {adapters}".format(name=self.name,
id=self.id,
adapters=adapters)) | python | def adapters(self, adapters):
"""
Sets the number of Ethernet adapters for this VMware VM instance.
:param adapters: number of adapters
"""
# VMware VMs are limited to 10 adapters
if adapters > 10:
raise VMwareError("Number of adapters above the maximum supported of 10")
self._ethernet_adapters.clear()
for adapter_number in range(0, adapters):
self._ethernet_adapters[adapter_number] = EthernetAdapter()
self._adapters = len(self._ethernet_adapters)
log.info("VMware VM '{name}' [{id}] has changed the number of Ethernet adapters to {adapters}".format(name=self.name,
id=self.id,
adapters=adapters)) | [
"def",
"adapters",
"(",
"self",
",",
"adapters",
")",
":",
"# VMware VMs are limited to 10 adapters",
"if",
"adapters",
">",
"10",
":",
"raise",
"VMwareError",
"(",
"\"Number of adapters above the maximum supported of 10\"",
")",
"self",
".",
"_ethernet_adapters",
".",
... | Sets the number of Ethernet adapters for this VMware VM instance.
:param adapters: number of adapters | [
"Sets",
"the",
"number",
"of",
"Ethernet",
"adapters",
"for",
"this",
"VMware",
"VM",
"instance",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L655-L673 |
226,375 | GNS3/gns3-server | gns3server/compute/vmware/vmware_vm.py | VMwareVM.adapter_type | def adapter_type(self, adapter_type):
"""
Sets the adapter type for this VMware VM instance.
:param adapter_type: adapter type (string)
"""
self._adapter_type = adapter_type
log.info("VMware VM '{name}' [{id}]: adapter type changed to {adapter_type}".format(name=self.name,
id=self.id,
adapter_type=adapter_type)) | python | def adapter_type(self, adapter_type):
"""
Sets the adapter type for this VMware VM instance.
:param adapter_type: adapter type (string)
"""
self._adapter_type = adapter_type
log.info("VMware VM '{name}' [{id}]: adapter type changed to {adapter_type}".format(name=self.name,
id=self.id,
adapter_type=adapter_type)) | [
"def",
"adapter_type",
"(",
"self",
",",
"adapter_type",
")",
":",
"self",
".",
"_adapter_type",
"=",
"adapter_type",
"log",
".",
"info",
"(",
"\"VMware VM '{name}' [{id}]: adapter type changed to {adapter_type}\"",
".",
"format",
"(",
"name",
"=",
"self",
".",
"nam... | Sets the adapter type for this VMware VM instance.
:param adapter_type: adapter type (string) | [
"Sets",
"the",
"adapter",
"type",
"for",
"this",
"VMware",
"VM",
"instance",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L686-L696 |
226,376 | GNS3/gns3-server | gns3server/compute/vmware/vmware_vm.py | VMwareVM.use_any_adapter | def use_any_adapter(self, use_any_adapter):
"""
Allows GNS3 to use any VMware adapter on this instance.
:param use_any_adapter: boolean
"""
if use_any_adapter:
log.info("VMware VM '{name}' [{id}] is allowed to use any adapter".format(name=self.name, id=self.id))
else:
log.info("VMware VM '{name}' [{id}] is not allowed to use any adapter".format(name=self.name, id=self.id))
self._use_any_adapter = use_any_adapter | python | def use_any_adapter(self, use_any_adapter):
"""
Allows GNS3 to use any VMware adapter on this instance.
:param use_any_adapter: boolean
"""
if use_any_adapter:
log.info("VMware VM '{name}' [{id}] is allowed to use any adapter".format(name=self.name, id=self.id))
else:
log.info("VMware VM '{name}' [{id}] is not allowed to use any adapter".format(name=self.name, id=self.id))
self._use_any_adapter = use_any_adapter | [
"def",
"use_any_adapter",
"(",
"self",
",",
"use_any_adapter",
")",
":",
"if",
"use_any_adapter",
":",
"log",
".",
"info",
"(",
"\"VMware VM '{name}' [{id}] is allowed to use any adapter\"",
".",
"format",
"(",
"name",
"=",
"self",
".",
"name",
",",
"id",
"=",
"... | Allows GNS3 to use any VMware adapter on this instance.
:param use_any_adapter: boolean | [
"Allows",
"GNS3",
"to",
"use",
"any",
"VMware",
"adapter",
"on",
"this",
"instance",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L709-L720 |
226,377 | GNS3/gns3-server | gns3server/compute/vmware/vmware_vm.py | VMwareVM._get_pipe_name | def _get_pipe_name(self):
"""
Returns the pipe name to create a serial connection.
:returns: pipe path (string)
"""
if sys.platform.startswith("win"):
pipe_name = r"\\.\pipe\gns3_vmware\{}".format(self.id)
else:
pipe_name = os.path.join(tempfile.gettempdir(), "gns3_vmware", "{}".format(self.id))
try:
os.makedirs(os.path.dirname(pipe_name), exist_ok=True)
except OSError as e:
raise VMwareError("Could not create the VMware pipe directory: {}".format(e))
return pipe_name | python | def _get_pipe_name(self):
"""
Returns the pipe name to create a serial connection.
:returns: pipe path (string)
"""
if sys.platform.startswith("win"):
pipe_name = r"\\.\pipe\gns3_vmware\{}".format(self.id)
else:
pipe_name = os.path.join(tempfile.gettempdir(), "gns3_vmware", "{}".format(self.id))
try:
os.makedirs(os.path.dirname(pipe_name), exist_ok=True)
except OSError as e:
raise VMwareError("Could not create the VMware pipe directory: {}".format(e))
return pipe_name | [
"def",
"_get_pipe_name",
"(",
"self",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"pipe_name",
"=",
"r\"\\\\.\\pipe\\gns3_vmware\\{}\"",
".",
"format",
"(",
"self",
".",
"id",
")",
"else",
":",
"pipe_name",
"=",
"os... | Returns the pipe name to create a serial connection.
:returns: pipe path (string) | [
"Returns",
"the",
"pipe",
"name",
"to",
"create",
"a",
"serial",
"connection",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L811-L826 |
226,378 | GNS3/gns3-server | gns3server/compute/vmware/vmware_vm.py | VMwareVM._start_console | def _start_console(self):
"""
Starts remote console support for this VM.
"""
self._remote_pipe = yield from asyncio_open_serial(self._get_pipe_name())
server = AsyncioTelnetServer(reader=self._remote_pipe,
writer=self._remote_pipe,
binary=True,
echo=True)
self._telnet_server = yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console) | python | def _start_console(self):
"""
Starts remote console support for this VM.
"""
self._remote_pipe = yield from asyncio_open_serial(self._get_pipe_name())
server = AsyncioTelnetServer(reader=self._remote_pipe,
writer=self._remote_pipe,
binary=True,
echo=True)
self._telnet_server = yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console) | [
"def",
"_start_console",
"(",
"self",
")",
":",
"self",
".",
"_remote_pipe",
"=",
"yield",
"from",
"asyncio_open_serial",
"(",
"self",
".",
"_get_pipe_name",
"(",
")",
")",
"server",
"=",
"AsyncioTelnetServer",
"(",
"reader",
"=",
"self",
".",
"_remote_pipe",
... | Starts remote console support for this VM. | [
"Starts",
"remote",
"console",
"support",
"for",
"this",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L842-L851 |
226,379 | GNS3/gns3-server | gns3server/compute/vmware/vmware_vm.py | VMwareVM._stop_remote_console | def _stop_remote_console(self):
"""
Stops remote console support for this VM.
"""
if self._telnet_server:
self._telnet_server.close()
yield from self._telnet_server.wait_closed()
self._remote_pipe.close()
self._telnet_server = None | python | def _stop_remote_console(self):
"""
Stops remote console support for this VM.
"""
if self._telnet_server:
self._telnet_server.close()
yield from self._telnet_server.wait_closed()
self._remote_pipe.close()
self._telnet_server = None | [
"def",
"_stop_remote_console",
"(",
"self",
")",
":",
"if",
"self",
".",
"_telnet_server",
":",
"self",
".",
"_telnet_server",
".",
"close",
"(",
")",
"yield",
"from",
"self",
".",
"_telnet_server",
".",
"wait_closed",
"(",
")",
"self",
".",
"_remote_pipe",
... | Stops remote console support for this VM. | [
"Stops",
"remote",
"console",
"support",
"for",
"this",
"VM",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L854-L862 |
226,380 | GNS3/gns3-server | gns3server/utils/path.py | get_default_project_directory | def get_default_project_directory():
"""
Return the default location for the project directory
depending of the operating system
"""
server_config = Config.instance().get_section_config("Server")
path = os.path.expanduser(server_config.get("projects_path", "~/GNS3/projects"))
path = os.path.normpath(path)
try:
os.makedirs(path, exist_ok=True)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not create project directory: {}".format(e))
return path | python | def get_default_project_directory():
"""
Return the default location for the project directory
depending of the operating system
"""
server_config = Config.instance().get_section_config("Server")
path = os.path.expanduser(server_config.get("projects_path", "~/GNS3/projects"))
path = os.path.normpath(path)
try:
os.makedirs(path, exist_ok=True)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not create project directory: {}".format(e))
return path | [
"def",
"get_default_project_directory",
"(",
")",
":",
"server_config",
"=",
"Config",
".",
"instance",
"(",
")",
".",
"get_section_config",
"(",
"\"Server\"",
")",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"server_config",
".",
"get",
"(",
"\"... | Return the default location for the project directory
depending of the operating system | [
"Return",
"the",
"default",
"location",
"for",
"the",
"project",
"directory",
"depending",
"of",
"the",
"operating",
"system"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/path.py#L24-L37 |
226,381 | GNS3/gns3-server | gns3server/utils/path.py | check_path_allowed | def check_path_allowed(path):
"""
If the server is non local raise an error if
the path is outside project directories
Raise a 403 in case of error
"""
config = Config.instance().get_section_config("Server")
project_directory = get_default_project_directory()
if len(os.path.commonprefix([project_directory, path])) == len(project_directory):
return
if "local" in config and config.getboolean("local") is False:
raise aiohttp.web.HTTPForbidden(text="The path is not allowed") | python | def check_path_allowed(path):
"""
If the server is non local raise an error if
the path is outside project directories
Raise a 403 in case of error
"""
config = Config.instance().get_section_config("Server")
project_directory = get_default_project_directory()
if len(os.path.commonprefix([project_directory, path])) == len(project_directory):
return
if "local" in config and config.getboolean("local") is False:
raise aiohttp.web.HTTPForbidden(text="The path is not allowed") | [
"def",
"check_path_allowed",
"(",
"path",
")",
":",
"config",
"=",
"Config",
".",
"instance",
"(",
")",
".",
"get_section_config",
"(",
"\"Server\"",
")",
"project_directory",
"=",
"get_default_project_directory",
"(",
")",
"if",
"len",
"(",
"os",
".",
"path",... | If the server is non local raise an error if
the path is outside project directories
Raise a 403 in case of error | [
"If",
"the",
"server",
"is",
"non",
"local",
"raise",
"an",
"error",
"if",
"the",
"path",
"is",
"outside",
"project",
"directories"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/path.py#L40-L55 |
226,382 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/ethernet_hub.py | EthernetHub.ports_mapping | def ports_mapping(self, ports):
"""
Set the ports on this hub
:param ports: ports info
"""
if ports != self._ports:
if len(self._mappings) > 0:
raise NodeError("Can't modify a hub already connected.")
port_number = 0
for port in ports:
port["name"] = "Ethernet{}".format(port_number)
port["port_number"] = port_number
port_number += 1
self._ports = ports | python | def ports_mapping(self, ports):
"""
Set the ports on this hub
:param ports: ports info
"""
if ports != self._ports:
if len(self._mappings) > 0:
raise NodeError("Can't modify a hub already connected.")
port_number = 0
for port in ports:
port["name"] = "Ethernet{}".format(port_number)
port["port_number"] = port_number
port_number += 1
self._ports = ports | [
"def",
"ports_mapping",
"(",
"self",
",",
"ports",
")",
":",
"if",
"ports",
"!=",
"self",
".",
"_ports",
":",
"if",
"len",
"(",
"self",
".",
"_mappings",
")",
">",
"0",
":",
"raise",
"NodeError",
"(",
"\"Can't modify a hub already connected.\"",
")",
"port... | Set the ports on this hub
:param ports: ports info | [
"Set",
"the",
"ports",
"on",
"this",
"hub"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/ethernet_hub.py#L78-L94 |
226,383 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/ethernet_hub.py | EthernetHub.close | def close(self):
"""
Deletes this hub.
"""
for nio in self._nios:
if nio:
yield from nio.close()
try:
yield from Bridge.delete(self)
log.info('Ethernet hub "{name}" [{id}] has been deleted'.format(name=self._name, id=self._id))
except DynamipsError:
log.debug("Could not properly delete Ethernet hub {}".format(self._name))
if self._hypervisor and not self._hypervisor.devices:
yield from self.hypervisor.stop()
self._hypervisor = None
return True | python | def close(self):
"""
Deletes this hub.
"""
for nio in self._nios:
if nio:
yield from nio.close()
try:
yield from Bridge.delete(self)
log.info('Ethernet hub "{name}" [{id}] has been deleted'.format(name=self._name, id=self._id))
except DynamipsError:
log.debug("Could not properly delete Ethernet hub {}".format(self._name))
if self._hypervisor and not self._hypervisor.devices:
yield from self.hypervisor.stop()
self._hypervisor = None
return True | [
"def",
"close",
"(",
"self",
")",
":",
"for",
"nio",
"in",
"self",
".",
"_nios",
":",
"if",
"nio",
":",
"yield",
"from",
"nio",
".",
"close",
"(",
")",
"try",
":",
"yield",
"from",
"Bridge",
".",
"delete",
"(",
"self",
")",
"log",
".",
"info",
... | Deletes this hub. | [
"Deletes",
"this",
"hub",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/ethernet_hub.py#L117-L134 |
226,384 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/ethernet_hub.py | EthernetHub.add_nio | def add_nio(self, nio, port_number):
"""
Adds a NIO as new port on this hub.
:param nio: NIO instance to add
:param port_number: port to allocate for the NIO
"""
if port_number not in [port["port_number"] for port in self._ports]:
raise DynamipsError("Port {} doesn't exist".format(port_number))
if port_number in self._mappings:
raise DynamipsError("Port {} isn't free".format(port_number))
yield from Bridge.add_nio(self, nio)
log.info('Ethernet hub "{name}" [{id}]: NIO {nio} bound to port {port}'.format(name=self._name,
id=self._id,
nio=nio,
port=port_number))
self._mappings[port_number] = nio | python | def add_nio(self, nio, port_number):
"""
Adds a NIO as new port on this hub.
:param nio: NIO instance to add
:param port_number: port to allocate for the NIO
"""
if port_number not in [port["port_number"] for port in self._ports]:
raise DynamipsError("Port {} doesn't exist".format(port_number))
if port_number in self._mappings:
raise DynamipsError("Port {} isn't free".format(port_number))
yield from Bridge.add_nio(self, nio)
log.info('Ethernet hub "{name}" [{id}]: NIO {nio} bound to port {port}'.format(name=self._name,
id=self._id,
nio=nio,
port=port_number))
self._mappings[port_number] = nio | [
"def",
"add_nio",
"(",
"self",
",",
"nio",
",",
"port_number",
")",
":",
"if",
"port_number",
"not",
"in",
"[",
"port",
"[",
"\"port_number\"",
"]",
"for",
"port",
"in",
"self",
".",
"_ports",
"]",
":",
"raise",
"DynamipsError",
"(",
"\"Port {} doesn't exi... | Adds a NIO as new port on this hub.
:param nio: NIO instance to add
:param port_number: port to allocate for the NIO | [
"Adds",
"a",
"NIO",
"as",
"new",
"port",
"on",
"this",
"hub",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/ethernet_hub.py#L137-L157 |
226,385 | GNS3/gns3-server | gns3server/compute/dynamips/nodes/ethernet_hub.py | EthernetHub.remove_nio | def remove_nio(self, port_number):
"""
Removes the specified NIO as member of this hub.
:param port_number: allocated port number
:returns: the NIO that was bound to the allocated port
"""
if port_number not in self._mappings:
raise DynamipsError("Port {} is not allocated".format(port_number))
nio = self._mappings[port_number]
if isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
yield from Bridge.remove_nio(self, nio)
log.info('Ethernet hub "{name}" [{id}]: NIO {nio} removed from port {port}'.format(name=self._name,
id=self._id,
nio=nio,
port=port_number))
del self._mappings[port_number]
return nio | python | def remove_nio(self, port_number):
"""
Removes the specified NIO as member of this hub.
:param port_number: allocated port number
:returns: the NIO that was bound to the allocated port
"""
if port_number not in self._mappings:
raise DynamipsError("Port {} is not allocated".format(port_number))
nio = self._mappings[port_number]
if isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
yield from Bridge.remove_nio(self, nio)
log.info('Ethernet hub "{name}" [{id}]: NIO {nio} removed from port {port}'.format(name=self._name,
id=self._id,
nio=nio,
port=port_number))
del self._mappings[port_number]
return nio | [
"def",
"remove_nio",
"(",
"self",
",",
"port_number",
")",
":",
"if",
"port_number",
"not",
"in",
"self",
".",
"_mappings",
":",
"raise",
"DynamipsError",
"(",
"\"Port {} is not allocated\"",
".",
"format",
"(",
"port_number",
")",
")",
"nio",
"=",
"self",
"... | Removes the specified NIO as member of this hub.
:param port_number: allocated port number
:returns: the NIO that was bound to the allocated port | [
"Removes",
"the",
"specified",
"NIO",
"as",
"member",
"of",
"this",
"hub",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/ethernet_hub.py#L160-L183 |
226,386 | GNS3/gns3-server | gns3server/compute/base_manager.py | BaseManager.instance | def instance(cls):
"""
Singleton to return only one instance of BaseManager.
:returns: instance of BaseManager
"""
if not hasattr(cls, "_instance") or cls._instance is None:
cls._instance = cls()
return cls._instance | python | def instance(cls):
"""
Singleton to return only one instance of BaseManager.
:returns: instance of BaseManager
"""
if not hasattr(cls, "_instance") or cls._instance is None:
cls._instance = cls()
return cls._instance | [
"def",
"instance",
"(",
"cls",
")",
":",
"if",
"not",
"hasattr",
"(",
"cls",
",",
"\"_instance\"",
")",
"or",
"cls",
".",
"_instance",
"is",
"None",
":",
"cls",
".",
"_instance",
"=",
"cls",
"(",
")",
"return",
"cls",
".",
"_instance"
] | Singleton to return only one instance of BaseManager.
:returns: instance of BaseManager | [
"Singleton",
"to",
"return",
"only",
"one",
"instance",
"of",
"BaseManager",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_manager.py#L78-L87 |
226,387 | GNS3/gns3-server | gns3server/compute/base_manager.py | BaseManager.port_manager | def port_manager(self):
"""
Returns the port manager.
:returns: Port manager
"""
if self._port_manager is None:
self._port_manager = PortManager.instance()
return self._port_manager | python | def port_manager(self):
"""
Returns the port manager.
:returns: Port manager
"""
if self._port_manager is None:
self._port_manager = PortManager.instance()
return self._port_manager | [
"def",
"port_manager",
"(",
"self",
")",
":",
"if",
"self",
".",
"_port_manager",
"is",
"None",
":",
"self",
".",
"_port_manager",
"=",
"PortManager",
".",
"instance",
"(",
")",
"return",
"self",
".",
"_port_manager"
] | Returns the port manager.
:returns: Port manager | [
"Returns",
"the",
"port",
"manager",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_manager.py#L100-L108 |
226,388 | GNS3/gns3-server | gns3server/compute/base_manager.py | BaseManager.convert_old_project | def convert_old_project(self, project, legacy_id, name):
"""
Convert projects made before version 1.3
:param project: Project instance
:param legacy_id: old identifier
:param name: node name
:returns: new identifier
"""
new_id = str(uuid4())
legacy_project_files_path = os.path.join(project.path, "{}-files".format(project.name))
new_project_files_path = os.path.join(project.path, "project-files")
if os.path.exists(legacy_project_files_path) and not os.path.exists(new_project_files_path):
# move the project files
log.info("Converting old project...")
try:
log.info('Moving "{}" to "{}"'.format(legacy_project_files_path, new_project_files_path))
yield from wait_run_in_executor(shutil.move, legacy_project_files_path, new_project_files_path)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not move project files directory: {} to {} {}".format(legacy_project_files_path,
new_project_files_path, e))
if project.is_local() is False:
legacy_remote_project_path = os.path.join(project.location, project.name, self.module_name.lower())
new_remote_project_path = os.path.join(project.path, "project-files", self.module_name.lower())
if os.path.exists(legacy_remote_project_path) and not os.path.exists(new_remote_project_path):
# move the legacy remote project (remote servers only)
log.info("Converting old remote project...")
try:
log.info('Moving "{}" to "{}"'.format(legacy_remote_project_path, new_remote_project_path))
yield from wait_run_in_executor(shutil.move, legacy_remote_project_path, new_remote_project_path)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not move directory: {} to {} {}".format(legacy_remote_project_path,
new_remote_project_path, e))
if hasattr(self, "get_legacy_vm_workdir"):
# rename old project node working dir
log.info("Converting old node working directory...")
legacy_vm_dir = self.get_legacy_vm_workdir(legacy_id, name)
legacy_vm_working_path = os.path.join(new_project_files_path, legacy_vm_dir)
new_vm_working_path = os.path.join(new_project_files_path, self.module_name.lower(), new_id)
if os.path.exists(legacy_vm_working_path) and not os.path.exists(new_vm_working_path):
try:
log.info('Moving "{}" to "{}"'.format(legacy_vm_working_path, new_vm_working_path))
yield from wait_run_in_executor(shutil.move, legacy_vm_working_path, new_vm_working_path)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not move vm working directory: {} to {} {}".format(legacy_vm_working_path,
new_vm_working_path, e))
return new_id | python | def convert_old_project(self, project, legacy_id, name):
"""
Convert projects made before version 1.3
:param project: Project instance
:param legacy_id: old identifier
:param name: node name
:returns: new identifier
"""
new_id = str(uuid4())
legacy_project_files_path = os.path.join(project.path, "{}-files".format(project.name))
new_project_files_path = os.path.join(project.path, "project-files")
if os.path.exists(legacy_project_files_path) and not os.path.exists(new_project_files_path):
# move the project files
log.info("Converting old project...")
try:
log.info('Moving "{}" to "{}"'.format(legacy_project_files_path, new_project_files_path))
yield from wait_run_in_executor(shutil.move, legacy_project_files_path, new_project_files_path)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not move project files directory: {} to {} {}".format(legacy_project_files_path,
new_project_files_path, e))
if project.is_local() is False:
legacy_remote_project_path = os.path.join(project.location, project.name, self.module_name.lower())
new_remote_project_path = os.path.join(project.path, "project-files", self.module_name.lower())
if os.path.exists(legacy_remote_project_path) and not os.path.exists(new_remote_project_path):
# move the legacy remote project (remote servers only)
log.info("Converting old remote project...")
try:
log.info('Moving "{}" to "{}"'.format(legacy_remote_project_path, new_remote_project_path))
yield from wait_run_in_executor(shutil.move, legacy_remote_project_path, new_remote_project_path)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not move directory: {} to {} {}".format(legacy_remote_project_path,
new_remote_project_path, e))
if hasattr(self, "get_legacy_vm_workdir"):
# rename old project node working dir
log.info("Converting old node working directory...")
legacy_vm_dir = self.get_legacy_vm_workdir(legacy_id, name)
legacy_vm_working_path = os.path.join(new_project_files_path, legacy_vm_dir)
new_vm_working_path = os.path.join(new_project_files_path, self.module_name.lower(), new_id)
if os.path.exists(legacy_vm_working_path) and not os.path.exists(new_vm_working_path):
try:
log.info('Moving "{}" to "{}"'.format(legacy_vm_working_path, new_vm_working_path))
yield from wait_run_in_executor(shutil.move, legacy_vm_working_path, new_vm_working_path)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not move vm working directory: {} to {} {}".format(legacy_vm_working_path,
new_vm_working_path, e))
return new_id | [
"def",
"convert_old_project",
"(",
"self",
",",
"project",
",",
"legacy_id",
",",
"name",
")",
":",
"new_id",
"=",
"str",
"(",
"uuid4",
"(",
")",
")",
"legacy_project_files_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"project",
".",
"path",
",",
"... | Convert projects made before version 1.3
:param project: Project instance
:param legacy_id: old identifier
:param name: node name
:returns: new identifier | [
"Convert",
"projects",
"made",
"before",
"version",
"1",
".",
"3"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_manager.py#L175-L226 |
226,389 | GNS3/gns3-server | gns3server/compute/base_manager.py | BaseManager.close_node | def close_node(self, node_id):
"""
Close a node
:param node_id: Node identifier
:returns: Node instance
"""
node = self.get_node(node_id)
if asyncio.iscoroutinefunction(node.close):
yield from node.close()
else:
node.close()
return node | python | def close_node(self, node_id):
"""
Close a node
:param node_id: Node identifier
:returns: Node instance
"""
node = self.get_node(node_id)
if asyncio.iscoroutinefunction(node.close):
yield from node.close()
else:
node.close()
return node | [
"def",
"close_node",
"(",
"self",
",",
"node_id",
")",
":",
"node",
"=",
"self",
".",
"get_node",
"(",
"node_id",
")",
"if",
"asyncio",
".",
"iscoroutinefunction",
"(",
"node",
".",
"close",
")",
":",
"yield",
"from",
"node",
".",
"close",
"(",
")",
... | Close a node
:param node_id: Node identifier
:returns: Node instance | [
"Close",
"a",
"node"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_manager.py#L291-L305 |
226,390 | GNS3/gns3-server | gns3server/compute/base_manager.py | BaseManager.delete_node | def delete_node(self, node_id):
"""
Delete a node. The node working directory will be destroyed when a commit is received.
:param node_id: Node identifier
:returns: Node instance
"""
node = None
try:
node = self.get_node(node_id)
yield from self.close_node(node_id)
finally:
if node:
node.project.emit("node.deleted", node)
yield from node.project.remove_node(node)
if node.id in self._nodes:
del self._nodes[node.id]
return node | python | def delete_node(self, node_id):
"""
Delete a node. The node working directory will be destroyed when a commit is received.
:param node_id: Node identifier
:returns: Node instance
"""
node = None
try:
node = self.get_node(node_id)
yield from self.close_node(node_id)
finally:
if node:
node.project.emit("node.deleted", node)
yield from node.project.remove_node(node)
if node.id in self._nodes:
del self._nodes[node.id]
return node | [
"def",
"delete_node",
"(",
"self",
",",
"node_id",
")",
":",
"node",
"=",
"None",
"try",
":",
"node",
"=",
"self",
".",
"get_node",
"(",
"node_id",
")",
"yield",
"from",
"self",
".",
"close_node",
"(",
"node_id",
")",
"finally",
":",
"if",
"node",
":... | Delete a node. The node working directory will be destroyed when a commit is received.
:param node_id: Node identifier
:returns: Node instance | [
"Delete",
"a",
"node",
".",
"The",
"node",
"working",
"directory",
"will",
"be",
"destroyed",
"when",
"a",
"commit",
"is",
"received",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_manager.py#L330-L348 |
226,391 | GNS3/gns3-server | gns3server/compute/base_manager.py | BaseManager.has_privileged_access | def has_privileged_access(executable):
"""
Check if an executable have the right to attach to Ethernet and TAP adapters.
:param executable: executable path
:returns: True or False
"""
if sys.platform.startswith("win"):
# do not check anything on Windows
return True
if sys.platform.startswith("darwin"):
if os.stat(executable).st_uid == 0:
return True
if os.geteuid() == 0:
# we are root, so we should have privileged access.
return True
if os.stat(executable).st_uid == 0 and (os.stat(executable).st_mode & stat.S_ISUID or os.stat(executable).st_mode & stat.S_ISGID):
# the executable has set UID bit.
return True
# test if the executable has the CAP_NET_RAW capability (Linux only)
try:
if sys.platform.startswith("linux") and "security.capability" in os.listxattr(executable):
caps = os.getxattr(executable, "security.capability")
# test the 2nd byte and check if the 13th bit (CAP_NET_RAW) is set
if struct.unpack("<IIIII", caps)[1] & 1 << 13:
return True
except (AttributeError, OSError) as e:
log.error("could not determine if CAP_NET_RAW capability is set for {}: {}".format(executable, e))
return False | python | def has_privileged_access(executable):
"""
Check if an executable have the right to attach to Ethernet and TAP adapters.
:param executable: executable path
:returns: True or False
"""
if sys.platform.startswith("win"):
# do not check anything on Windows
return True
if sys.platform.startswith("darwin"):
if os.stat(executable).st_uid == 0:
return True
if os.geteuid() == 0:
# we are root, so we should have privileged access.
return True
if os.stat(executable).st_uid == 0 and (os.stat(executable).st_mode & stat.S_ISUID or os.stat(executable).st_mode & stat.S_ISGID):
# the executable has set UID bit.
return True
# test if the executable has the CAP_NET_RAW capability (Linux only)
try:
if sys.platform.startswith("linux") and "security.capability" in os.listxattr(executable):
caps = os.getxattr(executable, "security.capability")
# test the 2nd byte and check if the 13th bit (CAP_NET_RAW) is set
if struct.unpack("<IIIII", caps)[1] & 1 << 13:
return True
except (AttributeError, OSError) as e:
log.error("could not determine if CAP_NET_RAW capability is set for {}: {}".format(executable, e))
return False | [
"def",
"has_privileged_access",
"(",
"executable",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"# do not check anything on Windows",
"return",
"True",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"darwin\"",
")... | Check if an executable have the right to attach to Ethernet and TAP adapters.
:param executable: executable path
:returns: True or False | [
"Check",
"if",
"an",
"executable",
"have",
"the",
"right",
"to",
"attach",
"to",
"Ethernet",
"and",
"TAP",
"adapters",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_manager.py#L351-L386 |
226,392 | GNS3/gns3-server | gns3server/compute/base_manager.py | BaseManager.get_abs_image_path | def get_abs_image_path(self, path):
"""
Get the absolute path of an image
:param path: file path
:return: file path
"""
if not path:
return ""
orig_path = path
server_config = self.config.get_section_config("Server")
img_directory = self.get_images_directory()
# Windows path should not be send to a unix server
if not sys.platform.startswith("win"):
if re.match(r"^[A-Z]:", path) is not None:
raise NodeError("{} is not allowed on this remote server. Please use only a filename in {}.".format(path, img_directory))
if not os.path.isabs(path):
for directory in images_directories(self._NODE_TYPE):
path = self._recursive_search_file_in_directory(directory, orig_path)
if path:
return force_unix_path(path)
# Not found we try the default directory
s = os.path.split(orig_path)
path = force_unix_path(os.path.join(img_directory, *s))
if os.path.exists(path):
return path
raise ImageMissingError(orig_path)
# For non local server we disallow using absolute path outside image directory
if server_config.getboolean("local", False) is True:
path = force_unix_path(path)
if os.path.exists(path):
return path
raise ImageMissingError(orig_path)
path = force_unix_path(path)
for directory in images_directories(self._NODE_TYPE):
if os.path.commonprefix([directory, path]) == directory:
if os.path.exists(path):
return path
raise ImageMissingError(orig_path)
raise NodeError("{} is not allowed on this remote server. Please use only a filename in {}.".format(path, img_directory)) | python | def get_abs_image_path(self, path):
"""
Get the absolute path of an image
:param path: file path
:return: file path
"""
if not path:
return ""
orig_path = path
server_config = self.config.get_section_config("Server")
img_directory = self.get_images_directory()
# Windows path should not be send to a unix server
if not sys.platform.startswith("win"):
if re.match(r"^[A-Z]:", path) is not None:
raise NodeError("{} is not allowed on this remote server. Please use only a filename in {}.".format(path, img_directory))
if not os.path.isabs(path):
for directory in images_directories(self._NODE_TYPE):
path = self._recursive_search_file_in_directory(directory, orig_path)
if path:
return force_unix_path(path)
# Not found we try the default directory
s = os.path.split(orig_path)
path = force_unix_path(os.path.join(img_directory, *s))
if os.path.exists(path):
return path
raise ImageMissingError(orig_path)
# For non local server we disallow using absolute path outside image directory
if server_config.getboolean("local", False) is True:
path = force_unix_path(path)
if os.path.exists(path):
return path
raise ImageMissingError(orig_path)
path = force_unix_path(path)
for directory in images_directories(self._NODE_TYPE):
if os.path.commonprefix([directory, path]) == directory:
if os.path.exists(path):
return path
raise ImageMissingError(orig_path)
raise NodeError("{} is not allowed on this remote server. Please use only a filename in {}.".format(path, img_directory)) | [
"def",
"get_abs_image_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"path",
":",
"return",
"\"\"",
"orig_path",
"=",
"path",
"server_config",
"=",
"self",
".",
"config",
".",
"get_section_config",
"(",
"\"Server\"",
")",
"img_directory",
"=",
"self... | Get the absolute path of an image
:param path: file path
:return: file path | [
"Get",
"the",
"absolute",
"path",
"of",
"an",
"image"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_manager.py#L430-L476 |
226,393 | GNS3/gns3-server | gns3server/compute/base_manager.py | BaseManager._recursive_search_file_in_directory | def _recursive_search_file_in_directory(self, directory, searched_file):
"""
Search for a file in directory and is subdirectories
:returns: Path or None if not found
"""
s = os.path.split(searched_file)
for root, dirs, files in os.walk(directory):
for file in files:
# If filename is the same
if s[1] == file and (s[0] == '' or s[0] == os.path.basename(root)):
path = os.path.normpath(os.path.join(root, s[1]))
if os.path.exists(path):
return path
return None | python | def _recursive_search_file_in_directory(self, directory, searched_file):
"""
Search for a file in directory and is subdirectories
:returns: Path or None if not found
"""
s = os.path.split(searched_file)
for root, dirs, files in os.walk(directory):
for file in files:
# If filename is the same
if s[1] == file and (s[0] == '' or s[0] == os.path.basename(root)):
path = os.path.normpath(os.path.join(root, s[1]))
if os.path.exists(path):
return path
return None | [
"def",
"_recursive_search_file_in_directory",
"(",
"self",
",",
"directory",
",",
"searched_file",
")",
":",
"s",
"=",
"os",
".",
"path",
".",
"split",
"(",
"searched_file",
")",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"di... | Search for a file in directory and is subdirectories
:returns: Path or None if not found | [
"Search",
"for",
"a",
"file",
"in",
"directory",
"and",
"is",
"subdirectories"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_manager.py#L478-L493 |
226,394 | GNS3/gns3-server | gns3server/compute/base_manager.py | BaseManager.get_relative_image_path | def get_relative_image_path(self, path):
"""
Get a path relative to images directory path
or an abspath if the path is not located inside
image directory
:param path: file path
:return: file path
"""
if not path:
return ""
path = force_unix_path(self.get_abs_image_path(path))
img_directory = self.get_images_directory()
for directory in images_directories(self._NODE_TYPE):
if os.path.commonprefix([directory, path]) == directory:
relpath = os.path.relpath(path, directory)
# We don't allow to recurse search from the top image directory just for image type directory (compatibility with old releases)
if os.sep not in relpath or directory == img_directory:
return relpath
return path | python | def get_relative_image_path(self, path):
"""
Get a path relative to images directory path
or an abspath if the path is not located inside
image directory
:param path: file path
:return: file path
"""
if not path:
return ""
path = force_unix_path(self.get_abs_image_path(path))
img_directory = self.get_images_directory()
for directory in images_directories(self._NODE_TYPE):
if os.path.commonprefix([directory, path]) == directory:
relpath = os.path.relpath(path, directory)
# We don't allow to recurse search from the top image directory just for image type directory (compatibility with old releases)
if os.sep not in relpath or directory == img_directory:
return relpath
return path | [
"def",
"get_relative_image_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"path",
":",
"return",
"\"\"",
"path",
"=",
"force_unix_path",
"(",
"self",
".",
"get_abs_image_path",
"(",
"path",
")",
")",
"img_directory",
"=",
"self",
".",
"get_images_di... | Get a path relative to images directory path
or an abspath if the path is not located inside
image directory
:param path: file path
:return: file path | [
"Get",
"a",
"path",
"relative",
"to",
"images",
"directory",
"path",
"or",
"an",
"abspath",
"if",
"the",
"path",
"is",
"not",
"located",
"inside",
"image",
"directory"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_manager.py#L495-L517 |
226,395 | GNS3/gns3-server | gns3server/compute/base_manager.py | BaseManager.list_images | def list_images(self):
"""
Return the list of available images for this node type
:returns: Array of hash
"""
try:
return list_images(self._NODE_TYPE)
except OSError as e:
raise aiohttp.web.HTTPConflict(text="Can not list images {}".format(e)) | python | def list_images(self):
"""
Return the list of available images for this node type
:returns: Array of hash
"""
try:
return list_images(self._NODE_TYPE)
except OSError as e:
raise aiohttp.web.HTTPConflict(text="Can not list images {}".format(e)) | [
"def",
"list_images",
"(",
"self",
")",
":",
"try",
":",
"return",
"list_images",
"(",
"self",
".",
"_NODE_TYPE",
")",
"except",
"OSError",
"as",
"e",
":",
"raise",
"aiohttp",
".",
"web",
".",
"HTTPConflict",
"(",
"text",
"=",
"\"Can not list images {}\"",
... | Return the list of available images for this node type
:returns: Array of hash | [
"Return",
"the",
"list",
"of",
"available",
"images",
"for",
"this",
"node",
"type"
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_manager.py#L520-L530 |
226,396 | GNS3/gns3-server | gns3server/compute/dynamips/hypervisor.py | Hypervisor.start | def start(self):
"""
Starts the Dynamips hypervisor process.
"""
self._command = self._build_command()
env = os.environ.copy()
if sys.platform.startswith("win"):
# add the Npcap directory to $PATH to force Dynamips to use npcap DLL instead of Winpcap (if installed)
system_root = os.path.join(os.path.expandvars("%SystemRoot%"), "System32", "Npcap")
if os.path.isdir(system_root):
env["PATH"] = system_root + ';' + env["PATH"]
try:
log.info("Starting Dynamips: {}".format(self._command))
self._stdout_file = os.path.join(self.working_dir, "dynamips_i{}_stdout.txt".format(self._id))
log.info("Dynamips process logging to {}".format(self._stdout_file))
with open(self._stdout_file, "w", encoding="utf-8") as fd:
self._process = yield from asyncio.create_subprocess_exec(*self._command,
stdout=fd,
stderr=subprocess.STDOUT,
cwd=self._working_dir,
env=env)
log.info("Dynamips process started PID={}".format(self._process.pid))
self._started = True
except (OSError, subprocess.SubprocessError) as e:
log.error("Could not start Dynamips: {}".format(e))
raise DynamipsError("Could not start Dynamips: {}".format(e)) | python | def start(self):
"""
Starts the Dynamips hypervisor process.
"""
self._command = self._build_command()
env = os.environ.copy()
if sys.platform.startswith("win"):
# add the Npcap directory to $PATH to force Dynamips to use npcap DLL instead of Winpcap (if installed)
system_root = os.path.join(os.path.expandvars("%SystemRoot%"), "System32", "Npcap")
if os.path.isdir(system_root):
env["PATH"] = system_root + ';' + env["PATH"]
try:
log.info("Starting Dynamips: {}".format(self._command))
self._stdout_file = os.path.join(self.working_dir, "dynamips_i{}_stdout.txt".format(self._id))
log.info("Dynamips process logging to {}".format(self._stdout_file))
with open(self._stdout_file, "w", encoding="utf-8") as fd:
self._process = yield from asyncio.create_subprocess_exec(*self._command,
stdout=fd,
stderr=subprocess.STDOUT,
cwd=self._working_dir,
env=env)
log.info("Dynamips process started PID={}".format(self._process.pid))
self._started = True
except (OSError, subprocess.SubprocessError) as e:
log.error("Could not start Dynamips: {}".format(e))
raise DynamipsError("Could not start Dynamips: {}".format(e)) | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_command",
"=",
"self",
".",
"_build_command",
"(",
")",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"# add... | Starts the Dynamips hypervisor process. | [
"Starts",
"the",
"Dynamips",
"hypervisor",
"process",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/hypervisor.py#L115-L141 |
226,397 | GNS3/gns3-server | gns3server/compute/dynamips/hypervisor.py | Hypervisor.stop | def stop(self):
"""
Stops the Dynamips hypervisor process.
"""
if self.is_running():
log.info("Stopping Dynamips process PID={}".format(self._process.pid))
yield from DynamipsHypervisor.stop(self)
# give some time for the hypervisor to properly stop.
# time to delete UNIX NIOs for instance.
yield from asyncio.sleep(0.01)
try:
yield from wait_for_process_termination(self._process, timeout=3)
except asyncio.TimeoutError:
if self._process.returncode is None:
log.warn("Dynamips process {} is still running... killing it".format(self._process.pid))
try:
self._process.kill()
except OSError as e:
log.error("Cannot stop the Dynamips process: {}".format(e))
if self._process.returncode is None:
log.warn('Dynamips hypervisor with PID={} is still running'.format(self._process.pid))
if self._stdout_file and os.access(self._stdout_file, os.W_OK):
try:
os.remove(self._stdout_file)
except OSError as e:
log.warning("could not delete temporary Dynamips log file: {}".format(e))
self._started = False | python | def stop(self):
"""
Stops the Dynamips hypervisor process.
"""
if self.is_running():
log.info("Stopping Dynamips process PID={}".format(self._process.pid))
yield from DynamipsHypervisor.stop(self)
# give some time for the hypervisor to properly stop.
# time to delete UNIX NIOs for instance.
yield from asyncio.sleep(0.01)
try:
yield from wait_for_process_termination(self._process, timeout=3)
except asyncio.TimeoutError:
if self._process.returncode is None:
log.warn("Dynamips process {} is still running... killing it".format(self._process.pid))
try:
self._process.kill()
except OSError as e:
log.error("Cannot stop the Dynamips process: {}".format(e))
if self._process.returncode is None:
log.warn('Dynamips hypervisor with PID={} is still running'.format(self._process.pid))
if self._stdout_file and os.access(self._stdout_file, os.W_OK):
try:
os.remove(self._stdout_file)
except OSError as e:
log.warning("could not delete temporary Dynamips log file: {}".format(e))
self._started = False | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_running",
"(",
")",
":",
"log",
".",
"info",
"(",
"\"Stopping Dynamips process PID={}\"",
".",
"format",
"(",
"self",
".",
"_process",
".",
"pid",
")",
")",
"yield",
"from",
"DynamipsHypervisor",... | Stops the Dynamips hypervisor process. | [
"Stops",
"the",
"Dynamips",
"hypervisor",
"process",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/hypervisor.py#L144-L172 |
226,398 | GNS3/gns3-server | gns3server/compute/dynamips/hypervisor.py | Hypervisor.read_stdout | def read_stdout(self):
"""
Reads the standard output of the Dynamips process.
Only use when the process has been stopped or has crashed.
"""
output = ""
if self._stdout_file and os.access(self._stdout_file, os.R_OK):
try:
with open(self._stdout_file, "rb") as file:
output = file.read().decode("utf-8", errors="replace")
except OSError as e:
log.warn("could not read {}: {}".format(self._stdout_file, e))
return output | python | def read_stdout(self):
"""
Reads the standard output of the Dynamips process.
Only use when the process has been stopped or has crashed.
"""
output = ""
if self._stdout_file and os.access(self._stdout_file, os.R_OK):
try:
with open(self._stdout_file, "rb") as file:
output = file.read().decode("utf-8", errors="replace")
except OSError as e:
log.warn("could not read {}: {}".format(self._stdout_file, e))
return output | [
"def",
"read_stdout",
"(",
"self",
")",
":",
"output",
"=",
"\"\"",
"if",
"self",
".",
"_stdout_file",
"and",
"os",
".",
"access",
"(",
"self",
".",
"_stdout_file",
",",
"os",
".",
"R_OK",
")",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"_s... | Reads the standard output of the Dynamips process.
Only use when the process has been stopped or has crashed. | [
"Reads",
"the",
"standard",
"output",
"of",
"the",
"Dynamips",
"process",
".",
"Only",
"use",
"when",
"the",
"process",
"has",
"been",
"stopped",
"or",
"has",
"crashed",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/hypervisor.py#L174-L187 |
226,399 | GNS3/gns3-server | gns3server/compute/dynamips/adapters/adapter.py | Adapter.install_wic | def install_wic(self, wic_slot_id, wic):
"""
Installs a WIC on this adapter.
:param wic_slot_id: WIC slot ID (integer)
:param wic: WIC instance
"""
self._wics[wic_slot_id] = wic
# Dynamips WICs ports start on a multiple of 16 + port number
# WIC1 port 1 = 16, WIC1 port 2 = 17
# WIC2 port 1 = 32, WIC2 port 2 = 33
# WIC3 port 1 = 48, WIC3 port 2 = 49
base = 16 * (wic_slot_id + 1)
for wic_port in range(0, wic.interfaces):
port_number = base + wic_port
self._ports[port_number] = None | python | def install_wic(self, wic_slot_id, wic):
"""
Installs a WIC on this adapter.
:param wic_slot_id: WIC slot ID (integer)
:param wic: WIC instance
"""
self._wics[wic_slot_id] = wic
# Dynamips WICs ports start on a multiple of 16 + port number
# WIC1 port 1 = 16, WIC1 port 2 = 17
# WIC2 port 1 = 32, WIC2 port 2 = 33
# WIC3 port 1 = 48, WIC3 port 2 = 49
base = 16 * (wic_slot_id + 1)
for wic_port in range(0, wic.interfaces):
port_number = base + wic_port
self._ports[port_number] = None | [
"def",
"install_wic",
"(",
"self",
",",
"wic_slot_id",
",",
"wic",
")",
":",
"self",
".",
"_wics",
"[",
"wic_slot_id",
"]",
"=",
"wic",
"# Dynamips WICs ports start on a multiple of 16 + port number",
"# WIC1 port 1 = 16, WIC1 port 2 = 17",
"# WIC2 port 1 = 32, WIC2 port 2 = ... | Installs a WIC on this adapter.
:param wic_slot_id: WIC slot ID (integer)
:param wic: WIC instance | [
"Installs",
"a",
"WIC",
"on",
"this",
"adapter",
"."
] | a221678448fb5d24e977ef562f81d56aacc89ab1 | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/adapters/adapter.py#L70-L87 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.