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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
240,100 | fhamborg/news-please | newsplease/helper_classes/url_extractor.py | UrlExtractor.get_url_directory_string | def get_url_directory_string(url):
"""
Determines the url's directory string.
:param str url: the url to extract the directory string from
:return str: the directory string on the server
"""
domain = UrlExtractor.get_allowed_domain(url)
splitted_url = url.split('/')
# the following commented list comprehension could replace
# the following for, if not and break statement
# index = [index for index in range(len(splitted_url))
# if not re.search(domain, splitted_url[index]) is None][0]
for index in range(len(splitted_url)):
if not re.search(domain, splitted_url[index]) is None:
if splitted_url[-1] is "":
splitted_url = splitted_url[index + 1:-2]
else:
splitted_url = splitted_url[index + 1:-1]
break
return '_'.join(splitted_url) | python | def get_url_directory_string(url):
domain = UrlExtractor.get_allowed_domain(url)
splitted_url = url.split('/')
# the following commented list comprehension could replace
# the following for, if not and break statement
# index = [index for index in range(len(splitted_url))
# if not re.search(domain, splitted_url[index]) is None][0]
for index in range(len(splitted_url)):
if not re.search(domain, splitted_url[index]) is None:
if splitted_url[-1] is "":
splitted_url = splitted_url[index + 1:-2]
else:
splitted_url = splitted_url[index + 1:-1]
break
return '_'.join(splitted_url) | [
"def",
"get_url_directory_string",
"(",
"url",
")",
":",
"domain",
"=",
"UrlExtractor",
".",
"get_allowed_domain",
"(",
"url",
")",
"splitted_url",
"=",
"url",
".",
"split",
"(",
"'/'",
")",
"# the following commented list comprehension could replace",
"# the following ... | Determines the url's directory string.
:param str url: the url to extract the directory string from
:return str: the directory string on the server | [
"Determines",
"the",
"url",
"s",
"directory",
"string",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/url_extractor.py#L149-L172 |
240,101 | fhamborg/news-please | newsplease/helper_classes/url_extractor.py | UrlExtractor.get_url_file_name | def get_url_file_name(url):
"""
Determines the url's file name.
:param str url: the url to extract the file name from
:return str: the filename (without the file extension) on the server
"""
url_root_ext = os.path.splitext(url)
if len(url_root_ext[1]) <= MAX_FILE_EXTENSION_LENGTH:
return os.path.split(url_root_ext[0])[1]
else:
return os.path.split(url)[1] | python | def get_url_file_name(url):
url_root_ext = os.path.splitext(url)
if len(url_root_ext[1]) <= MAX_FILE_EXTENSION_LENGTH:
return os.path.split(url_root_ext[0])[1]
else:
return os.path.split(url)[1] | [
"def",
"get_url_file_name",
"(",
"url",
")",
":",
"url_root_ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"url",
")",
"if",
"len",
"(",
"url_root_ext",
"[",
"1",
"]",
")",
"<=",
"MAX_FILE_EXTENSION_LENGTH",
":",
"return",
"os",
".",
"path",
".",
... | Determines the url's file name.
:param str url: the url to extract the file name from
:return str: the filename (without the file extension) on the server | [
"Determines",
"the",
"url",
"s",
"file",
"name",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/url_extractor.py#L175-L187 |
240,102 | fhamborg/news-please | newsplease/config.py | CrawlerConfig.load_config | def load_config(self):
"""
Loads the config-file
"""
self.__config = {}
# Parse sections, its options and put it in self.config.
for section in self.sections:
self.__config[section] = {}
options = self.parser.options(section)
# Parse options of each section
for option in options:
try:
opt = self.parser \
.get(section, option)
try:
self.__config[section][option] = literal_eval(opt)
except (SyntaxError, ValueError):
self.__config[section][option] = opt
self.log_output.append(
{"level": "debug",
"msg": "Option not literal_eval-parsable"
" (maybe string): [{0}] {1}"
.format(section, option)})
if self.__config[section][option] == -1:
self.log_output.append(
{"level": "debug",
"msg": "Skipping: [%s] %s" % (section, option)}
)
except ConfigParser.NoOptionError as exc:
self.log_output.append(
{"level": "error",
"msg": "Exception on [%s] %s: %s"
% (section, option, exc)}
)
self.__config[section][option] = None | python | def load_config(self):
self.__config = {}
# Parse sections, its options and put it in self.config.
for section in self.sections:
self.__config[section] = {}
options = self.parser.options(section)
# Parse options of each section
for option in options:
try:
opt = self.parser \
.get(section, option)
try:
self.__config[section][option] = literal_eval(opt)
except (SyntaxError, ValueError):
self.__config[section][option] = opt
self.log_output.append(
{"level": "debug",
"msg": "Option not literal_eval-parsable"
" (maybe string): [{0}] {1}"
.format(section, option)})
if self.__config[section][option] == -1:
self.log_output.append(
{"level": "debug",
"msg": "Skipping: [%s] %s" % (section, option)}
)
except ConfigParser.NoOptionError as exc:
self.log_output.append(
{"level": "error",
"msg": "Exception on [%s] %s: %s"
% (section, option, exc)}
)
self.__config[section][option] = None | [
"def",
"load_config",
"(",
"self",
")",
":",
"self",
".",
"__config",
"=",
"{",
"}",
"# Parse sections, its options and put it in self.config.",
"for",
"section",
"in",
"self",
".",
"sections",
":",
"self",
".",
"__config",
"[",
"section",
"]",
"=",
"{",
"}",
... | Loads the config-file | [
"Loads",
"the",
"config",
"-",
"file"
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/config.py#L95-L134 |
240,103 | fhamborg/news-please | newsplease/config.py | CrawlerConfig.handle_logging | def handle_logging(self):
"""
To allow devs to log as early as possible, logging will already be
handled here
"""
configure_logging(self.get_scrapy_options())
# Disable duplicates
self.__scrapy_options["LOG_ENABLED"] = False
# Now, after log-level is correctly set, lets log them.
for msg in self.log_output:
if msg["level"] is "error":
self.log.error(msg["msg"])
elif msg["level"] is "info":
self.log.info(msg["msg"])
elif msg["level"] is "debug":
self.log.debug(msg["msg"]) | python | def handle_logging(self):
configure_logging(self.get_scrapy_options())
# Disable duplicates
self.__scrapy_options["LOG_ENABLED"] = False
# Now, after log-level is correctly set, lets log them.
for msg in self.log_output:
if msg["level"] is "error":
self.log.error(msg["msg"])
elif msg["level"] is "info":
self.log.info(msg["msg"])
elif msg["level"] is "debug":
self.log.debug(msg["msg"]) | [
"def",
"handle_logging",
"(",
"self",
")",
":",
"configure_logging",
"(",
"self",
".",
"get_scrapy_options",
"(",
")",
")",
"# Disable duplicates",
"self",
".",
"__scrapy_options",
"[",
"\"LOG_ENABLED\"",
"]",
"=",
"False",
"# Now, after log-level is correctly set, lets... | To allow devs to log as early as possible, logging will already be
handled here | [
"To",
"allow",
"devs",
"to",
"log",
"as",
"early",
"as",
"possible",
"logging",
"will",
"already",
"be",
"handled",
"here"
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/config.py#L148-L166 |
240,104 | fhamborg/news-please | newsplease/config.py | CrawlerConfig.option | def option(self, option):
"""
Gets the option, set_section needs to be set before.
:param option (string): The option to get.
:return mixed: The option from from the config.
"""
if self.__current_section is None:
raise RuntimeError('No section set in option-getting')
return self.__config[self.__current_section][option] | python | def option(self, option):
if self.__current_section is None:
raise RuntimeError('No section set in option-getting')
return self.__config[self.__current_section][option] | [
"def",
"option",
"(",
"self",
",",
"option",
")",
":",
"if",
"self",
".",
"__current_section",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'No section set in option-getting'",
")",
"return",
"self",
".",
"__config",
"[",
"self",
".",
"__current_section",
... | Gets the option, set_section needs to be set before.
:param option (string): The option to get.
:return mixed: The option from from the config. | [
"Gets",
"the",
"option",
"set_section",
"needs",
"to",
"be",
"set",
"before",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/config.py#L194-L203 |
240,105 | fhamborg/news-please | newsplease/config.py | JsonConfig.get_url_array | def get_url_array(self):
"""
Get all url-objects in an array
:return sites (array): The sites from the JSON-file
"""
urlarray = []
for urlobjects in self.__json_object["base_urls"]:
urlarray.append(urlobjects["url"])
return urlarray | python | def get_url_array(self):
urlarray = []
for urlobjects in self.__json_object["base_urls"]:
urlarray.append(urlobjects["url"])
return urlarray | [
"def",
"get_url_array",
"(",
"self",
")",
":",
"urlarray",
"=",
"[",
"]",
"for",
"urlobjects",
"in",
"self",
".",
"__json_object",
"[",
"\"base_urls\"",
"]",
":",
"urlarray",
".",
"append",
"(",
"urlobjects",
"[",
"\"url\"",
"]",
")",
"return",
"urlarray"
... | Get all url-objects in an array
:return sites (array): The sites from the JSON-file | [
"Get",
"all",
"url",
"-",
"objects",
"in",
"an",
"array"
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/config.py#L293-L302 |
240,106 | fhamborg/news-please | newsplease/pipeline/extractor/comparer/comparer_title.py | ComparerTitle.find_matches | def find_matches(self, list_title):
"""Checks if there are any matches between extracted titles.
:param list_title: A list, the extracted titles saved in a list
:return: A list, the matched titles
"""
list_title_matches = []
# Generate every possible tuple of titles and safe the matched string in a list.
for a, b, in itertools.combinations(list_title, 2):
if a == b:
list_title_matches.append(a)
return list_title_matches | python | def find_matches(self, list_title):
list_title_matches = []
# Generate every possible tuple of titles and safe the matched string in a list.
for a, b, in itertools.combinations(list_title, 2):
if a == b:
list_title_matches.append(a)
return list_title_matches | [
"def",
"find_matches",
"(",
"self",
",",
"list_title",
")",
":",
"list_title_matches",
"=",
"[",
"]",
"# Generate every possible tuple of titles and safe the matched string in a list.",
"for",
"a",
",",
"b",
",",
"in",
"itertools",
".",
"combinations",
"(",
"list_title"... | Checks if there are any matches between extracted titles.
:param list_title: A list, the extracted titles saved in a list
:return: A list, the matched titles | [
"Checks",
"if",
"there",
"are",
"any",
"matches",
"between",
"extracted",
"titles",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/comparer/comparer_title.py#L7-L19 |
240,107 | fhamborg/news-please | newsplease/pipeline/extractor/comparer/comparer_title.py | ComparerTitle.extract_match | def extract_match(self, list_title_matches):
"""Extract the title with the most matches from the list.
:param list_title_matches: A list, the extracted titles which match with others
:return: A string, the most frequently extracted title.
"""
# Create a set of the extracted titles
list_title_matches_set = set(list_title_matches)
list_title_count = []
# Count how often a title was matched and safe as tuple in list.
for match in list_title_matches_set:
list_title_count.append((list_title_matches.count(match), match))
if list_title_count and max(list_title_count)[0] != min(list_title_count)[0]:
return max(list_title_count)[1]
return None | python | def extract_match(self, list_title_matches):
# Create a set of the extracted titles
list_title_matches_set = set(list_title_matches)
list_title_count = []
# Count how often a title was matched and safe as tuple in list.
for match in list_title_matches_set:
list_title_count.append((list_title_matches.count(match), match))
if list_title_count and max(list_title_count)[0] != min(list_title_count)[0]:
return max(list_title_count)[1]
return None | [
"def",
"extract_match",
"(",
"self",
",",
"list_title_matches",
")",
":",
"# Create a set of the extracted titles",
"list_title_matches_set",
"=",
"set",
"(",
"list_title_matches",
")",
"list_title_count",
"=",
"[",
"]",
"# Count how often a title was matched and safe as tuple ... | Extract the title with the most matches from the list.
:param list_title_matches: A list, the extracted titles which match with others
:return: A string, the most frequently extracted title. | [
"Extract",
"the",
"title",
"with",
"the",
"most",
"matches",
"from",
"the",
"list",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/comparer/comparer_title.py#L21-L38 |
240,108 | fhamborg/news-please | newsplease/pipeline/extractor/comparer/comparer_title.py | ComparerTitle.extract | def extract(self, item, list_article_candidate):
"""Compares the extracted titles.
: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 title
"""
list_title = []
# Save every title from the candidates in list_title.
for article_candidate in list_article_candidate:
if article_candidate.title is not None:
list_title.append(article_candidate.title)
if not list_title:
return None
# Creates a list with matched titles
list_title_matches = self.find_matches(list_title)
# Extract title with the most matches
matched_title = self.extract_match(list_title_matches)
# Returns the matched title if there is one, else returns the shortest title
if matched_title:
return matched_title
else:
if list_title_matches:
return self.choose_shortest_title(set(list_title_matches))
else:
return self.choose_shortest_title(list_title) | python | def extract(self, item, list_article_candidate):
list_title = []
# Save every title from the candidates in list_title.
for article_candidate in list_article_candidate:
if article_candidate.title is not None:
list_title.append(article_candidate.title)
if not list_title:
return None
# Creates a list with matched titles
list_title_matches = self.find_matches(list_title)
# Extract title with the most matches
matched_title = self.extract_match(list_title_matches)
# Returns the matched title if there is one, else returns the shortest title
if matched_title:
return matched_title
else:
if list_title_matches:
return self.choose_shortest_title(set(list_title_matches))
else:
return self.choose_shortest_title(list_title) | [
"def",
"extract",
"(",
"self",
",",
"item",
",",
"list_article_candidate",
")",
":",
"list_title",
"=",
"[",
"]",
"# Save every title from the candidates in list_title.",
"for",
"article_candidate",
"in",
"list_article_candidate",
":",
"if",
"article_candidate",
".",
"t... | Compares the extracted titles.
: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 title | [
"Compares",
"the",
"extracted",
"titles",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/pipeline/extractor/comparer/comparer_title.py#L53-L82 |
240,109 | fhamborg/news-please | newsplease/__main__.py | cli | def cli(cfg_file_path, resume, reset_elasticsearch, reset_mysql, reset_json, reset_all, no_confirm):
"A generic news crawler and extractor."
if reset_all:
reset_elasticsearch = True
reset_json = True
reset_mysql = True
if cfg_file_path and not cfg_file_path.endswith(os.path.sep):
cfg_file_path += os.path.sep
NewsPleaseLauncher(cfg_file_path, resume, reset_elasticsearch, reset_json, reset_mysql, no_confirm) | python | def cli(cfg_file_path, resume, reset_elasticsearch, reset_mysql, reset_json, reset_all, no_confirm):
"A generic news crawler and extractor."
if reset_all:
reset_elasticsearch = True
reset_json = True
reset_mysql = True
if cfg_file_path and not cfg_file_path.endswith(os.path.sep):
cfg_file_path += os.path.sep
NewsPleaseLauncher(cfg_file_path, resume, reset_elasticsearch, reset_json, reset_mysql, no_confirm) | [
"def",
"cli",
"(",
"cfg_file_path",
",",
"resume",
",",
"reset_elasticsearch",
",",
"reset_mysql",
",",
"reset_json",
",",
"reset_all",
",",
"no_confirm",
")",
":",
"if",
"reset_all",
":",
"reset_elasticsearch",
"=",
"True",
"reset_json",
"=",
"True",
"reset_mys... | A generic news crawler and extractor. | [
"A",
"generic",
"news",
"crawler",
"and",
"extractor",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/__main__.py#L634-L645 |
240,110 | fhamborg/news-please | newsplease/__main__.py | NewsPleaseLauncher.manage_crawlers | def manage_crawlers(self):
"""
Manages all crawlers, threads and limites the number of parallel
running threads.
"""
sites = self.json.get_site_objects()
for index, site in enumerate(sites):
if "daemonize" in site:
self.daemon_list.add_daemon(index, site["daemonize"])
elif "additional_rss_daemon" in site:
self.daemon_list.add_daemon(index,
site["additional_rss_daemon"])
self.crawler_list.append_item(index)
else:
self.crawler_list.append_item(index)
num_threads = self.cfg.section('Crawler')[
'number_of_parallel_crawlers']
if self.crawler_list.len() < num_threads:
num_threads = self.crawler_list.len()
for _ in range(num_threads):
thread = threading.Thread(target=self.manage_crawler,
args=(),
kwargs={})
self.threads.append(thread)
thread.start()
num_daemons = self.cfg.section('Crawler')['number_of_parallel_daemons']
if self.daemon_list.len() < num_daemons:
num_daemons = self.daemon_list.len()
for _ in range(num_daemons):
thread_daemonized = threading.Thread(target=self.manage_daemon,
args=(),
kwargs={})
self.threads_daemonized.append(thread_daemonized)
thread_daemonized.start()
while not self.shutdown:
try:
time.sleep(10)
# if we are not in daemon mode and no crawler is running any longer,
# all articles have been crawled and the tool can shut down
if self.daemon_list.len() == 0 and self.number_of_active_crawlers == 0:
self.graceful_stop()
break
except IOError:
# This exception will only occur on kill-process on windows.
# The process should be killed, thus this exception is
# irrelevant.
pass | python | def manage_crawlers(self):
sites = self.json.get_site_objects()
for index, site in enumerate(sites):
if "daemonize" in site:
self.daemon_list.add_daemon(index, site["daemonize"])
elif "additional_rss_daemon" in site:
self.daemon_list.add_daemon(index,
site["additional_rss_daemon"])
self.crawler_list.append_item(index)
else:
self.crawler_list.append_item(index)
num_threads = self.cfg.section('Crawler')[
'number_of_parallel_crawlers']
if self.crawler_list.len() < num_threads:
num_threads = self.crawler_list.len()
for _ in range(num_threads):
thread = threading.Thread(target=self.manage_crawler,
args=(),
kwargs={})
self.threads.append(thread)
thread.start()
num_daemons = self.cfg.section('Crawler')['number_of_parallel_daemons']
if self.daemon_list.len() < num_daemons:
num_daemons = self.daemon_list.len()
for _ in range(num_daemons):
thread_daemonized = threading.Thread(target=self.manage_daemon,
args=(),
kwargs={})
self.threads_daemonized.append(thread_daemonized)
thread_daemonized.start()
while not self.shutdown:
try:
time.sleep(10)
# if we are not in daemon mode and no crawler is running any longer,
# all articles have been crawled and the tool can shut down
if self.daemon_list.len() == 0 and self.number_of_active_crawlers == 0:
self.graceful_stop()
break
except IOError:
# This exception will only occur on kill-process on windows.
# The process should be killed, thus this exception is
# irrelevant.
pass | [
"def",
"manage_crawlers",
"(",
"self",
")",
":",
"sites",
"=",
"self",
".",
"json",
".",
"get_site_objects",
"(",
")",
"for",
"index",
",",
"site",
"in",
"enumerate",
"(",
"sites",
")",
":",
"if",
"\"daemonize\"",
"in",
"site",
":",
"self",
".",
"daemo... | Manages all crawlers, threads and limites the number of parallel
running threads. | [
"Manages",
"all",
"crawlers",
"threads",
"and",
"limites",
"the",
"number",
"of",
"parallel",
"running",
"threads",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/__main__.py#L152-L204 |
240,111 | fhamborg/news-please | newsplease/__main__.py | NewsPleaseLauncher.manage_crawler | def manage_crawler(self):
"""
Manages a normal crawler thread.
When a crawler finished, it loads another one if there are still sites
to crawl.
"""
index = True
self.number_of_active_crawlers += 1
while not self.shutdown and index is not None:
index = self.crawler_list.get_next_item()
if index is None:
self.number_of_active_crawlers -= 1
break
self.start_crawler(index) | python | def manage_crawler(self):
index = True
self.number_of_active_crawlers += 1
while not self.shutdown and index is not None:
index = self.crawler_list.get_next_item()
if index is None:
self.number_of_active_crawlers -= 1
break
self.start_crawler(index) | [
"def",
"manage_crawler",
"(",
"self",
")",
":",
"index",
"=",
"True",
"self",
".",
"number_of_active_crawlers",
"+=",
"1",
"while",
"not",
"self",
".",
"shutdown",
"and",
"index",
"is",
"not",
"None",
":",
"index",
"=",
"self",
".",
"crawler_list",
".",
... | Manages a normal crawler thread.
When a crawler finished, it loads another one if there are still sites
to crawl. | [
"Manages",
"a",
"normal",
"crawler",
"thread",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/__main__.py#L206-L221 |
240,112 | fhamborg/news-please | newsplease/__main__.py | NewsPleaseLauncher.manage_daemon | def manage_daemon(self):
"""
Manages a daemonized crawler thread.
Once a crawler it finished, it loads the next one.
"""
while not self.shutdown:
# next scheduled daemon, tuple (time, index)
item = self.daemon_list.get_next_item()
cur = time.time()
pajama_time = item[0] - cur
if pajama_time > 0:
self.thread_event.wait(pajama_time)
if not self.shutdown:
self.start_crawler(item[1], daemonize=True) | python | def manage_daemon(self):
while not self.shutdown:
# next scheduled daemon, tuple (time, index)
item = self.daemon_list.get_next_item()
cur = time.time()
pajama_time = item[0] - cur
if pajama_time > 0:
self.thread_event.wait(pajama_time)
if not self.shutdown:
self.start_crawler(item[1], daemonize=True) | [
"def",
"manage_daemon",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"shutdown",
":",
"# next scheduled daemon, tuple (time, index)",
"item",
"=",
"self",
".",
"daemon_list",
".",
"get_next_item",
"(",
")",
"cur",
"=",
"time",
".",
"time",
"(",
")",
"... | Manages a daemonized crawler thread.
Once a crawler it finished, it loads the next one. | [
"Manages",
"a",
"daemonized",
"crawler",
"thread",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/__main__.py#L223-L237 |
240,113 | fhamborg/news-please | newsplease/__main__.py | NewsPleaseLauncher.start_crawler | def start_crawler(self, index, daemonize=False):
"""
Starts a crawler from the input-array.
:param int index: The array-index of the site
:param int daemonize: Bool if the crawler is supposed to be daemonized
(to delete the JOBDIR)
"""
call_process = [sys.executable,
self.__single_crawler,
self.cfg_file_path,
self.json_file_path,
"%s" % index,
"%s" % self.shall_resume,
"%s" % daemonize]
self.log.debug("Calling Process: %s", call_process)
crawler = Popen(call_process,
stderr=None,
stdout=None)
crawler.communicate()
self.crawlers.append(crawler) | python | def start_crawler(self, index, daemonize=False):
call_process = [sys.executable,
self.__single_crawler,
self.cfg_file_path,
self.json_file_path,
"%s" % index,
"%s" % self.shall_resume,
"%s" % daemonize]
self.log.debug("Calling Process: %s", call_process)
crawler = Popen(call_process,
stderr=None,
stdout=None)
crawler.communicate()
self.crawlers.append(crawler) | [
"def",
"start_crawler",
"(",
"self",
",",
"index",
",",
"daemonize",
"=",
"False",
")",
":",
"call_process",
"=",
"[",
"sys",
".",
"executable",
",",
"self",
".",
"__single_crawler",
",",
"self",
".",
"cfg_file_path",
",",
"self",
".",
"json_file_path",
",... | Starts a crawler from the input-array.
:param int index: The array-index of the site
:param int daemonize: Bool if the crawler is supposed to be daemonized
(to delete the JOBDIR) | [
"Starts",
"a",
"crawler",
"from",
"the",
"input",
"-",
"array",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/__main__.py#L239-L261 |
240,114 | fhamborg/news-please | newsplease/__main__.py | NewsPleaseLauncher.graceful_stop | def graceful_stop(self, signal_number=None, stack_frame=None):
"""
This function will be called when a graceful-stop is initiated.
"""
stop_msg = "Hard" if self.shutdown else "Graceful"
if signal_number is None:
self.log.info("%s stop called manually. "
"Shutting down.", stop_msg)
else:
self.log.info("%s stop called by signal #%s. Shutting down."
"Stack Frame: %s",
stop_msg, signal_number, stack_frame)
self.shutdown = True
self.crawler_list.stop()
self.daemon_list.stop()
self.thread_event.set()
return True | python | def graceful_stop(self, signal_number=None, stack_frame=None):
stop_msg = "Hard" if self.shutdown else "Graceful"
if signal_number is None:
self.log.info("%s stop called manually. "
"Shutting down.", stop_msg)
else:
self.log.info("%s stop called by signal #%s. Shutting down."
"Stack Frame: %s",
stop_msg, signal_number, stack_frame)
self.shutdown = True
self.crawler_list.stop()
self.daemon_list.stop()
self.thread_event.set()
return True | [
"def",
"graceful_stop",
"(",
"self",
",",
"signal_number",
"=",
"None",
",",
"stack_frame",
"=",
"None",
")",
":",
"stop_msg",
"=",
"\"Hard\"",
"if",
"self",
".",
"shutdown",
"else",
"\"Graceful\"",
"if",
"signal_number",
"is",
"None",
":",
"self",
".",
"l... | This function will be called when a graceful-stop is initiated. | [
"This",
"function",
"will",
"be",
"called",
"when",
"a",
"graceful",
"-",
"stop",
"is",
"initiated",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/__main__.py#L263-L279 |
240,115 | fhamborg/news-please | newsplease/helper_classes/savepath_parser.py | SavepathParser.time_replacer | def time_replacer(match, timestamp):
"""
Transforms the timestamp to the format the regex match determines.
:param str match: the regex match
:param time timestamp: the timestamp to format with match.group(1)
:return str: the timestamp formated with strftime the way the
regex-match within the first set of braces defines
"""
# match.group(0) = entire match
# match.group(1) = match in braces #1
return time.strftime(match.group(1), time.gmtime(timestamp)) | python | def time_replacer(match, timestamp):
# match.group(0) = entire match
# match.group(1) = match in braces #1
return time.strftime(match.group(1), time.gmtime(timestamp)) | [
"def",
"time_replacer",
"(",
"match",
",",
"timestamp",
")",
":",
"# match.group(0) = entire match",
"# match.group(1) = match in braces #1",
"return",
"time",
".",
"strftime",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"time",
".",
"gmtime",
"(",
"timestamp"... | Transforms the timestamp to the format the regex match determines.
:param str match: the regex match
:param time timestamp: the timestamp to format with match.group(1)
:return str: the timestamp formated with strftime the way the
regex-match within the first set of braces defines | [
"Transforms",
"the",
"timestamp",
"to",
"the",
"format",
"the",
"regex",
"match",
"determines",
"."
] | 731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9 | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/savepath_parser.py#L76-L87 |
240,116 | 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):
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 |
240,117 | 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):
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 |
240,118 | 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):
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 |
240,119 | 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):
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 |
240,120 | 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):
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 |
240,121 | 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):
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 |
240,122 | 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):
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 |
240,123 | 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
):
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 |
240,124 | 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'):
# 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 |
240,125 | 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):
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 |
240,126 | 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):
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 |
240,127 | 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):
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 |
240,128 | 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):
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 |
240,129 | 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):
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 |
240,130 | 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):
# 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 |
240,131 | 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):
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 |
240,132 | 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:
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 |
240,133 | 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):
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 |
240,134 | 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):
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 |
240,135 | 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):
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 |
240,136 | 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):
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 |
240,137 | 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):
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 |
240,138 | 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):
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 |
240,139 | 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):
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 |
240,140 | 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):
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 |
240,141 | 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):
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 |
240,142 | 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):
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 |
240,143 | 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):
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 |
240,144 | 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):
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 |
240,145 | 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):
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 |
240,146 | 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():
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 |
240,147 | 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):
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 |
240,148 | 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):
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 |
240,149 | 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):
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 |
240,150 | 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():
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 |
240,151 | 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):
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 |
240,152 | 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):
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 |
240,153 | 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):
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 |
240,154 | 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):
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 |
240,155 | 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):
# 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 |
240,156 | 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):
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 |
240,157 | 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):
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 |
240,158 | 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):
# 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 |
240,159 | 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):
(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 |
240,160 | 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):
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 |
240,161 | 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):
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 |
240,162 | 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):
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 |
240,163 | 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):
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 |
240,164 | 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):
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 |
240,165 | 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):
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 |
240,166 | 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):
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 |
240,167 | 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):
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 |
240,168 | 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):
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 |
240,169 | 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):
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 |
240,170 | 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):
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 |
240,171 | 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):
# 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 |
240,172 | 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():
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 |
240,173 | 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):
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 |
240,174 | 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):
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 |
240,175 | 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():
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 |
240,176 | 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):
# 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 |
240,177 | 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):
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 |
240,178 | 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):
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 |
240,179 | 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):
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 |
240,180 | 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):
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 |
240,181 | 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):
# 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 |
240,182 | 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):
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 |
240,183 | 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):
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 |
240,184 | 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):
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 |
240,185 | 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):
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 |
240,186 | 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):
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 |
240,187 | 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):
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 |
240,188 | 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):
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 |
240,189 | 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):
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 |
240,190 | 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):
# 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 |
240,191 | 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):
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 |
240,192 | 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):
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 |
240,193 | 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):
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 |
240,194 | 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):
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 |
240,195 | 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):
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 |
240,196 | 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():
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 |
240,197 | 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):
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 |
240,198 | 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):
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 |
240,199 | 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):
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.