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
20,800
davedoesdev/dxf
dxf/__init__.py
DXFBase.list_repos
def list_repos(self, batch_size=None, iterate=False): """ List all repositories in the registry. :param batch_size: Number of repository names to ask the server for at a time. :type batch_size: int :param iterate: Whether to return iterator over the names or a list of all the names. :type iterate: bool :rtype: list or iterator of strings :returns: Repository names. """ it = PaginatingResponse(self, '_base_request', '_catalog', 'repositories', params={'n': batch_size}) return it if iterate else list(it)
python
def list_repos(self, batch_size=None, iterate=False): it = PaginatingResponse(self, '_base_request', '_catalog', 'repositories', params={'n': batch_size}) return it if iterate else list(it)
[ "def", "list_repos", "(", "self", ",", "batch_size", "=", "None", ",", "iterate", "=", "False", ")", ":", "it", "=", "PaginatingResponse", "(", "self", ",", "'_base_request'", ",", "'_catalog'", ",", "'repositories'", ",", "params", "=", "{", "'n'", ":", ...
List all repositories in the registry. :param batch_size: Number of repository names to ask the server for at a time. :type batch_size: int :param iterate: Whether to return iterator over the names or a list of all the names. :type iterate: bool :rtype: list or iterator of strings :returns: Repository names.
[ "List", "all", "repositories", "in", "the", "registry", "." ]
63fad55e0f0086e5f6d3511670db1ef23b5298f6
https://github.com/davedoesdev/dxf/blob/63fad55e0f0086e5f6d3511670db1ef23b5298f6/dxf/__init__.py#L314-L330
20,801
davedoesdev/dxf
dxf/__init__.py
DXF.pull_blob
def pull_blob(self, digest, size=False, chunk_size=None): """ Download a blob from the registry given the hash of its content. :param digest: Hash of the blob's content (prefixed by ``sha256:``). :type digest: str :param size: Whether to return the size of the blob too. :type size: bool :param chunk_size: Number of bytes to download at a time. Defaults to 8192. :type chunk_size: int :rtype: iterator :returns: If ``size`` is falsey, a byte string iterator over the blob's content. If ``size`` is truthy, a tuple containing the iterator and the blob's size. """ if chunk_size is None: chunk_size = 8192 r = self._request('get', 'blobs/' + digest, stream=True) class Chunks(object): # pylint: disable=too-few-public-methods def __iter__(self): sha256 = hashlib.sha256() for chunk in r.iter_content(chunk_size): sha256.update(chunk) yield chunk dgst = 'sha256:' + sha256.hexdigest() if dgst != digest: raise exceptions.DXFDigestMismatchError(dgst, digest) return (Chunks(), long(r.headers['content-length'])) if size else Chunks()
python
def pull_blob(self, digest, size=False, chunk_size=None): if chunk_size is None: chunk_size = 8192 r = self._request('get', 'blobs/' + digest, stream=True) class Chunks(object): # pylint: disable=too-few-public-methods def __iter__(self): sha256 = hashlib.sha256() for chunk in r.iter_content(chunk_size): sha256.update(chunk) yield chunk dgst = 'sha256:' + sha256.hexdigest() if dgst != digest: raise exceptions.DXFDigestMismatchError(dgst, digest) return (Chunks(), long(r.headers['content-length'])) if size else Chunks()
[ "def", "pull_blob", "(", "self", ",", "digest", ",", "size", "=", "False", ",", "chunk_size", "=", "None", ")", ":", "if", "chunk_size", "is", "None", ":", "chunk_size", "=", "8192", "r", "=", "self", ".", "_request", "(", "'get'", ",", "'blobs/'", "...
Download a blob from the registry given the hash of its content. :param digest: Hash of the blob's content (prefixed by ``sha256:``). :type digest: str :param size: Whether to return the size of the blob too. :type size: bool :param chunk_size: Number of bytes to download at a time. Defaults to 8192. :type chunk_size: int :rtype: iterator :returns: If ``size`` is falsey, a byte string iterator over the blob's content. If ``size`` is truthy, a tuple containing the iterator and the blob's size.
[ "Download", "a", "blob", "from", "the", "registry", "given", "the", "hash", "of", "its", "content", "." ]
63fad55e0f0086e5f6d3511670db1ef23b5298f6
https://github.com/davedoesdev/dxf/blob/63fad55e0f0086e5f6d3511670db1ef23b5298f6/dxf/__init__.py#L438-L467
20,802
davedoesdev/dxf
dxf/__init__.py
DXF.blob_size
def blob_size(self, digest): """ Return the size of a blob in the registry given the hash of its content. :param digest: Hash of the blob's content (prefixed by ``sha256:``). :type digest: str :rtype: long :returns: Whether the blob exists. """ r = self._request('head', 'blobs/' + digest) return long(r.headers['content-length'])
python
def blob_size(self, digest): r = self._request('head', 'blobs/' + digest) return long(r.headers['content-length'])
[ "def", "blob_size", "(", "self", ",", "digest", ")", ":", "r", "=", "self", ".", "_request", "(", "'head'", ",", "'blobs/'", "+", "digest", ")", "return", "long", "(", "r", ".", "headers", "[", "'content-length'", "]", ")" ]
Return the size of a blob in the registry given the hash of its content. :param digest: Hash of the blob's content (prefixed by ``sha256:``). :type digest: str :rtype: long :returns: Whether the blob exists.
[ "Return", "the", "size", "of", "a", "blob", "in", "the", "registry", "given", "the", "hash", "of", "its", "content", "." ]
63fad55e0f0086e5f6d3511670db1ef23b5298f6
https://github.com/davedoesdev/dxf/blob/63fad55e0f0086e5f6d3511670db1ef23b5298f6/dxf/__init__.py#L469-L480
20,803
davedoesdev/dxf
dxf/__init__.py
DXF.get_manifest_and_response
def get_manifest_and_response(self, alias): """ Request the manifest for an alias and return the manifest and the response. :param alias: Alias name. :type alias: str :rtype: tuple :returns: Tuple containing the manifest as a string (JSON) and the `requests.Response <http://docs.python-requests.org/en/master/api/#requests.Response>`_ """ r = self._request('get', 'manifests/' + alias, headers={'Accept': _schema2_mimetype + ', ' + _schema1_mimetype}) return r.content.decode('utf-8'), r
python
def get_manifest_and_response(self, alias): r = self._request('get', 'manifests/' + alias, headers={'Accept': _schema2_mimetype + ', ' + _schema1_mimetype}) return r.content.decode('utf-8'), r
[ "def", "get_manifest_and_response", "(", "self", ",", "alias", ")", ":", "r", "=", "self", ".", "_request", "(", "'get'", ",", "'manifests/'", "+", "alias", ",", "headers", "=", "{", "'Accept'", ":", "_schema2_mimetype", "+", "', '", "+", "_schema1_mimetype"...
Request the manifest for an alias and return the manifest and the response. :param alias: Alias name. :type alias: str :rtype: tuple :returns: Tuple containing the manifest as a string (JSON) and the `requests.Response <http://docs.python-requests.org/en/master/api/#requests.Response>`_
[ "Request", "the", "manifest", "for", "an", "alias", "and", "return", "the", "manifest", "and", "the", "response", "." ]
63fad55e0f0086e5f6d3511670db1ef23b5298f6
https://github.com/davedoesdev/dxf/blob/63fad55e0f0086e5f6d3511670db1ef23b5298f6/dxf/__init__.py#L555-L570
20,804
davedoesdev/dxf
dxf/__init__.py
DXF.get_alias
def get_alias(self, alias=None, manifest=None, verify=True, sizes=False, dcd=None): # pylint: disable=too-many-arguments """ Get the blob hashes assigned to an alias. :param alias: Alias name. You almost definitely will only need to pass this argument. :type alias: str :param manifest: If you previously obtained a manifest, specify it here instead of ``alias``. You almost definitely won't need to do this. :type manifest: str :param verify: (v1 schema only) Whether to verify the integrity of the alias definition in the registry itself. You almost definitely won't need to change this from the default (``True``). :type verify: bool :param sizes: Whether to return sizes of the blobs along with their hashes :type sizes: bool :param dcd: (if ``manifest`` is specified) The Docker-Content-Digest header returned when getting the manifest. If present, this is checked against the manifest. :type dcd: str :rtype: list :returns: If ``sizes`` is falsey, a list of blob hashes (strings) which are assigned to the alias. If ``sizes`` is truthy, a list of (hash,size) tuples for each blob. """ return self._get_alias(alias, manifest, verify, sizes, dcd, False)
python
def get_alias(self, alias=None, manifest=None, verify=True, sizes=False, dcd=None): # pylint: disable=too-many-arguments return self._get_alias(alias, manifest, verify, sizes, dcd, False)
[ "def", "get_alias", "(", "self", ",", "alias", "=", "None", ",", "manifest", "=", "None", ",", "verify", "=", "True", ",", "sizes", "=", "False", ",", "dcd", "=", "None", ")", ":", "# pylint: disable=too-many-arguments", "return", "self", ".", "_get_alias"...
Get the blob hashes assigned to an alias. :param alias: Alias name. You almost definitely will only need to pass this argument. :type alias: str :param manifest: If you previously obtained a manifest, specify it here instead of ``alias``. You almost definitely won't need to do this. :type manifest: str :param verify: (v1 schema only) Whether to verify the integrity of the alias definition in the registry itself. You almost definitely won't need to change this from the default (``True``). :type verify: bool :param sizes: Whether to return sizes of the blobs along with their hashes :type sizes: bool :param dcd: (if ``manifest`` is specified) The Docker-Content-Digest header returned when getting the manifest. If present, this is checked against the manifest. :type dcd: str :rtype: list :returns: If ``sizes`` is falsey, a list of blob hashes (strings) which are assigned to the alias. If ``sizes`` is truthy, a list of (hash,size) tuples for each blob.
[ "Get", "the", "blob", "hashes", "assigned", "to", "an", "alias", "." ]
63fad55e0f0086e5f6d3511670db1ef23b5298f6
https://github.com/davedoesdev/dxf/blob/63fad55e0f0086e5f6d3511670db1ef23b5298f6/dxf/__init__.py#L630-L658
20,805
davedoesdev/dxf
dxf/__init__.py
DXF._get_dcd
def _get_dcd(self, alias): """ Get the Docker-Content-Digest header for an alias. :param alias: Alias name. :type alias: str :rtype: str :returns: DCD header for the alias. """ # https://docs.docker.com/registry/spec/api/#deleting-an-image # Note When deleting a manifest from a registry version 2.3 or later, # the following header must be used when HEAD or GET-ing the manifest # to obtain the correct digest to delete: # Accept: application/vnd.docker.distribution.manifest.v2+json return self._request( 'head', 'manifests/{}'.format(alias), headers={'Accept': _schema2_mimetype}, ).headers.get('Docker-Content-Digest')
python
def _get_dcd(self, alias): # https://docs.docker.com/registry/spec/api/#deleting-an-image # Note When deleting a manifest from a registry version 2.3 or later, # the following header must be used when HEAD or GET-ing the manifest # to obtain the correct digest to delete: # Accept: application/vnd.docker.distribution.manifest.v2+json return self._request( 'head', 'manifests/{}'.format(alias), headers={'Accept': _schema2_mimetype}, ).headers.get('Docker-Content-Digest')
[ "def", "_get_dcd", "(", "self", ",", "alias", ")", ":", "# https://docs.docker.com/registry/spec/api/#deleting-an-image", "# Note When deleting a manifest from a registry version 2.3 or later,", "# the following header must be used when HEAD or GET-ing the manifest", "# to obtain the correct d...
Get the Docker-Content-Digest header for an alias. :param alias: Alias name. :type alias: str :rtype: str :returns: DCD header for the alias.
[ "Get", "the", "Docker", "-", "Content", "-", "Digest", "header", "for", "an", "alias", "." ]
63fad55e0f0086e5f6d3511670db1ef23b5298f6
https://github.com/davedoesdev/dxf/blob/63fad55e0f0086e5f6d3511670db1ef23b5298f6/dxf/__init__.py#L691-L710
20,806
shinichi-takii/ddlparse
ddlparse/ddlparse.py
DdlParseTableColumnBase.get_name
def get_name(self, name_case=DdlParseBase.NAME_CASE.original): """ Get Name converted case :param name_case: name case type * DdlParse.NAME_CASE.original : Return to no convert * DdlParse.NAME_CASE.lower : Return to lower * DdlParse.NAME_CASE.upper : Return to upper :return: name """ if name_case == self.NAME_CASE.lower: return self._name.lower() elif name_case == self.NAME_CASE.upper: return self._name.upper() else: return self._name
python
def get_name(self, name_case=DdlParseBase.NAME_CASE.original): if name_case == self.NAME_CASE.lower: return self._name.lower() elif name_case == self.NAME_CASE.upper: return self._name.upper() else: return self._name
[ "def", "get_name", "(", "self", ",", "name_case", "=", "DdlParseBase", ".", "NAME_CASE", ".", "original", ")", ":", "if", "name_case", "==", "self", ".", "NAME_CASE", ".", "lower", ":", "return", "self", ".", "_name", ".", "lower", "(", ")", "elif", "n...
Get Name converted case :param name_case: name case type * DdlParse.NAME_CASE.original : Return to no convert * DdlParse.NAME_CASE.lower : Return to lower * DdlParse.NAME_CASE.upper : Return to upper :return: name
[ "Get", "Name", "converted", "case" ]
7328656ee807d14960999a98ace8cd76f0fe3ff8
https://github.com/shinichi-takii/ddlparse/blob/7328656ee807d14960999a98ace8cd76f0fe3ff8/ddlparse/ddlparse.py#L55-L71
20,807
shinichi-takii/ddlparse
ddlparse/ddlparse.py
DdlParseColumn.bigquery_data_type
def bigquery_data_type(self): """Get BigQuery Legacy SQL data type""" # BigQuery data type = {source_database: [data type, ...], ...} BQ_DATA_TYPE_DIC = OrderedDict() BQ_DATA_TYPE_DIC["STRING"] = {None: [re.compile(r"(CHAR|TEXT|CLOB|JSON|UUID)")]} BQ_DATA_TYPE_DIC["INTEGER"] = {None: [re.compile(r"INT|SERIAL|YEAR")]} BQ_DATA_TYPE_DIC["FLOAT"] = {None: [re.compile(r"(FLOAT|DOUBLE)"), "REAL", "MONEY"]} BQ_DATA_TYPE_DIC["DATETIME"] = { None: ["DATETIME", "TIMESTAMP", "TIMESTAMP WITHOUT TIME ZONE"], self.DATABASE.oracle: ["DATE"] } BQ_DATA_TYPE_DIC["TIMESTAMP"] = {None: ["TIMESTAMPTZ", "TIMESTAMP WITH TIME ZONE"]} BQ_DATA_TYPE_DIC["DATE"] = {None: ["DATE"]} BQ_DATA_TYPE_DIC["TIME"] = {None: ["TIME"]} BQ_DATA_TYPE_DIC["BOOLEAN"] = {None: [re.compile(r"BOOL")]} for bq_type, conditions in BQ_DATA_TYPE_DIC.items(): for source_db, source_datatypes in conditions.items(): for source_datatype in source_datatypes: if isinstance(source_datatype, str): if self._data_type == source_datatype \ and ( self._source_database == source_db or (self._source_database is not None and source_db is None)): return bq_type elif re.search(source_datatype, self._data_type) \ and ( self._source_database == source_db or (self._source_database is not None and source_db is None)): return bq_type if self._data_type in ["NUMERIC", "NUMBER", "DECIMAL"]: if self._scale is not None: return "FLOAT" if self._data_type == "NUMBER" \ and self._source_database == self.DATABASE.oracle \ and self._length is None: return "FLOAT" return "INTEGER" raise ValueError("Unknown data type : '{}'".format(self._data_type))
python
def bigquery_data_type(self): # BigQuery data type = {source_database: [data type, ...], ...} BQ_DATA_TYPE_DIC = OrderedDict() BQ_DATA_TYPE_DIC["STRING"] = {None: [re.compile(r"(CHAR|TEXT|CLOB|JSON|UUID)")]} BQ_DATA_TYPE_DIC["INTEGER"] = {None: [re.compile(r"INT|SERIAL|YEAR")]} BQ_DATA_TYPE_DIC["FLOAT"] = {None: [re.compile(r"(FLOAT|DOUBLE)"), "REAL", "MONEY"]} BQ_DATA_TYPE_DIC["DATETIME"] = { None: ["DATETIME", "TIMESTAMP", "TIMESTAMP WITHOUT TIME ZONE"], self.DATABASE.oracle: ["DATE"] } BQ_DATA_TYPE_DIC["TIMESTAMP"] = {None: ["TIMESTAMPTZ", "TIMESTAMP WITH TIME ZONE"]} BQ_DATA_TYPE_DIC["DATE"] = {None: ["DATE"]} BQ_DATA_TYPE_DIC["TIME"] = {None: ["TIME"]} BQ_DATA_TYPE_DIC["BOOLEAN"] = {None: [re.compile(r"BOOL")]} for bq_type, conditions in BQ_DATA_TYPE_DIC.items(): for source_db, source_datatypes in conditions.items(): for source_datatype in source_datatypes: if isinstance(source_datatype, str): if self._data_type == source_datatype \ and ( self._source_database == source_db or (self._source_database is not None and source_db is None)): return bq_type elif re.search(source_datatype, self._data_type) \ and ( self._source_database == source_db or (self._source_database is not None and source_db is None)): return bq_type if self._data_type in ["NUMERIC", "NUMBER", "DECIMAL"]: if self._scale is not None: return "FLOAT" if self._data_type == "NUMBER" \ and self._source_database == self.DATABASE.oracle \ and self._length is None: return "FLOAT" return "INTEGER" raise ValueError("Unknown data type : '{}'".format(self._data_type))
[ "def", "bigquery_data_type", "(", "self", ")", ":", "# BigQuery data type = {source_database: [data type, ...], ...}", "BQ_DATA_TYPE_DIC", "=", "OrderedDict", "(", ")", "BQ_DATA_TYPE_DIC", "[", "\"STRING\"", "]", "=", "{", "None", ":", "[", "re", ".", "compile", "(", ...
Get BigQuery Legacy SQL data type
[ "Get", "BigQuery", "Legacy", "SQL", "data", "type" ]
7328656ee807d14960999a98ace8cd76f0fe3ff8
https://github.com/shinichi-takii/ddlparse/blob/7328656ee807d14960999a98ace8cd76f0fe3ff8/ddlparse/ddlparse.py#L173-L216
20,808
shinichi-takii/ddlparse
ddlparse/ddlparse.py
DdlParseColumn.to_bigquery_field
def to_bigquery_field(self, name_case=DdlParseBase.NAME_CASE.original): """Generate BigQuery JSON field define""" col_name = self.get_name(name_case) mode = self.bigquery_mode if self.array_dimensional <= 1: # no or one dimensional array data type type = self.bigquery_legacy_data_type else: # multiple dimensional array data type type = "RECORD" fields = OrderedDict() fields_cur = fields for i in range(1, self.array_dimensional): is_last = True if i == self.array_dimensional - 1 else False fields_cur['fields'] = [OrderedDict()] fields_cur = fields_cur['fields'][0] fields_cur['name'] = "dimension_{}".format(i) fields_cur['type'] = self.bigquery_legacy_data_type if is_last else "RECORD" fields_cur['mode'] = self.bigquery_mode if is_last else "REPEATED" col = OrderedDict() col['name'] = col_name col['type'] = type col['mode'] = mode if self.array_dimensional > 1: col['fields'] = fields['fields'] return json.dumps(col)
python
def to_bigquery_field(self, name_case=DdlParseBase.NAME_CASE.original): col_name = self.get_name(name_case) mode = self.bigquery_mode if self.array_dimensional <= 1: # no or one dimensional array data type type = self.bigquery_legacy_data_type else: # multiple dimensional array data type type = "RECORD" fields = OrderedDict() fields_cur = fields for i in range(1, self.array_dimensional): is_last = True if i == self.array_dimensional - 1 else False fields_cur['fields'] = [OrderedDict()] fields_cur = fields_cur['fields'][0] fields_cur['name'] = "dimension_{}".format(i) fields_cur['type'] = self.bigquery_legacy_data_type if is_last else "RECORD" fields_cur['mode'] = self.bigquery_mode if is_last else "REPEATED" col = OrderedDict() col['name'] = col_name col['type'] = type col['mode'] = mode if self.array_dimensional > 1: col['fields'] = fields['fields'] return json.dumps(col)
[ "def", "to_bigquery_field", "(", "self", ",", "name_case", "=", "DdlParseBase", ".", "NAME_CASE", ".", "original", ")", ":", "col_name", "=", "self", ".", "get_name", "(", "name_case", ")", "mode", "=", "self", ".", "bigquery_mode", "if", "self", ".", "arr...
Generate BigQuery JSON field define
[ "Generate", "BigQuery", "JSON", "field", "define" ]
7328656ee807d14960999a98ace8cd76f0fe3ff8
https://github.com/shinichi-takii/ddlparse/blob/7328656ee807d14960999a98ace8cd76f0fe3ff8/ddlparse/ddlparse.py#L250-L284
20,809
shinichi-takii/ddlparse
ddlparse/ddlparse.py
DdlParseTable.to_bigquery_ddl
def to_bigquery_ddl(self, name_case=DdlParseBase.NAME_CASE.original): """ Generate BigQuery CREATE TABLE statements :param name_case: name case type * DdlParse.NAME_CASE.original : Return to no convert * DdlParse.NAME_CASE.lower : Return to lower * DdlParse.NAME_CASE.upper : Return to upper :return: BigQuery CREATE TABLE statements """ if self.schema is None: dataset = "dataset" elif name_case == self.NAME_CASE.lower: dataset = self.schema.lower() elif name_case == self.NAME_CASE.upper: dataset = self.schema.upper() else: dataset = self.schema cols_defs = [] for col in self.columns.values(): col_name = col.get_name(name_case) if col.array_dimensional < 1: # no array data type type = col.bigquery_standard_data_type not_null = " NOT NULL" if col.not_null else "" else: # one or multiple dimensional array data type type_front = "ARRAY<" type_back = ">" for i in range(1, col.array_dimensional): type_front += "STRUCT<dimension_{} ARRAY<".format(i) type_back += ">>" type = "{}{}{}".format(type_front, col.bigquery_standard_data_type, type_back) not_null = "" cols_defs.append("{name} {type}{not_null}".format( name=col_name, type=type, not_null=not_null, )) return textwrap.dedent( """\ #standardSQL CREATE TABLE `project.{dataset}.{table}` ( {colmns_define} )""").format( dataset=dataset, table=self.get_name(name_case), colmns_define=",\n ".join(cols_defs), )
python
def to_bigquery_ddl(self, name_case=DdlParseBase.NAME_CASE.original): if self.schema is None: dataset = "dataset" elif name_case == self.NAME_CASE.lower: dataset = self.schema.lower() elif name_case == self.NAME_CASE.upper: dataset = self.schema.upper() else: dataset = self.schema cols_defs = [] for col in self.columns.values(): col_name = col.get_name(name_case) if col.array_dimensional < 1: # no array data type type = col.bigquery_standard_data_type not_null = " NOT NULL" if col.not_null else "" else: # one or multiple dimensional array data type type_front = "ARRAY<" type_back = ">" for i in range(1, col.array_dimensional): type_front += "STRUCT<dimension_{} ARRAY<".format(i) type_back += ">>" type = "{}{}{}".format(type_front, col.bigquery_standard_data_type, type_back) not_null = "" cols_defs.append("{name} {type}{not_null}".format( name=col_name, type=type, not_null=not_null, )) return textwrap.dedent( """\ #standardSQL CREATE TABLE `project.{dataset}.{table}` ( {colmns_define} )""").format( dataset=dataset, table=self.get_name(name_case), colmns_define=",\n ".join(cols_defs), )
[ "def", "to_bigquery_ddl", "(", "self", ",", "name_case", "=", "DdlParseBase", ".", "NAME_CASE", ".", "original", ")", ":", "if", "self", ".", "schema", "is", "None", ":", "dataset", "=", "\"dataset\"", "elif", "name_case", "==", "self", ".", "NAME_CASE", "...
Generate BigQuery CREATE TABLE statements :param name_case: name case type * DdlParse.NAME_CASE.original : Return to no convert * DdlParse.NAME_CASE.lower : Return to lower * DdlParse.NAME_CASE.upper : Return to upper :return: BigQuery CREATE TABLE statements
[ "Generate", "BigQuery", "CREATE", "TABLE", "statements" ]
7328656ee807d14960999a98ace8cd76f0fe3ff8
https://github.com/shinichi-takii/ddlparse/blob/7328656ee807d14960999a98ace8cd76f0fe3ff8/ddlparse/ddlparse.py#L393-L450
20,810
shinichi-takii/ddlparse
ddlparse/ddlparse.py
DdlParse.parse
def parse(self, ddl=None, source_database=None): """ Parse DDL script. :param ddl: DDL script :return: DdlParseTable, Parsed table define info. """ if ddl is not None: self._ddl = ddl if source_database is not None: self.source_database = source_database if self._ddl is None: raise ValueError("DDL is not specified") ret = self._DDL_PARSE_EXPR.parseString(self._ddl) # print(ret.dump()) if "schema" in ret: self._table.schema = ret["schema"] self._table.name = ret["table"] self._table.is_temp = True if "temp" in ret else False for ret_col in ret["columns"]: if ret_col.getName() == "column": # add column col = self._table.columns.append( column_name=ret_col["name"], data_type_array=ret_col["type"], array_brackets=ret_col['array_brackets'] if "array_brackets" in ret_col else None) if "constraint" in ret_col: col.constraint = ret_col["constraint"] elif ret_col.getName() == "constraint": # set column constraint for col_name in ret_col["constraint_columns"]: col = self._table.columns[col_name] if ret_col["type"] == "PRIMARY KEY": col.not_null = True col.primary_key = True elif ret_col["type"] in ["UNIQUE", "UNIQUE KEY"]: col.unique = True elif ret_col["type"] == "NOT NULL": col.not_null = True return self._table
python
def parse(self, ddl=None, source_database=None): if ddl is not None: self._ddl = ddl if source_database is not None: self.source_database = source_database if self._ddl is None: raise ValueError("DDL is not specified") ret = self._DDL_PARSE_EXPR.parseString(self._ddl) # print(ret.dump()) if "schema" in ret: self._table.schema = ret["schema"] self._table.name = ret["table"] self._table.is_temp = True if "temp" in ret else False for ret_col in ret["columns"]: if ret_col.getName() == "column": # add column col = self._table.columns.append( column_name=ret_col["name"], data_type_array=ret_col["type"], array_brackets=ret_col['array_brackets'] if "array_brackets" in ret_col else None) if "constraint" in ret_col: col.constraint = ret_col["constraint"] elif ret_col.getName() == "constraint": # set column constraint for col_name in ret_col["constraint_columns"]: col = self._table.columns[col_name] if ret_col["type"] == "PRIMARY KEY": col.not_null = True col.primary_key = True elif ret_col["type"] in ["UNIQUE", "UNIQUE KEY"]: col.unique = True elif ret_col["type"] == "NOT NULL": col.not_null = True return self._table
[ "def", "parse", "(", "self", ",", "ddl", "=", "None", ",", "source_database", "=", "None", ")", ":", "if", "ddl", "is", "not", "None", ":", "self", ".", "_ddl", "=", "ddl", "if", "source_database", "is", "not", "None", ":", "self", ".", "source_datab...
Parse DDL script. :param ddl: DDL script :return: DdlParseTable, Parsed table define info.
[ "Parse", "DDL", "script", "." ]
7328656ee807d14960999a98ace8cd76f0fe3ff8
https://github.com/shinichi-takii/ddlparse/blob/7328656ee807d14960999a98ace8cd76f0fe3ff8/ddlparse/ddlparse.py#L540-L591
20,811
rhelmot/nclib
nclib/process.py
Process.launch
def launch(program, sock, stderr=True, cwd=None, env=None): """ A static method for launching a process that is connected to a given socket. Same rules from the Process constructor apply. """ if stderr is True: err = sock # redirect to socket elif stderr is False: err = open(os.devnull, 'wb') # hide elif stderr is None: err = None # redirect to console p = subprocess.Popen(program, shell=type(program) not in (list, tuple), stdin=sock, stdout=sock, stderr=err, cwd=cwd, env=env, close_fds=True) sock.close() return p
python
def launch(program, sock, stderr=True, cwd=None, env=None): if stderr is True: err = sock # redirect to socket elif stderr is False: err = open(os.devnull, 'wb') # hide elif stderr is None: err = None # redirect to console p = subprocess.Popen(program, shell=type(program) not in (list, tuple), stdin=sock, stdout=sock, stderr=err, cwd=cwd, env=env, close_fds=True) sock.close() return p
[ "def", "launch", "(", "program", ",", "sock", ",", "stderr", "=", "True", ",", "cwd", "=", "None", ",", "env", "=", "None", ")", ":", "if", "stderr", "is", "True", ":", "err", "=", "sock", "# redirect to socket", "elif", "stderr", "is", "False", ":",...
A static method for launching a process that is connected to a given socket. Same rules from the Process constructor apply.
[ "A", "static", "method", "for", "launching", "a", "process", "that", "is", "connected", "to", "a", "given", "socket", ".", "Same", "rules", "from", "the", "Process", "constructor", "apply", "." ]
6147779766557ee4fafcbae683bdd2f74157e825
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/process.py#L85-L104
20,812
rhelmot/nclib
nclib/server.py
UDPServer.respond
def respond(self, packet, peer, flags=0): """ Send a message back to a peer. :param packet: The data to send :param peer: The address to send to, as a tuple (host, port) :param flags: Any sending flags you want to use for some reason """ self.sock.sendto(packet, flags, peer)
python
def respond(self, packet, peer, flags=0): self.sock.sendto(packet, flags, peer)
[ "def", "respond", "(", "self", ",", "packet", ",", "peer", ",", "flags", "=", "0", ")", ":", "self", ".", "sock", ".", "sendto", "(", "packet", ",", "flags", ",", "peer", ")" ]
Send a message back to a peer. :param packet: The data to send :param peer: The address to send to, as a tuple (host, port) :param flags: Any sending flags you want to use for some reason
[ "Send", "a", "message", "back", "to", "a", "peer", "." ]
6147779766557ee4fafcbae683bdd2f74157e825
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/server.py#L75-L83
20,813
rhelmot/nclib
nclib/netcat.py
Netcat.shutdown_rd
def shutdown_rd(self): """ Send a shutdown signal for reading - you may no longer read from this socket. """ if self._sock_send is not None: self.sock.close() else: return self.shutdown(socket.SHUT_RD)
python
def shutdown_rd(self): if self._sock_send is not None: self.sock.close() else: return self.shutdown(socket.SHUT_RD)
[ "def", "shutdown_rd", "(", "self", ")", ":", "if", "self", ".", "_sock_send", "is", "not", "None", ":", "self", ".", "sock", ".", "close", "(", ")", "else", ":", "return", "self", ".", "shutdown", "(", "socket", ".", "SHUT_RD", ")" ]
Send a shutdown signal for reading - you may no longer read from this socket.
[ "Send", "a", "shutdown", "signal", "for", "reading", "-", "you", "may", "no", "longer", "read", "from", "this", "socket", "." ]
6147779766557ee4fafcbae683bdd2f74157e825
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L443-L451
20,814
rhelmot/nclib
nclib/netcat.py
Netcat.shutdown_wr
def shutdown_wr(self): """ Send a shutdown signal for writing - you may no longer write to this socket. """ if self._sock_send is not None: self._sock_send.close() else: return self.shutdown(socket.SHUT_WR)
python
def shutdown_wr(self): if self._sock_send is not None: self._sock_send.close() else: return self.shutdown(socket.SHUT_WR)
[ "def", "shutdown_wr", "(", "self", ")", ":", "if", "self", ".", "_sock_send", "is", "not", "None", ":", "self", ".", "_sock_send", ".", "close", "(", ")", "else", ":", "return", "self", ".", "shutdown", "(", "socket", ".", "SHUT_WR", ")" ]
Send a shutdown signal for writing - you may no longer write to this socket.
[ "Send", "a", "shutdown", "signal", "for", "writing", "-", "you", "may", "no", "longer", "write", "to", "this", "socket", "." ]
6147779766557ee4fafcbae683bdd2f74157e825
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L453-L461
20,815
rhelmot/nclib
nclib/netcat.py
Netcat._recv_predicate
def _recv_predicate(self, predicate, timeout='default', raise_eof=True): """ Receive until predicate returns a positive integer. The returned number is the size to return. """ if timeout == 'default': timeout = self._timeout self.timed_out = False start = time.time() try: while True: cut_at = predicate(self.buf) if cut_at > 0: break if timeout is not None: time_elapsed = time.time() - start if time_elapsed > timeout: raise socket.timeout self._settimeout(timeout - time_elapsed) data = self._recv(4096) self._log_recv(data, False) self.buf += data if not data: if raise_eof: raise NetcatError("Connection dropped!") cut_at = len(self.buf) break except KeyboardInterrupt: self._print_header('\n======== Connection interrupted! ========') raise except socket.timeout: self.timed_out = True if self._raise_timeout: raise NetcatTimeout() return b'' except socket.error as exc: raise NetcatError('Socket error: %r' % exc) self._settimeout(self._timeout) ret = self.buf[:cut_at] self.buf = self.buf[cut_at:] self._log_recv(ret, True) return ret
python
def _recv_predicate(self, predicate, timeout='default', raise_eof=True): if timeout == 'default': timeout = self._timeout self.timed_out = False start = time.time() try: while True: cut_at = predicate(self.buf) if cut_at > 0: break if timeout is not None: time_elapsed = time.time() - start if time_elapsed > timeout: raise socket.timeout self._settimeout(timeout - time_elapsed) data = self._recv(4096) self._log_recv(data, False) self.buf += data if not data: if raise_eof: raise NetcatError("Connection dropped!") cut_at = len(self.buf) break except KeyboardInterrupt: self._print_header('\n======== Connection interrupted! ========') raise except socket.timeout: self.timed_out = True if self._raise_timeout: raise NetcatTimeout() return b'' except socket.error as exc: raise NetcatError('Socket error: %r' % exc) self._settimeout(self._timeout) ret = self.buf[:cut_at] self.buf = self.buf[cut_at:] self._log_recv(ret, True) return ret
[ "def", "_recv_predicate", "(", "self", ",", "predicate", ",", "timeout", "=", "'default'", ",", "raise_eof", "=", "True", ")", ":", "if", "timeout", "==", "'default'", ":", "timeout", "=", "self", ".", "_timeout", "self", ".", "timed_out", "=", "False", ...
Receive until predicate returns a positive integer. The returned number is the size to return.
[ "Receive", "until", "predicate", "returns", "a", "positive", "integer", ".", "The", "returned", "number", "is", "the", "size", "to", "return", "." ]
6147779766557ee4fafcbae683bdd2f74157e825
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L569-L618
20,816
rhelmot/nclib
nclib/netcat.py
Netcat.recv_until
def recv_until(self, s, max_size=None, timeout='default'): """ Recieve data from the socket until the given substring is observed. Data in the same datagram as the substring, following the substring, will not be returned and will be cached for future receives. Aliases: read_until, readuntil, recvuntil """ self._print_recv_header( '======== Receiving until {0}{timeout_text} ========', timeout, repr(s)) if max_size is None: max_size = 2 ** 62 def _predicate(buf): try: return min(buf.index(s) + len(s), max_size) except ValueError: return 0 if len(buf) < max_size else max_size return self._recv_predicate(_predicate, timeout)
python
def recv_until(self, s, max_size=None, timeout='default'): self._print_recv_header( '======== Receiving until {0}{timeout_text} ========', timeout, repr(s)) if max_size is None: max_size = 2 ** 62 def _predicate(buf): try: return min(buf.index(s) + len(s), max_size) except ValueError: return 0 if len(buf) < max_size else max_size return self._recv_predicate(_predicate, timeout)
[ "def", "recv_until", "(", "self", ",", "s", ",", "max_size", "=", "None", ",", "timeout", "=", "'default'", ")", ":", "self", ".", "_print_recv_header", "(", "'======== Receiving until {0}{timeout_text} ========'", ",", "timeout", ",", "repr", "(", "s", ")", "...
Recieve data from the socket until the given substring is observed. Data in the same datagram as the substring, following the substring, will not be returned and will be cached for future receives. Aliases: read_until, readuntil, recvuntil
[ "Recieve", "data", "from", "the", "socket", "until", "the", "given", "substring", "is", "observed", ".", "Data", "in", "the", "same", "datagram", "as", "the", "substring", "following", "the", "substring", "will", "not", "be", "returned", "and", "will", "be",...
6147779766557ee4fafcbae683bdd2f74157e825
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L652-L672
20,817
rhelmot/nclib
nclib/netcat.py
Netcat.recv_all
def recv_all(self, timeout='default'): """ Return all data recieved until connection closes. Aliases: read_all, readall, recvall """ self._print_recv_header('======== Receiving until close{timeout_text} ========', timeout) return self._recv_predicate(lambda s: 0, timeout, raise_eof=False)
python
def recv_all(self, timeout='default'): self._print_recv_header('======== Receiving until close{timeout_text} ========', timeout) return self._recv_predicate(lambda s: 0, timeout, raise_eof=False)
[ "def", "recv_all", "(", "self", ",", "timeout", "=", "'default'", ")", ":", "self", ".", "_print_recv_header", "(", "'======== Receiving until close{timeout_text} ========'", ",", "timeout", ")", "return", "self", ".", "_recv_predicate", "(", "lambda", "s", ":", "...
Return all data recieved until connection closes. Aliases: read_all, readall, recvall
[ "Return", "all", "data", "recieved", "until", "connection", "closes", "." ]
6147779766557ee4fafcbae683bdd2f74157e825
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L674-L683
20,818
rhelmot/nclib
nclib/netcat.py
Netcat.recv_exactly
def recv_exactly(self, n, timeout='default'): """ Recieve exactly n bytes Aliases: read_exactly, readexactly, recvexactly """ self._print_recv_header( '======== Receiving until exactly {0}B{timeout_text} ========', timeout, n) return self._recv_predicate(lambda s: n if len(s) >= n else 0, timeout)
python
def recv_exactly(self, n, timeout='default'): self._print_recv_header( '======== Receiving until exactly {0}B{timeout_text} ========', timeout, n) return self._recv_predicate(lambda s: n if len(s) >= n else 0, timeout)
[ "def", "recv_exactly", "(", "self", ",", "n", ",", "timeout", "=", "'default'", ")", ":", "self", ".", "_print_recv_header", "(", "'======== Receiving until exactly {0}B{timeout_text} ========'", ",", "timeout", ",", "n", ")", "return", "self", ".", "_recv_predicate...
Recieve exactly n bytes Aliases: read_exactly, readexactly, recvexactly
[ "Recieve", "exactly", "n", "bytes" ]
6147779766557ee4fafcbae683bdd2f74157e825
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L685-L695
20,819
rhelmot/nclib
nclib/netcat.py
Netcat.send
def send(self, s): """ Sends all the given data to the socket. Aliases: write, put, sendall, send_all """ self._print_header('======== Sending ({0}) ========'.format(len(s))) self._log_send(s) out = len(s) while s: s = s[self._send(s):] return out
python
def send(self, s): self._print_header('======== Sending ({0}) ========'.format(len(s))) self._log_send(s) out = len(s) while s: s = s[self._send(s):] return out
[ "def", "send", "(", "self", ",", "s", ")", ":", "self", ".", "_print_header", "(", "'======== Sending ({0}) ========'", ".", "format", "(", "len", "(", "s", ")", ")", ")", "self", ".", "_log_send", "(", "s", ")", "out", "=", "len", "(", "s", ")", "...
Sends all the given data to the socket. Aliases: write, put, sendall, send_all
[ "Sends", "all", "the", "given", "data", "to", "the", "socket", "." ]
6147779766557ee4fafcbae683bdd2f74157e825
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L697-L710
20,820
rhelmot/nclib
nclib/netcat.py
Netcat.interact
def interact(self, insock=sys.stdin, outsock=sys.stdout): """ Connects the socket to the terminal for user interaction. Alternate input and output files may be specified. This method cannot be used with a timeout. Aliases: interactive, interaction """ self._print_header('======== Beginning interactive session ========') if hasattr(outsock, 'buffer'): outsock = outsock.buffer # pylint: disable=no-member self.timed_out = False save_verbose = self.verbose self.verbose = 0 try: if self.buf: outsock.write(self.buf) outsock.flush() self.buf = b'' while True: readable_socks = select(self.sock, insock) for readable in readable_socks: if readable is insock: data = os.read(insock.fileno(), 4096) self.send(data) if not data: raise NetcatError else: data = self.recv(timeout=None) outsock.write(data) outsock.flush() if not data: raise NetcatError except KeyboardInterrupt: self.verbose = save_verbose self._print_header('\n======== Connection interrupted! ========') raise except (socket.error, NetcatError): self.verbose = save_verbose self._print_header('\n======== Connection dropped! ========') finally: self.verbose = save_verbose
python
def interact(self, insock=sys.stdin, outsock=sys.stdout): self._print_header('======== Beginning interactive session ========') if hasattr(outsock, 'buffer'): outsock = outsock.buffer # pylint: disable=no-member self.timed_out = False save_verbose = self.verbose self.verbose = 0 try: if self.buf: outsock.write(self.buf) outsock.flush() self.buf = b'' while True: readable_socks = select(self.sock, insock) for readable in readable_socks: if readable is insock: data = os.read(insock.fileno(), 4096) self.send(data) if not data: raise NetcatError else: data = self.recv(timeout=None) outsock.write(data) outsock.flush() if not data: raise NetcatError except KeyboardInterrupt: self.verbose = save_verbose self._print_header('\n======== Connection interrupted! ========') raise except (socket.error, NetcatError): self.verbose = save_verbose self._print_header('\n======== Connection dropped! ========') finally: self.verbose = save_verbose
[ "def", "interact", "(", "self", ",", "insock", "=", "sys", ".", "stdin", ",", "outsock", "=", "sys", ".", "stdout", ")", ":", "self", ".", "_print_header", "(", "'======== Beginning interactive session ========'", ")", "if", "hasattr", "(", "outsock", ",", "...
Connects the socket to the terminal for user interaction. Alternate input and output files may be specified. This method cannot be used with a timeout. Aliases: interactive, interaction
[ "Connects", "the", "socket", "to", "the", "terminal", "for", "user", "interaction", ".", "Alternate", "input", "and", "output", "files", "may", "be", "specified", "." ]
6147779766557ee4fafcbae683bdd2f74157e825
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L712-L758
20,821
rhelmot/nclib
nclib/netcat.py
Netcat.recv_line
def recv_line(self, max_size=None, timeout='default', ending=None): """ Recieve until the next newline , default "\\n". The newline string can be changed by changing ``nc.LINE_ENDING``. The newline will be returned as part of the string. Aliases: recvline, readline, read_line, readln, recvln """ if ending is None: ending = self.LINE_ENDING return self.recv_until(ending, max_size, timeout)
python
def recv_line(self, max_size=None, timeout='default', ending=None): if ending is None: ending = self.LINE_ENDING return self.recv_until(ending, max_size, timeout)
[ "def", "recv_line", "(", "self", ",", "max_size", "=", "None", ",", "timeout", "=", "'default'", ",", "ending", "=", "None", ")", ":", "if", "ending", "is", "None", ":", "ending", "=", "self", ".", "LINE_ENDING", "return", "self", ".", "recv_until", "(...
Recieve until the next newline , default "\\n". The newline string can be changed by changing ``nc.LINE_ENDING``. The newline will be returned as part of the string. Aliases: recvline, readline, read_line, readln, recvln
[ "Recieve", "until", "the", "next", "newline", "default", "\\\\", "n", ".", "The", "newline", "string", "can", "be", "changed", "by", "changing", "nc", ".", "LINE_ENDING", ".", "The", "newline", "will", "be", "returned", "as", "part", "of", "the", "string",...
6147779766557ee4fafcbae683bdd2f74157e825
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L762-L772
20,822
rhelmot/nclib
nclib/netcat.py
Netcat.send_line
def send_line(self, line, ending=None): """ Write the string to the wire, followed by a newline. The newline string can be changed by changing ``nc.LINE_ENDING``. Aliases: sendline, writeline, write_line, writeln, sendln """ if ending is None: ending = self.LINE_ENDING return self.send(line + ending)
python
def send_line(self, line, ending=None): if ending is None: ending = self.LINE_ENDING return self.send(line + ending)
[ "def", "send_line", "(", "self", ",", "line", ",", "ending", "=", "None", ")", ":", "if", "ending", "is", "None", ":", "ending", "=", "self", ".", "LINE_ENDING", "return", "self", ".", "send", "(", "line", "+", "ending", ")" ]
Write the string to the wire, followed by a newline. The newline string can be changed by changing ``nc.LINE_ENDING``. Aliases: sendline, writeline, write_line, writeln, sendln
[ "Write", "the", "string", "to", "the", "wire", "followed", "by", "a", "newline", ".", "The", "newline", "string", "can", "be", "changed", "by", "changing", "nc", ".", "LINE_ENDING", "." ]
6147779766557ee4fafcbae683bdd2f74157e825
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L774-L783
20,823
Alignak-monitoring/alignak
alignak/objects/resultmodulation.py
Resultmodulation.is_active
def is_active(self, timperiods): """ Know if this result modulation is active now :return: True is we are in the period, otherwise False :rtype: bool """ now = int(time.time()) timperiod = timperiods[self.modulation_period] if not timperiod or timperiod.is_time_valid(now): return True return False
python
def is_active(self, timperiods): now = int(time.time()) timperiod = timperiods[self.modulation_period] if not timperiod or timperiod.is_time_valid(now): return True return False
[ "def", "is_active", "(", "self", ",", "timperiods", ")", ":", "now", "=", "int", "(", "time", ".", "time", "(", ")", ")", "timperiod", "=", "timperiods", "[", "self", ".", "modulation_period", "]", "if", "not", "timperiod", "or", "timperiod", ".", "is_...
Know if this result modulation is active now :return: True is we are in the period, otherwise False :rtype: bool
[ "Know", "if", "this", "result", "modulation", "is", "active", "now" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/resultmodulation.py#L93-L104
20,824
Alignak-monitoring/alignak
alignak/http/scheduler_interface.py
SchedulerInterface.object
def object(self, o_type, o_name=None): """Get an object from the scheduler. The result is a serialized object which is a Json structure containing: - content: the serialized object content - __sys_python_module__: the python class of the returned object The Alignak unserialize function of the alignak.misc.serialization package allows to restore the initial object. .. code-block:: python from alignak.misc.serialization import unserialize from alignak.objects.hostgroup import Hostgroup raw_data = req.get("http://127.0.0.1:7768/object/hostgroup/allhosts") print("Got: %s / %s" % (raw_data.status_code, raw_data.content)) assert raw_data.status_code == 200 object = raw_data.json() group = unserialize(object, True) assert group.__class__ == Hostgroup assert group.get_name() == 'allhosts' As an example: { "__sys_python_module__": "alignak.objects.hostgroup.Hostgroup", "content": { "uuid": "32248642-97dd-4f39-aaa2-5120112a765d", "name": "", "hostgroup_name": "allhosts", "use": [], "tags": [], "alias": "All Hosts", "notes": "", "definition_order": 100, "register": true, "unknown_members": [], "notes_url": "", "action_url": "", "imported_from": "unknown", "conf_is_correct": true, "configuration_errors": [], "configuration_warnings": [], "realm": "", "downtimes": {}, "hostgroup_members": [], "members": [ "553d47bc-27aa-426c-a664-49c4c0c4a249", "f88093ca-e61b-43ff-a41e-613f7ad2cea2", "df1e2e13-552d-43de-ad2a-fe80ad4ba979", "d3d667dd-f583-4668-9f44-22ef3dcb53ad" ] } } :param o_type: searched object type :type o_type: str :param o_name: searched object name (or uuid) :type o_name: str :return: serialized object information :rtype: str """ o_found = self._get_object(o_type=o_type, o_name=o_name) if not o_found: return {'_status': u'ERR', '_message': u'Required %s not found.' % o_type} return o_found
python
def object(self, o_type, o_name=None): o_found = self._get_object(o_type=o_type, o_name=o_name) if not o_found: return {'_status': u'ERR', '_message': u'Required %s not found.' % o_type} return o_found
[ "def", "object", "(", "self", ",", "o_type", ",", "o_name", "=", "None", ")", ":", "o_found", "=", "self", ".", "_get_object", "(", "o_type", "=", "o_type", ",", "o_name", "=", "o_name", ")", "if", "not", "o_found", ":", "return", "{", "'_status'", "...
Get an object from the scheduler. The result is a serialized object which is a Json structure containing: - content: the serialized object content - __sys_python_module__: the python class of the returned object The Alignak unserialize function of the alignak.misc.serialization package allows to restore the initial object. .. code-block:: python from alignak.misc.serialization import unserialize from alignak.objects.hostgroup import Hostgroup raw_data = req.get("http://127.0.0.1:7768/object/hostgroup/allhosts") print("Got: %s / %s" % (raw_data.status_code, raw_data.content)) assert raw_data.status_code == 200 object = raw_data.json() group = unserialize(object, True) assert group.__class__ == Hostgroup assert group.get_name() == 'allhosts' As an example: { "__sys_python_module__": "alignak.objects.hostgroup.Hostgroup", "content": { "uuid": "32248642-97dd-4f39-aaa2-5120112a765d", "name": "", "hostgroup_name": "allhosts", "use": [], "tags": [], "alias": "All Hosts", "notes": "", "definition_order": 100, "register": true, "unknown_members": [], "notes_url": "", "action_url": "", "imported_from": "unknown", "conf_is_correct": true, "configuration_errors": [], "configuration_warnings": [], "realm": "", "downtimes": {}, "hostgroup_members": [], "members": [ "553d47bc-27aa-426c-a664-49c4c0c4a249", "f88093ca-e61b-43ff-a41e-613f7ad2cea2", "df1e2e13-552d-43de-ad2a-fe80ad4ba979", "d3d667dd-f583-4668-9f44-22ef3dcb53ad" ] } } :param o_type: searched object type :type o_type: str :param o_name: searched object name (or uuid) :type o_name: str :return: serialized object information :rtype: str
[ "Get", "an", "object", "from", "the", "scheduler", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/scheduler_interface.py#L48-L113
20,825
Alignak-monitoring/alignak
alignak/http/scheduler_interface.py
SchedulerInterface.monitoring_problems
def monitoring_problems(self): """Get Alignak scheduler monitoring status Returns an object with the scheduler livesynthesis and the known problems :return: scheduler live synthesis :rtype: dict """ if self.app.type != 'scheduler': return {'_status': u'ERR', '_message': u"This service is only available for a scheduler daemon"} res = self.identity() res.update(self.app.get_monitoring_problems()) return res
python
def monitoring_problems(self): if self.app.type != 'scheduler': return {'_status': u'ERR', '_message': u"This service is only available for a scheduler daemon"} res = self.identity() res.update(self.app.get_monitoring_problems()) return res
[ "def", "monitoring_problems", "(", "self", ")", ":", "if", "self", ".", "app", ".", "type", "!=", "'scheduler'", ":", "return", "{", "'_status'", ":", "u'ERR'", ",", "'_message'", ":", "u\"This service is only available for a scheduler daemon\"", "}", "res", "=", ...
Get Alignak scheduler monitoring status Returns an object with the scheduler livesynthesis and the known problems :return: scheduler live synthesis :rtype: dict
[ "Get", "Alignak", "scheduler", "monitoring", "status" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/scheduler_interface.py#L329-L344
20,826
Alignak-monitoring/alignak
alignak/http/scheduler_interface.py
SchedulerInterface._wait_new_conf
def _wait_new_conf(self): """Ask the scheduler to drop its configuration and wait for a new one. This overrides the default method from GenericInterface :return: None """ # Stop the scheduling loop self.app.sched.stop_scheduling() super(SchedulerInterface, self)._wait_new_conf()
python
def _wait_new_conf(self): # Stop the scheduling loop self.app.sched.stop_scheduling() super(SchedulerInterface, self)._wait_new_conf()
[ "def", "_wait_new_conf", "(", "self", ")", ":", "# Stop the scheduling loop", "self", ".", "app", ".", "sched", ".", "stop_scheduling", "(", ")", "super", "(", "SchedulerInterface", ",", "self", ")", ".", "_wait_new_conf", "(", ")" ]
Ask the scheduler to drop its configuration and wait for a new one. This overrides the default method from GenericInterface :return: None
[ "Ask", "the", "scheduler", "to", "drop", "its", "configuration", "and", "wait", "for", "a", "new", "one", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/scheduler_interface.py#L357-L366
20,827
Alignak-monitoring/alignak
alignak/http/scheduler_interface.py
SchedulerInterface._initial_broks
def _initial_broks(self, broker_name): """Get initial_broks from the scheduler This is used by the brokers to prepare the initial status broks This do not send broks, it only makes scheduler internal processing. Then the broker must use the *_broks* API to get all the stuff :param broker_name: broker name, used to filter broks :type broker_name: str :return: None """ with self.app.conf_lock: logger.info("A new broker just connected : %s", broker_name) return self.app.sched.fill_initial_broks(broker_name)
python
def _initial_broks(self, broker_name): with self.app.conf_lock: logger.info("A new broker just connected : %s", broker_name) return self.app.sched.fill_initial_broks(broker_name)
[ "def", "_initial_broks", "(", "self", ",", "broker_name", ")", ":", "with", "self", ".", "app", ".", "conf_lock", ":", "logger", ".", "info", "(", "\"A new broker just connected : %s\"", ",", "broker_name", ")", "return", "self", ".", "app", ".", "sched", "....
Get initial_broks from the scheduler This is used by the brokers to prepare the initial status broks This do not send broks, it only makes scheduler internal processing. Then the broker must use the *_broks* API to get all the stuff :param broker_name: broker name, used to filter broks :type broker_name: str :return: None
[ "Get", "initial_broks", "from", "the", "scheduler" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/scheduler_interface.py#L370-L384
20,828
Alignak-monitoring/alignak
alignak/http/scheduler_interface.py
SchedulerInterface._broks
def _broks(self, broker_name): """Get the broks from a scheduler, used by brokers This is used by the brokers to get the broks list of a scheduler :param broker_name: broker name, used to filter broks :type broker_name: str :return: serialized brok list :rtype: dict """ logger.debug("Getting broks for %s from the scheduler", broker_name) for broker_link in list(self.app.brokers.values()): if broker_name == broker_link.name: break else: logger.warning("Requesting broks for an unknown broker: %s", broker_name) return {} # Now get the broks for this specific broker with self.app.broks_lock: res = self.app.get_broks(broker_name) return serialize(res, True)
python
def _broks(self, broker_name): logger.debug("Getting broks for %s from the scheduler", broker_name) for broker_link in list(self.app.brokers.values()): if broker_name == broker_link.name: break else: logger.warning("Requesting broks for an unknown broker: %s", broker_name) return {} # Now get the broks for this specific broker with self.app.broks_lock: res = self.app.get_broks(broker_name) return serialize(res, True)
[ "def", "_broks", "(", "self", ",", "broker_name", ")", ":", "logger", ".", "debug", "(", "\"Getting broks for %s from the scheduler\"", ",", "broker_name", ")", "for", "broker_link", "in", "list", "(", "self", ".", "app", ".", "brokers", ".", "values", "(", ...
Get the broks from a scheduler, used by brokers This is used by the brokers to get the broks list of a scheduler :param broker_name: broker name, used to filter broks :type broker_name: str :return: serialized brok list :rtype: dict
[ "Get", "the", "broks", "from", "a", "scheduler", "used", "by", "brokers" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/scheduler_interface.py#L388-L410
20,829
Alignak-monitoring/alignak
alignak/http/scheduler_interface.py
SchedulerInterface._get_objects
def _get_objects(self, o_type): """Get an object list from the scheduler Returns None if the required object type (`o_type`) is not known or an exception is raised. Else returns the objects list :param o_type: searched object type :type o_type: str :return: objects list :rtype: alignak.objects.item.Items """ if o_type not in [t for t in self.app.sched.pushed_conf.types_creations]: return None try: _, _, strclss, _, _ = self.app.sched.pushed_conf.types_creations[o_type] o_list = getattr(self.app.sched, strclss) except Exception: # pylint: disable=broad-except return None return o_list
python
def _get_objects(self, o_type): if o_type not in [t for t in self.app.sched.pushed_conf.types_creations]: return None try: _, _, strclss, _, _ = self.app.sched.pushed_conf.types_creations[o_type] o_list = getattr(self.app.sched, strclss) except Exception: # pylint: disable=broad-except return None return o_list
[ "def", "_get_objects", "(", "self", ",", "o_type", ")", ":", "if", "o_type", "not", "in", "[", "t", "for", "t", "in", "self", ".", "app", ".", "sched", ".", "pushed_conf", ".", "types_creations", "]", ":", "return", "None", "try", ":", "_", ",", "_...
Get an object list from the scheduler Returns None if the required object type (`o_type`) is not known or an exception is raised. Else returns the objects list :param o_type: searched object type :type o_type: str :return: objects list :rtype: alignak.objects.item.Items
[ "Get", "an", "object", "list", "from", "the", "scheduler" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/scheduler_interface.py#L498-L518
20,830
Alignak-monitoring/alignak
alignak/http/scheduler_interface.py
SchedulerInterface._get_object
def _get_object(self, o_type, o_name=None): """Get an object from the scheduler Returns None if the required object type (`o_type`) is not known. Else returns the serialized object if found. The object is searched first with o_name as its name and then with o_name as its uuid. :param o_type: searched object type :type o_type: str :param name: searched object name :type name: str :return: serialized object :rtype: str """ try: o_found = None o_list = self._get_objects(o_type) if o_list: if o_name is None: return serialize(o_list, True) if o_list else None # We expected a name... o_found = o_list.find_by_name(o_name) if not o_found: # ... but perharps we got an object uuid o_found = o_list[o_name] except Exception: # pylint: disable=broad-except return None return serialize(o_found, True) if o_found else None
python
def _get_object(self, o_type, o_name=None): try: o_found = None o_list = self._get_objects(o_type) if o_list: if o_name is None: return serialize(o_list, True) if o_list else None # We expected a name... o_found = o_list.find_by_name(o_name) if not o_found: # ... but perharps we got an object uuid o_found = o_list[o_name] except Exception: # pylint: disable=broad-except return None return serialize(o_found, True) if o_found else None
[ "def", "_get_object", "(", "self", ",", "o_type", ",", "o_name", "=", "None", ")", ":", "try", ":", "o_found", "=", "None", "o_list", "=", "self", ".", "_get_objects", "(", "o_type", ")", "if", "o_list", ":", "if", "o_name", "is", "None", ":", "retur...
Get an object from the scheduler Returns None if the required object type (`o_type`) is not known. Else returns the serialized object if found. The object is searched first with o_name as its name and then with o_name as its uuid. :param o_type: searched object type :type o_type: str :param name: searched object name :type name: str :return: serialized object :rtype: str
[ "Get", "an", "object", "from", "the", "scheduler" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/scheduler_interface.py#L520-L547
20,831
Alignak-monitoring/alignak
alignak/objects/module.py
Module.is_a_module
def is_a_module(self, module_type): """ Is the module of the required type? :param module_type: module type to check :type: str :return: True / False """ if hasattr(self, 'type'): return module_type in self.type return module_type in self.module_types
python
def is_a_module(self, module_type): if hasattr(self, 'type'): return module_type in self.type return module_type in self.module_types
[ "def", "is_a_module", "(", "self", ",", "module_type", ")", ":", "if", "hasattr", "(", "self", ",", "'type'", ")", ":", "return", "module_type", "in", "self", ".", "type", "return", "module_type", "in", "self", ".", "module_types" ]
Is the module of the required type? :param module_type: module type to check :type: str :return: True / False
[ "Is", "the", "module", "of", "the", "required", "type?" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/module.py#L198-L208
20,832
Alignak-monitoring/alignak
alignak/objects/module.py
Module.serialize
def serialize(self): """A module may have some properties that are not defined in the class properties list. Serializing a module is the same as serializing an Item but we also also include all the existing properties that are not defined in the properties or running_properties class list. We must also exclude the reference to the daemon that loaded the module! """ res = super(Module, self).serialize() cls = self.__class__ for prop in self.__dict__: if prop in cls.properties or prop in cls.running_properties or prop in ['properties', 'my_daemon']: continue res[prop] = getattr(self, prop) return res
python
def serialize(self): res = super(Module, self).serialize() cls = self.__class__ for prop in self.__dict__: if prop in cls.properties or prop in cls.running_properties or prop in ['properties', 'my_daemon']: continue res[prop] = getattr(self, prop) return res
[ "def", "serialize", "(", "self", ")", ":", "res", "=", "super", "(", "Module", ",", "self", ")", ".", "serialize", "(", ")", "cls", "=", "self", ".", "__class__", "for", "prop", "in", "self", ".", "__dict__", ":", "if", "prop", "in", "cls", ".", ...
A module may have some properties that are not defined in the class properties list. Serializing a module is the same as serializing an Item but we also also include all the existing properties that are not defined in the properties or running_properties class list. We must also exclude the reference to the daemon that loaded the module!
[ "A", "module", "may", "have", "some", "properties", "that", "are", "not", "defined", "in", "the", "class", "properties", "list", ".", "Serializing", "a", "module", "is", "the", "same", "as", "serializing", "an", "Item", "but", "we", "also", "also", "includ...
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/module.py#L210-L227
20,833
Alignak-monitoring/alignak
alignak/objects/module.py
Modules.linkify_s_by_plug
def linkify_s_by_plug(self): """Link a module to some other modules :return: None """ for module in self: new_modules = [] for related in getattr(module, 'modules', []): related = related.strip() if not related: continue o_related = self.find_by_name(related) if o_related is not None: new_modules.append(o_related.uuid) else: self.add_error("the module '%s' for the module '%s' is unknown!" % (related, module.get_name())) module.modules = new_modules
python
def linkify_s_by_plug(self): for module in self: new_modules = [] for related in getattr(module, 'modules', []): related = related.strip() if not related: continue o_related = self.find_by_name(related) if o_related is not None: new_modules.append(o_related.uuid) else: self.add_error("the module '%s' for the module '%s' is unknown!" % (related, module.get_name())) module.modules = new_modules
[ "def", "linkify_s_by_plug", "(", "self", ")", ":", "for", "module", "in", "self", ":", "new_modules", "=", "[", "]", "for", "related", "in", "getattr", "(", "module", ",", "'modules'", ",", "[", "]", ")", ":", "related", "=", "related", ".", "strip", ...
Link a module to some other modules :return: None
[ "Link", "a", "module", "to", "some", "other", "modules" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/module.py#L245-L262
20,834
Alignak-monitoring/alignak
alignak/daterange.py
get_start_of_day
def get_start_of_day(year, month, day): """Get the timestamp associated to the first second of a specific day :param year: date year :type year: int :param month: date month :type month: int :param day: date day :type day: int :return: timestamp :rtype: int """ # DST is not known in the provided date try: timestamp = time.mktime((year, month, day, 00, 00, 00, 0, 0, -1)) except (OverflowError, ValueError): # Windows mktime sometimes crashes on (1970, 1, 1, ...) timestamp = 0.0 return int(timestamp)
python
def get_start_of_day(year, month, day): # DST is not known in the provided date try: timestamp = time.mktime((year, month, day, 00, 00, 00, 0, 0, -1)) except (OverflowError, ValueError): # Windows mktime sometimes crashes on (1970, 1, 1, ...) timestamp = 0.0 return int(timestamp)
[ "def", "get_start_of_day", "(", "year", ",", "month", ",", "day", ")", ":", "# DST is not known in the provided date", "try", ":", "timestamp", "=", "time", ".", "mktime", "(", "(", "year", ",", "month", ",", "day", ",", "00", ",", "00", ",", "00", ",", ...
Get the timestamp associated to the first second of a specific day :param year: date year :type year: int :param month: date month :type month: int :param day: date day :type day: int :return: timestamp :rtype: int
[ "Get", "the", "timestamp", "associated", "to", "the", "first", "second", "of", "a", "specific", "day" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L63-L82
20,835
Alignak-monitoring/alignak
alignak/daterange.py
get_end_of_day
def get_end_of_day(year, month, day): """Get the timestamp associated to the last second of a specific day :param year: date year :type year: int :param month: date month (int) :type month: int :param day: date day :type day: int :return: timestamp :rtype: int """ # DST is not known in the provided date timestamp = time.mktime((year, month, day, 23, 59, 59, 0, 0, -1)) return int(timestamp)
python
def get_end_of_day(year, month, day): # DST is not known in the provided date timestamp = time.mktime((year, month, day, 23, 59, 59, 0, 0, -1)) return int(timestamp)
[ "def", "get_end_of_day", "(", "year", ",", "month", ",", "day", ")", ":", "# DST is not known in the provided date", "timestamp", "=", "time", ".", "mktime", "(", "(", "year", ",", "month", ",", "day", ",", "23", ",", "59", ",", "59", ",", "0", ",", "0...
Get the timestamp associated to the last second of a specific day :param year: date year :type year: int :param month: date month (int) :type month: int :param day: date day :type day: int :return: timestamp :rtype: int
[ "Get", "the", "timestamp", "associated", "to", "the", "last", "second", "of", "a", "specific", "day" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L85-L99
20,836
Alignak-monitoring/alignak
alignak/daterange.py
get_sec_from_morning
def get_sec_from_morning(timestamp): """Get the number of seconds elapsed since the beginning of the day deducted from the provided timestamp :param timestamp: time to use for computation :type timestamp: int :return: timestamp :rtype: int """ t_lt = time.localtime(timestamp) return t_lt.tm_hour * 3600 + t_lt.tm_min * 60 + t_lt.tm_sec
python
def get_sec_from_morning(timestamp): t_lt = time.localtime(timestamp) return t_lt.tm_hour * 3600 + t_lt.tm_min * 60 + t_lt.tm_sec
[ "def", "get_sec_from_morning", "(", "timestamp", ")", ":", "t_lt", "=", "time", ".", "localtime", "(", "timestamp", ")", "return", "t_lt", ".", "tm_hour", "*", "3600", "+", "t_lt", ".", "tm_min", "*", "60", "+", "t_lt", ".", "tm_sec" ]
Get the number of seconds elapsed since the beginning of the day deducted from the provided timestamp :param timestamp: time to use for computation :type timestamp: int :return: timestamp :rtype: int
[ "Get", "the", "number", "of", "seconds", "elapsed", "since", "the", "beginning", "of", "the", "day", "deducted", "from", "the", "provided", "timestamp" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L126-L136
20,837
Alignak-monitoring/alignak
alignak/daterange.py
find_day_by_weekday_offset
def find_day_by_weekday_offset(year, month, weekday, offset): """Get the day number based on a date and offset :param year: date year :type year: int :param month: date month :type month: int :param weekday: date week day :type weekday: int :param offset: offset (-1 is last, 1 is first etc) :type offset: int :return: day number in the month :rtype: int >>> find_day_by_weekday_offset(2010, 7, 1, -1) 27 """ # thanks calendar :) cal = calendar.monthcalendar(year, month) # If we ask for a -1 day, just reverse cal if offset < 0: offset = abs(offset) cal.reverse() # ok go for it nb_found = 0 try: for i in range(0, offset + 1): # in cal 0 mean "there are no day here :)" if cal[i][weekday] != 0: nb_found += 1 if nb_found == offset: return cal[i][weekday] return None except KeyError: return None
python
def find_day_by_weekday_offset(year, month, weekday, offset): # thanks calendar :) cal = calendar.monthcalendar(year, month) # If we ask for a -1 day, just reverse cal if offset < 0: offset = abs(offset) cal.reverse() # ok go for it nb_found = 0 try: for i in range(0, offset + 1): # in cal 0 mean "there are no day here :)" if cal[i][weekday] != 0: nb_found += 1 if nb_found == offset: return cal[i][weekday] return None except KeyError: return None
[ "def", "find_day_by_weekday_offset", "(", "year", ",", "month", ",", "weekday", ",", "offset", ")", ":", "# thanks calendar :)", "cal", "=", "calendar", ".", "monthcalendar", "(", "year", ",", "month", ")", "# If we ask for a -1 day, just reverse cal", "if", "offset...
Get the day number based on a date and offset :param year: date year :type year: int :param month: date month :type month: int :param weekday: date week day :type weekday: int :param offset: offset (-1 is last, 1 is first etc) :type offset: int :return: day number in the month :rtype: int >>> find_day_by_weekday_offset(2010, 7, 1, -1) 27
[ "Get", "the", "day", "number", "based", "on", "a", "date", "and", "offset" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L139-L175
20,838
Alignak-monitoring/alignak
alignak/daterange.py
find_day_by_offset
def find_day_by_offset(year, month, offset): """Get the month day based on date and offset :param year: date year :type year: int :param month: date month :type month: int :param offset: offset in day to compute (usually negative) :type offset: int :return: day number in the month :rtype: int >>> find_day_by_offset(2015, 7, -1) 31 """ (_, days_in_month) = calendar.monthrange(year, month) if offset >= 0: return min(offset, days_in_month) return max(1, days_in_month + offset + 1)
python
def find_day_by_offset(year, month, offset): (_, days_in_month) = calendar.monthrange(year, month) if offset >= 0: return min(offset, days_in_month) return max(1, days_in_month + offset + 1)
[ "def", "find_day_by_offset", "(", "year", ",", "month", ",", "offset", ")", ":", "(", "_", ",", "days_in_month", ")", "=", "calendar", ".", "monthrange", "(", "year", ",", "month", ")", "if", "offset", ">=", "0", ":", "return", "min", "(", "offset", ...
Get the month day based on date and offset :param year: date year :type year: int :param month: date month :type month: int :param offset: offset in day to compute (usually negative) :type offset: int :return: day number in the month :rtype: int >>> find_day_by_offset(2015, 7, -1) 31
[ "Get", "the", "month", "day", "based", "on", "date", "and", "offset" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L178-L197
20,839
Alignak-monitoring/alignak
alignak/daterange.py
Timerange.is_time_valid
def is_time_valid(self, timestamp): """Check if time is valid for this Timerange If sec_from_morning is not provided, get the value. :param timestamp: time to check :type timestamp: int :return: True if time is valid (in interval), False otherwise :rtype: bool """ sec_from_morning = get_sec_from_morning(timestamp) return (self.is_valid and self.hstart * 3600 + self.mstart * 60 <= sec_from_morning <= self.hend * 3600 + self.mend * 60)
python
def is_time_valid(self, timestamp): sec_from_morning = get_sec_from_morning(timestamp) return (self.is_valid and self.hstart * 3600 + self.mstart * 60 <= sec_from_morning <= self.hend * 3600 + self.mend * 60)
[ "def", "is_time_valid", "(", "self", ",", "timestamp", ")", ":", "sec_from_morning", "=", "get_sec_from_morning", "(", "timestamp", ")", "return", "(", "self", ".", "is_valid", "and", "self", ".", "hstart", "*", "3600", "+", "self", ".", "mstart", "*", "60...
Check if time is valid for this Timerange If sec_from_morning is not provided, get the value. :param timestamp: time to check :type timestamp: int :return: True if time is valid (in interval), False otherwise :rtype: bool
[ "Check", "if", "time", "is", "valid", "for", "this", "Timerange" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L268-L282
20,840
Alignak-monitoring/alignak
alignak/daterange.py
AbstractDaterange.is_time_valid
def is_time_valid(self, timestamp): """Check if time is valid for one of the timerange. :param timestamp: time to check :type timestamp: int :return: True if one of the timerange is valid for t, False otherwise :rtype: bool """ if self.is_time_day_valid(timestamp): for timerange in self.timeranges: if timerange.is_time_valid(timestamp): return True return False
python
def is_time_valid(self, timestamp): if self.is_time_day_valid(timestamp): for timerange in self.timeranges: if timerange.is_time_valid(timestamp): return True return False
[ "def", "is_time_valid", "(", "self", ",", "timestamp", ")", ":", "if", "self", ".", "is_time_day_valid", "(", "timestamp", ")", ":", "for", "timerange", "in", "self", ".", "timeranges", ":", "if", "timerange", ".", "is_time_valid", "(", "timestamp", ")", "...
Check if time is valid for one of the timerange. :param timestamp: time to check :type timestamp: int :return: True if one of the timerange is valid for t, False otherwise :rtype: bool
[ "Check", "if", "time", "is", "valid", "for", "one", "of", "the", "timerange", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L379-L391
20,841
Alignak-monitoring/alignak
alignak/daterange.py
AbstractDaterange.get_min_sec_from_morning
def get_min_sec_from_morning(self): """Get the first second from midnight where a timerange is effective :return: smallest amount of second from midnight of all timerange :rtype: int """ mins = [] for timerange in self.timeranges: mins.append(timerange.get_sec_from_morning()) return min(mins)
python
def get_min_sec_from_morning(self): mins = [] for timerange in self.timeranges: mins.append(timerange.get_sec_from_morning()) return min(mins)
[ "def", "get_min_sec_from_morning", "(", "self", ")", ":", "mins", "=", "[", "]", "for", "timerange", "in", "self", ".", "timeranges", ":", "mins", ".", "append", "(", "timerange", ".", "get_sec_from_morning", "(", ")", ")", "return", "min", "(", "mins", ...
Get the first second from midnight where a timerange is effective :return: smallest amount of second from midnight of all timerange :rtype: int
[ "Get", "the", "first", "second", "from", "midnight", "where", "a", "timerange", "is", "effective" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L393-L402
20,842
Alignak-monitoring/alignak
alignak/daterange.py
AbstractDaterange.is_time_day_valid
def is_time_day_valid(self, timestamp): """Check if it is within start time and end time of the DateRange :param timestamp: time to check :type timestamp: int :return: True if t in range, False otherwise :rtype: bool """ (start_time, end_time) = self.get_start_and_end_time(timestamp) return start_time <= timestamp <= end_time
python
def is_time_day_valid(self, timestamp): (start_time, end_time) = self.get_start_and_end_time(timestamp) return start_time <= timestamp <= end_time
[ "def", "is_time_day_valid", "(", "self", ",", "timestamp", ")", ":", "(", "start_time", ",", "end_time", ")", "=", "self", ".", "get_start_and_end_time", "(", "timestamp", ")", "return", "start_time", "<=", "timestamp", "<=", "end_time" ]
Check if it is within start time and end time of the DateRange :param timestamp: time to check :type timestamp: int :return: True if t in range, False otherwise :rtype: bool
[ "Check", "if", "it", "is", "within", "start", "time", "and", "end", "time", "of", "the", "DateRange" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L428-L437
20,843
Alignak-monitoring/alignak
alignak/daterange.py
AbstractDaterange.get_next_future_timerange_invalid
def get_next_future_timerange_invalid(self, timestamp): """Get next invalid time for timeranges :param timestamp: time to check :type timestamp: int :return: next time when a timerange is not valid :rtype: None | int """ sec_from_morning = get_sec_from_morning(timestamp) ends = [] for timerange in self.timeranges: tr_end = timerange.hend * 3600 + timerange.mend * 60 if tr_end >= sec_from_morning: # Remove the last second of the day for 00->24h" if tr_end == 86400: tr_end = 86399 ends.append(tr_end) if ends != []: return min(ends) return None
python
def get_next_future_timerange_invalid(self, timestamp): sec_from_morning = get_sec_from_morning(timestamp) ends = [] for timerange in self.timeranges: tr_end = timerange.hend * 3600 + timerange.mend * 60 if tr_end >= sec_from_morning: # Remove the last second of the day for 00->24h" if tr_end == 86400: tr_end = 86399 ends.append(tr_end) if ends != []: return min(ends) return None
[ "def", "get_next_future_timerange_invalid", "(", "self", ",", "timestamp", ")", ":", "sec_from_morning", "=", "get_sec_from_morning", "(", "timestamp", ")", "ends", "=", "[", "]", "for", "timerange", "in", "self", ".", "timeranges", ":", "tr_end", "=", "timerang...
Get next invalid time for timeranges :param timestamp: time to check :type timestamp: int :return: next time when a timerange is not valid :rtype: None | int
[ "Get", "next", "invalid", "time", "for", "timeranges" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L468-L488
20,844
Alignak-monitoring/alignak
alignak/daterange.py
AbstractDaterange.get_next_valid_day
def get_next_valid_day(self, timestamp): """Get next valid day for timerange :param timestamp: time we compute from :type timestamp: int :return: timestamp of the next valid day (midnight) in LOCAL time. :rtype: int | None """ if self.get_next_future_timerange_valid(timestamp) is None: # this day is finish, we check for next period (start_time, _) = self.get_start_and_end_time(get_day(timestamp) + 86400) else: (start_time, _) = self.get_start_and_end_time(timestamp) if timestamp <= start_time: return get_day(start_time) if self.is_time_day_valid(timestamp): return get_day(timestamp) return None
python
def get_next_valid_day(self, timestamp): if self.get_next_future_timerange_valid(timestamp) is None: # this day is finish, we check for next period (start_time, _) = self.get_start_and_end_time(get_day(timestamp) + 86400) else: (start_time, _) = self.get_start_and_end_time(timestamp) if timestamp <= start_time: return get_day(start_time) if self.is_time_day_valid(timestamp): return get_day(timestamp) return None
[ "def", "get_next_valid_day", "(", "self", ",", "timestamp", ")", ":", "if", "self", ".", "get_next_future_timerange_valid", "(", "timestamp", ")", "is", "None", ":", "# this day is finish, we check for next period", "(", "start_time", ",", "_", ")", "=", "self", "...
Get next valid day for timerange :param timestamp: time we compute from :type timestamp: int :return: timestamp of the next valid day (midnight) in LOCAL time. :rtype: int | None
[ "Get", "next", "valid", "day", "for", "timerange" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L490-L510
20,845
Alignak-monitoring/alignak
alignak/daterange.py
AbstractDaterange.get_next_valid_time_from_t
def get_next_valid_time_from_t(self, timestamp): """Get next valid time for time range :param timestamp: time we compute from :type timestamp: int :return: timestamp of the next valid time (LOCAL TIME) :rtype: int | None """ if self.is_time_valid(timestamp): return timestamp # First we search for the day of t t_day = self.get_next_valid_day(timestamp) if t_day is None: return t_day # We search for the min of all tr.start > sec_from_morning # if it's the next day, use a start of the day search for timerange if timestamp < t_day: sec_from_morning = self.get_next_future_timerange_valid(t_day) else: # it is in this day, so look from t (can be in the evening or so) sec_from_morning = self.get_next_future_timerange_valid(timestamp) if sec_from_morning is not None: if t_day is not None and sec_from_morning is not None: return t_day + sec_from_morning # Then we search for the next day of t # The sec will be the min of the day timestamp = get_day(timestamp) + 86400 t_day2 = self.get_next_valid_day(timestamp) sec_from_morning = self.get_next_future_timerange_valid(t_day2) if t_day2 is not None and sec_from_morning is not None: return t_day2 + sec_from_morning # I did not found any valid time return None
python
def get_next_valid_time_from_t(self, timestamp): if self.is_time_valid(timestamp): return timestamp # First we search for the day of t t_day = self.get_next_valid_day(timestamp) if t_day is None: return t_day # We search for the min of all tr.start > sec_from_morning # if it's the next day, use a start of the day search for timerange if timestamp < t_day: sec_from_morning = self.get_next_future_timerange_valid(t_day) else: # it is in this day, so look from t (can be in the evening or so) sec_from_morning = self.get_next_future_timerange_valid(timestamp) if sec_from_morning is not None: if t_day is not None and sec_from_morning is not None: return t_day + sec_from_morning # Then we search for the next day of t # The sec will be the min of the day timestamp = get_day(timestamp) + 86400 t_day2 = self.get_next_valid_day(timestamp) sec_from_morning = self.get_next_future_timerange_valid(t_day2) if t_day2 is not None and sec_from_morning is not None: return t_day2 + sec_from_morning # I did not found any valid time return None
[ "def", "get_next_valid_time_from_t", "(", "self", ",", "timestamp", ")", ":", "if", "self", ".", "is_time_valid", "(", "timestamp", ")", ":", "return", "timestamp", "# First we search for the day of t", "t_day", "=", "self", ".", "get_next_valid_day", "(", "timestam...
Get next valid time for time range :param timestamp: time we compute from :type timestamp: int :return: timestamp of the next valid time (LOCAL TIME) :rtype: int | None
[ "Get", "next", "valid", "time", "for", "time", "range" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L512-L548
20,846
Alignak-monitoring/alignak
alignak/daterange.py
AbstractDaterange.get_next_invalid_day
def get_next_invalid_day(self, timestamp): # pylint: disable=no-else-return """Get next day where timerange is not active :param timestamp: time we compute from :type timestamp: int :return: timestamp of the next invalid day (midnight) in LOCAL time. :rtype: int | None """ if self.is_time_day_invalid(timestamp): return timestamp next_future_timerange_invalid = self.get_next_future_timerange_invalid(timestamp) # If today there is no more unavailable timerange, search the next day if next_future_timerange_invalid is None: # this day is finish, we check for next period (start_time, end_time) = self.get_start_and_end_time(get_day(timestamp)) else: (start_time, end_time) = self.get_start_and_end_time(timestamp) # (start_time, end_time) = self.get_start_and_end_time(t) # The next invalid day can be t day if there a possible # invalid time range (timerange is not 00->24 if next_future_timerange_invalid is not None: if start_time <= timestamp <= end_time: return get_day(timestamp) if start_time >= timestamp: return get_day(start_time) else: # Else, there is no possibility than in our start_time<->end_time we got # any invalid time (full period out). So it's end_time+1 sec (tomorrow of end_time) return get_day(end_time + 1) return None
python
def get_next_invalid_day(self, timestamp): # pylint: disable=no-else-return if self.is_time_day_invalid(timestamp): return timestamp next_future_timerange_invalid = self.get_next_future_timerange_invalid(timestamp) # If today there is no more unavailable timerange, search the next day if next_future_timerange_invalid is None: # this day is finish, we check for next period (start_time, end_time) = self.get_start_and_end_time(get_day(timestamp)) else: (start_time, end_time) = self.get_start_and_end_time(timestamp) # (start_time, end_time) = self.get_start_and_end_time(t) # The next invalid day can be t day if there a possible # invalid time range (timerange is not 00->24 if next_future_timerange_invalid is not None: if start_time <= timestamp <= end_time: return get_day(timestamp) if start_time >= timestamp: return get_day(start_time) else: # Else, there is no possibility than in our start_time<->end_time we got # any invalid time (full period out). So it's end_time+1 sec (tomorrow of end_time) return get_day(end_time + 1) return None
[ "def", "get_next_invalid_day", "(", "self", ",", "timestamp", ")", ":", "# pylint: disable=no-else-return", "if", "self", ".", "is_time_day_invalid", "(", "timestamp", ")", ":", "return", "timestamp", "next_future_timerange_invalid", "=", "self", ".", "get_next_future_t...
Get next day where timerange is not active :param timestamp: time we compute from :type timestamp: int :return: timestamp of the next invalid day (midnight) in LOCAL time. :rtype: int | None
[ "Get", "next", "day", "where", "timerange", "is", "not", "active" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L550-L584
20,847
Alignak-monitoring/alignak
alignak/daterange.py
AbstractDaterange.get_next_invalid_time_from_t
def get_next_invalid_time_from_t(self, timestamp): """Get next invalid time for time range :param timestamp: time we compute from :type timestamp: int :return: timestamp of the next invalid time (LOCAL TIME) :rtype: int """ if not self.is_time_valid(timestamp): return timestamp # First we search for the day of time range t_day = self.get_next_invalid_day(timestamp) # We search for the min of all tr.start > sec_from_morning # if it's the next day, use a start of the day search for timerange if timestamp < t_day: sec_from_morning = self.get_next_future_timerange_invalid(t_day) else: # it is in this day, so look from t (can be in the evening or so) sec_from_morning = self.get_next_future_timerange_invalid(timestamp) # tr can't be valid, or it will be return at the beginning # sec_from_morning = self.get_next_future_timerange_invalid(t) # Ok we've got a next invalid day and a invalid possibility in # timerange, so the next invalid is this day+sec_from_morning if t_day is not None and sec_from_morning is not None: return t_day + sec_from_morning + 1 # We've got a day but no sec_from_morning: the timerange is full (0->24h) # so the next invalid is this day at the day_start if t_day is not None and sec_from_morning is None: return t_day # Then we search for the next day of t # The sec will be the min of the day timestamp = get_day(timestamp) + 86400 t_day2 = self.get_next_invalid_day(timestamp) sec_from_morning = self.get_next_future_timerange_invalid(t_day2) if t_day2 is not None and sec_from_morning is not None: return t_day2 + sec_from_morning + 1 if t_day2 is not None and sec_from_morning is None: return t_day2 # I did not found any valid time return None
python
def get_next_invalid_time_from_t(self, timestamp): if not self.is_time_valid(timestamp): return timestamp # First we search for the day of time range t_day = self.get_next_invalid_day(timestamp) # We search for the min of all tr.start > sec_from_morning # if it's the next day, use a start of the day search for timerange if timestamp < t_day: sec_from_morning = self.get_next_future_timerange_invalid(t_day) else: # it is in this day, so look from t (can be in the evening or so) sec_from_morning = self.get_next_future_timerange_invalid(timestamp) # tr can't be valid, or it will be return at the beginning # sec_from_morning = self.get_next_future_timerange_invalid(t) # Ok we've got a next invalid day and a invalid possibility in # timerange, so the next invalid is this day+sec_from_morning if t_day is not None and sec_from_morning is not None: return t_day + sec_from_morning + 1 # We've got a day but no sec_from_morning: the timerange is full (0->24h) # so the next invalid is this day at the day_start if t_day is not None and sec_from_morning is None: return t_day # Then we search for the next day of t # The sec will be the min of the day timestamp = get_day(timestamp) + 86400 t_day2 = self.get_next_invalid_day(timestamp) sec_from_morning = self.get_next_future_timerange_invalid(t_day2) if t_day2 is not None and sec_from_morning is not None: return t_day2 + sec_from_morning + 1 if t_day2 is not None and sec_from_morning is None: return t_day2 # I did not found any valid time return None
[ "def", "get_next_invalid_time_from_t", "(", "self", ",", "timestamp", ")", ":", "if", "not", "self", ".", "is_time_valid", "(", "timestamp", ")", ":", "return", "timestamp", "# First we search for the day of time range", "t_day", "=", "self", ".", "get_next_invalid_da...
Get next invalid time for time range :param timestamp: time we compute from :type timestamp: int :return: timestamp of the next invalid time (LOCAL TIME) :rtype: int
[ "Get", "next", "invalid", "time", "for", "time", "range" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L586-L632
20,848
Alignak-monitoring/alignak
alignak/daterange.py
CalendarDaterange.get_start_and_end_time
def get_start_and_end_time(self, ref=None): """Specific function to get start time and end time for CalendarDaterange :param ref: time in seconds :type ref: int :return: tuple with start and end time :rtype: tuple (int, int) """ return (get_start_of_day(self.syear, int(self.smon), self.smday), get_end_of_day(self.eyear, int(self.emon), self.emday))
python
def get_start_and_end_time(self, ref=None): return (get_start_of_day(self.syear, int(self.smon), self.smday), get_end_of_day(self.eyear, int(self.emon), self.emday))
[ "def", "get_start_and_end_time", "(", "self", ",", "ref", "=", "None", ")", ":", "return", "(", "get_start_of_day", "(", "self", ".", "syear", ",", "int", "(", "self", ".", "smon", ")", ",", "self", ".", "smday", ")", ",", "get_end_of_day", "(", "self"...
Specific function to get start time and end time for CalendarDaterange :param ref: time in seconds :type ref: int :return: tuple with start and end time :rtype: tuple (int, int)
[ "Specific", "function", "to", "get", "start", "time", "and", "end", "time", "for", "CalendarDaterange" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L728-L737
20,849
Alignak-monitoring/alignak
alignak/daterange.py
StandardDaterange.get_start_and_end_time
def get_start_and_end_time(self, ref=None): """Specific function to get start time and end time for StandardDaterange :param ref: time in seconds :type ref: int :return: tuple with start and end time :rtype: tuple (int, int) """ now = time.localtime(ref) self.syear = now.tm_year self.month = now.tm_mon self.wday = now.tm_wday day_id = Daterange.get_weekday_id(self.day) today_morning = get_start_of_day(now.tm_year, now.tm_mon, now.tm_mday) tonight = get_end_of_day(now.tm_year, now.tm_mon, now.tm_mday) day_diff = (day_id - now.tm_wday) % 7 morning = datetime.fromtimestamp(today_morning) + timedelta(days=day_diff) night = datetime.fromtimestamp(tonight) + timedelta(days=day_diff) return (int(morning.strftime("%s")), int(night.strftime("%s")))
python
def get_start_and_end_time(self, ref=None): now = time.localtime(ref) self.syear = now.tm_year self.month = now.tm_mon self.wday = now.tm_wday day_id = Daterange.get_weekday_id(self.day) today_morning = get_start_of_day(now.tm_year, now.tm_mon, now.tm_mday) tonight = get_end_of_day(now.tm_year, now.tm_mon, now.tm_mday) day_diff = (day_id - now.tm_wday) % 7 morning = datetime.fromtimestamp(today_morning) + timedelta(days=day_diff) night = datetime.fromtimestamp(tonight) + timedelta(days=day_diff) return (int(morning.strftime("%s")), int(night.strftime("%s")))
[ "def", "get_start_and_end_time", "(", "self", ",", "ref", "=", "None", ")", ":", "now", "=", "time", ".", "localtime", "(", "ref", ")", "self", ".", "syear", "=", "now", ".", "tm_year", "self", ".", "month", "=", "now", ".", "tm_mon", "self", ".", ...
Specific function to get start time and end time for StandardDaterange :param ref: time in seconds :type ref: int :return: tuple with start and end time :rtype: tuple (int, int)
[ "Specific", "function", "to", "get", "start", "time", "and", "end", "time", "for", "StandardDaterange" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L794-L812
20,850
Alignak-monitoring/alignak
alignak/daterange.py
MonthWeekDayDaterange.get_start_and_end_time
def get_start_and_end_time(self, ref=None): """Specific function to get start time and end time for MonthWeekDayDaterange :param ref: time in seconds :type ref: int | None :return: tuple with start and end time :rtype: tuple """ now = time.localtime(ref) if self.syear == 0: self.syear = now.tm_year day_start = find_day_by_weekday_offset(self.syear, self.smon, self.swday, self.swday_offset) start_time = get_start_of_day(self.syear, self.smon, day_start) if self.eyear == 0: self.eyear = now.tm_year day_end = find_day_by_weekday_offset(self.eyear, self.emon, self.ewday, self.ewday_offset) end_time = get_end_of_day(self.eyear, self.emon, day_end) now_epoch = time.mktime(now) if start_time > end_time: # the period is between years if now_epoch > end_time: # check for next year day_end = find_day_by_weekday_offset(self.eyear + 1, self.emon, self.ewday, self.ewday_offset) end_time = get_end_of_day(self.eyear + 1, self.emon, day_end) else: # it s just that the start was the last year day_start = find_day_by_weekday_offset(self.syear - 1, self.smon, self.swday, self.swday_offset) start_time = get_start_of_day(self.syear - 1, self.smon, day_start) else: if now_epoch > end_time: # just have to check for next year if necessary day_start = find_day_by_weekday_offset(self.syear + 1, self.smon, self.swday, self.swday_offset) start_time = get_start_of_day(self.syear + 1, self.smon, day_start) day_end = find_day_by_weekday_offset(self.eyear + 1, self.emon, self.ewday, self.ewday_offset) end_time = get_end_of_day(self.eyear + 1, self.emon, day_end) return (start_time, end_time)
python
def get_start_and_end_time(self, ref=None): now = time.localtime(ref) if self.syear == 0: self.syear = now.tm_year day_start = find_day_by_weekday_offset(self.syear, self.smon, self.swday, self.swday_offset) start_time = get_start_of_day(self.syear, self.smon, day_start) if self.eyear == 0: self.eyear = now.tm_year day_end = find_day_by_weekday_offset(self.eyear, self.emon, self.ewday, self.ewday_offset) end_time = get_end_of_day(self.eyear, self.emon, day_end) now_epoch = time.mktime(now) if start_time > end_time: # the period is between years if now_epoch > end_time: # check for next year day_end = find_day_by_weekday_offset(self.eyear + 1, self.emon, self.ewday, self.ewday_offset) end_time = get_end_of_day(self.eyear + 1, self.emon, day_end) else: # it s just that the start was the last year day_start = find_day_by_weekday_offset(self.syear - 1, self.smon, self.swday, self.swday_offset) start_time = get_start_of_day(self.syear - 1, self.smon, day_start) else: if now_epoch > end_time: # just have to check for next year if necessary day_start = find_day_by_weekday_offset(self.syear + 1, self.smon, self.swday, self.swday_offset) start_time = get_start_of_day(self.syear + 1, self.smon, day_start) day_end = find_day_by_weekday_offset(self.eyear + 1, self.emon, self.ewday, self.ewday_offset) end_time = get_end_of_day(self.eyear + 1, self.emon, day_end) return (start_time, end_time)
[ "def", "get_start_and_end_time", "(", "self", ",", "ref", "=", "None", ")", ":", "now", "=", "time", ".", "localtime", "(", "ref", ")", "if", "self", ".", "syear", "==", "0", ":", "self", ".", "syear", "=", "now", ".", "tm_year", "day_start", "=", ...
Specific function to get start time and end time for MonthWeekDayDaterange :param ref: time in seconds :type ref: int | None :return: tuple with start and end time :rtype: tuple
[ "Specific", "function", "to", "get", "start", "time", "and", "end", "time", "for", "MonthWeekDayDaterange" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L837-L878
20,851
Alignak-monitoring/alignak
alignak/daterange.py
MonthDateDaterange.get_start_and_end_time
def get_start_and_end_time(self, ref=None): """Specific function to get start time and end time for MonthDateDaterange :param ref: time in seconds :type ref: int :return: tuple with start and end time :rtype: tuple (int, int) """ now = time.localtime(ref) if self.syear == 0: self.syear = now.tm_year day_start = find_day_by_offset(self.syear, self.smon, self.smday) start_time = get_start_of_day(self.syear, self.smon, day_start) if self.eyear == 0: self.eyear = now.tm_year day_end = find_day_by_offset(self.eyear, self.emon, self.emday) end_time = get_end_of_day(self.eyear, self.emon, day_end) now_epoch = time.mktime(now) if start_time > end_time: # the period is between years if now_epoch > end_time: # check for next year day_end = find_day_by_offset(self.eyear + 1, self.emon, self.emday) end_time = get_end_of_day(self.eyear + 1, self.emon, day_end) else: # it s just that start was the last year day_start = find_day_by_offset(self.syear - 1, self.smon, self.emday) start_time = get_start_of_day(self.syear - 1, self.smon, day_start) else: if now_epoch > end_time: # just have to check for next year if necessary day_start = find_day_by_offset(self.syear + 1, self.smon, self.smday) start_time = get_start_of_day(self.syear + 1, self.smon, day_start) day_end = find_day_by_offset(self.eyear + 1, self.emon, self.emday) end_time = get_end_of_day(self.eyear + 1, self.emon, day_end) return (start_time, end_time)
python
def get_start_and_end_time(self, ref=None): now = time.localtime(ref) if self.syear == 0: self.syear = now.tm_year day_start = find_day_by_offset(self.syear, self.smon, self.smday) start_time = get_start_of_day(self.syear, self.smon, day_start) if self.eyear == 0: self.eyear = now.tm_year day_end = find_day_by_offset(self.eyear, self.emon, self.emday) end_time = get_end_of_day(self.eyear, self.emon, day_end) now_epoch = time.mktime(now) if start_time > end_time: # the period is between years if now_epoch > end_time: # check for next year day_end = find_day_by_offset(self.eyear + 1, self.emon, self.emday) end_time = get_end_of_day(self.eyear + 1, self.emon, day_end) else: # it s just that start was the last year day_start = find_day_by_offset(self.syear - 1, self.smon, self.emday) start_time = get_start_of_day(self.syear - 1, self.smon, day_start) else: if now_epoch > end_time: # just have to check for next year if necessary day_start = find_day_by_offset(self.syear + 1, self.smon, self.smday) start_time = get_start_of_day(self.syear + 1, self.smon, day_start) day_end = find_day_by_offset(self.eyear + 1, self.emon, self.emday) end_time = get_end_of_day(self.eyear + 1, self.emon, day_end) return (start_time, end_time)
[ "def", "get_start_and_end_time", "(", "self", ",", "ref", "=", "None", ")", ":", "now", "=", "time", ".", "localtime", "(", "ref", ")", "if", "self", ".", "syear", "==", "0", ":", "self", ".", "syear", "=", "now", ".", "tm_year", "day_start", "=", ...
Specific function to get start time and end time for MonthDateDaterange :param ref: time in seconds :type ref: int :return: tuple with start and end time :rtype: tuple (int, int)
[ "Specific", "function", "to", "get", "start", "time", "and", "end", "time", "for", "MonthDateDaterange" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L885-L922
20,852
Alignak-monitoring/alignak
alignak/daterange.py
WeekDayDaterange.get_start_and_end_time
def get_start_and_end_time(self, ref=None): """Specific function to get start time and end time for WeekDayDaterange :param ref: time in seconds :type ref: int :return: tuple with start and end time :rtype: tuple (int, int) """ now = time.localtime(ref) # If no year, it's our year if self.syear == 0: self.syear = now.tm_year month_start_id = now.tm_mon day_start = find_day_by_weekday_offset(self.syear, month_start_id, self.swday, self.swday_offset) start_time = get_start_of_day(self.syear, month_start_id, day_start) # Same for end year if self.eyear == 0: self.eyear = now.tm_year month_end_id = now.tm_mon day_end = find_day_by_weekday_offset(self.eyear, month_end_id, self.ewday, self.ewday_offset) end_time = get_end_of_day(self.eyear, month_end_id, day_end) # Maybe end_time is before start. So look for the # next month if start_time > end_time: month_end_id += 1 if month_end_id > 12: month_end_id = 1 self.eyear += 1 day_end = find_day_by_weekday_offset(self.eyear, month_end_id, self.ewday, self.ewday_offset) end_time = get_end_of_day(self.eyear, month_end_id, day_end) now_epoch = time.mktime(now) # But maybe we look not enought far. We should add a month if end_time < now_epoch: month_end_id += 1 month_start_id += 1 if month_end_id > 12: month_end_id = 1 self.eyear += 1 if month_start_id > 12: month_start_id = 1 self.syear += 1 # First start day_start = find_day_by_weekday_offset(self.syear, month_start_id, self.swday, self.swday_offset) start_time = get_start_of_day(self.syear, month_start_id, day_start) # Then end day_end = find_day_by_weekday_offset(self.eyear, month_end_id, self.ewday, self.ewday_offset) end_time = get_end_of_day(self.eyear, month_end_id, day_end) return (start_time, end_time)
python
def get_start_and_end_time(self, ref=None): now = time.localtime(ref) # If no year, it's our year if self.syear == 0: self.syear = now.tm_year month_start_id = now.tm_mon day_start = find_day_by_weekday_offset(self.syear, month_start_id, self.swday, self.swday_offset) start_time = get_start_of_day(self.syear, month_start_id, day_start) # Same for end year if self.eyear == 0: self.eyear = now.tm_year month_end_id = now.tm_mon day_end = find_day_by_weekday_offset(self.eyear, month_end_id, self.ewday, self.ewday_offset) end_time = get_end_of_day(self.eyear, month_end_id, day_end) # Maybe end_time is before start. So look for the # next month if start_time > end_time: month_end_id += 1 if month_end_id > 12: month_end_id = 1 self.eyear += 1 day_end = find_day_by_weekday_offset(self.eyear, month_end_id, self.ewday, self.ewday_offset) end_time = get_end_of_day(self.eyear, month_end_id, day_end) now_epoch = time.mktime(now) # But maybe we look not enought far. We should add a month if end_time < now_epoch: month_end_id += 1 month_start_id += 1 if month_end_id > 12: month_end_id = 1 self.eyear += 1 if month_start_id > 12: month_start_id = 1 self.syear += 1 # First start day_start = find_day_by_weekday_offset(self.syear, month_start_id, self.swday, self.swday_offset) start_time = get_start_of_day(self.syear, month_start_id, day_start) # Then end day_end = find_day_by_weekday_offset(self.eyear, month_end_id, self.ewday, self.ewday_offset) end_time = get_end_of_day(self.eyear, month_end_id, day_end) return (start_time, end_time)
[ "def", "get_start_and_end_time", "(", "self", ",", "ref", "=", "None", ")", ":", "now", "=", "time", ".", "localtime", "(", "ref", ")", "# If no year, it's our year", "if", "self", ".", "syear", "==", "0", ":", "self", ".", "syear", "=", "now", ".", "t...
Specific function to get start time and end time for WeekDayDaterange :param ref: time in seconds :type ref: int :return: tuple with start and end time :rtype: tuple (int, int)
[ "Specific", "function", "to", "get", "start", "time", "and", "end", "time", "for", "WeekDayDaterange" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L929-L986
20,853
Alignak-monitoring/alignak
alignak/daterange.py
MonthDayDaterange.get_start_and_end_time
def get_start_and_end_time(self, ref=None): """Specific function to get start time and end time for MonthDayDaterange :param ref: time in seconds :type ref: int :return: tuple with start and end time :rtype: tuple (int, int) """ now = time.localtime(ref) if self.syear == 0: self.syear = now.tm_year month_start_id = now.tm_mon day_start = find_day_by_offset(self.syear, month_start_id, self.smday) start_time = get_start_of_day(self.syear, month_start_id, day_start) if self.eyear == 0: self.eyear = now.tm_year month_end_id = now.tm_mon day_end = find_day_by_offset(self.eyear, month_end_id, self.emday) end_time = get_end_of_day(self.eyear, month_end_id, day_end) now_epoch = time.mktime(now) if start_time > end_time: month_start_id -= 1 if month_start_id < 1: month_start_id = 12 self.syear -= 1 day_start = find_day_by_offset(self.syear, month_start_id, self.smday) start_time = get_start_of_day(self.syear, month_start_id, day_start) if end_time < now_epoch: month_end_id += 1 month_start_id += 1 if month_end_id > 12: month_end_id = 1 self.eyear += 1 if month_start_id > 12: month_start_id = 1 self.syear += 1 # For the start day_start = find_day_by_offset(self.syear, month_start_id, self.smday) start_time = get_start_of_day(self.syear, month_start_id, day_start) # For the end day_end = find_day_by_offset(self.eyear, month_end_id, self.emday) end_time = get_end_of_day(self.eyear, month_end_id, day_end) return (start_time, end_time)
python
def get_start_and_end_time(self, ref=None): now = time.localtime(ref) if self.syear == 0: self.syear = now.tm_year month_start_id = now.tm_mon day_start = find_day_by_offset(self.syear, month_start_id, self.smday) start_time = get_start_of_day(self.syear, month_start_id, day_start) if self.eyear == 0: self.eyear = now.tm_year month_end_id = now.tm_mon day_end = find_day_by_offset(self.eyear, month_end_id, self.emday) end_time = get_end_of_day(self.eyear, month_end_id, day_end) now_epoch = time.mktime(now) if start_time > end_time: month_start_id -= 1 if month_start_id < 1: month_start_id = 12 self.syear -= 1 day_start = find_day_by_offset(self.syear, month_start_id, self.smday) start_time = get_start_of_day(self.syear, month_start_id, day_start) if end_time < now_epoch: month_end_id += 1 month_start_id += 1 if month_end_id > 12: month_end_id = 1 self.eyear += 1 if month_start_id > 12: month_start_id = 1 self.syear += 1 # For the start day_start = find_day_by_offset(self.syear, month_start_id, self.smday) start_time = get_start_of_day(self.syear, month_start_id, day_start) # For the end day_end = find_day_by_offset(self.eyear, month_end_id, self.emday) end_time = get_end_of_day(self.eyear, month_end_id, day_end) return (start_time, end_time)
[ "def", "get_start_and_end_time", "(", "self", ",", "ref", "=", "None", ")", ":", "now", "=", "time", ".", "localtime", "(", "ref", ")", "if", "self", ".", "syear", "==", "0", ":", "self", ".", "syear", "=", "now", ".", "tm_year", "month_start_id", "=...
Specific function to get start time and end time for MonthDayDaterange :param ref: time in seconds :type ref: int :return: tuple with start and end time :rtype: tuple (int, int)
[ "Specific", "function", "to", "get", "start", "time", "and", "end", "time", "for", "MonthDayDaterange" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L993-L1042
20,854
Alignak-monitoring/alignak
alignak/external_command.py
ExternalCommandManager.get_unknown_check_result_brok
def get_unknown_check_result_brok(cmd_line): """Create unknown check result brok and fill it with command data :param cmd_line: command line to extract data :type cmd_line: str :return: unknown check result brok :rtype: alignak.objects.brok.Brok """ match = re.match( r'^\[([0-9]{10})] PROCESS_(SERVICE)_CHECK_RESULT;' r'([^\;]*);([^\;]*);([^\;]*);([^\|]*)(?:\|(.*))?', cmd_line) if not match: match = re.match( r'^\[([0-9]{10})] PROCESS_(HOST)_CHECK_RESULT;' r'([^\;]*);([^\;]*);([^\|]*)(?:\|(.*))?', cmd_line) if not match: return None data = { 'time_stamp': int(match.group(1)), 'host_name': match.group(3), } if match.group(2) == 'SERVICE': data['service_description'] = match.group(4) data['return_code'] = match.group(5) data['output'] = match.group(6) data['perf_data'] = match.group(7) else: data['return_code'] = match.group(4) data['output'] = match.group(5) data['perf_data'] = match.group(6) return Brok({'type': 'unknown_%s_check_result' % match.group(2).lower(), 'data': data})
python
def get_unknown_check_result_brok(cmd_line): match = re.match( r'^\[([0-9]{10})] PROCESS_(SERVICE)_CHECK_RESULT;' r'([^\;]*);([^\;]*);([^\;]*);([^\|]*)(?:\|(.*))?', cmd_line) if not match: match = re.match( r'^\[([0-9]{10})] PROCESS_(HOST)_CHECK_RESULT;' r'([^\;]*);([^\;]*);([^\|]*)(?:\|(.*))?', cmd_line) if not match: return None data = { 'time_stamp': int(match.group(1)), 'host_name': match.group(3), } if match.group(2) == 'SERVICE': data['service_description'] = match.group(4) data['return_code'] = match.group(5) data['output'] = match.group(6) data['perf_data'] = match.group(7) else: data['return_code'] = match.group(4) data['output'] = match.group(5) data['perf_data'] = match.group(6) return Brok({'type': 'unknown_%s_check_result' % match.group(2).lower(), 'data': data})
[ "def", "get_unknown_check_result_brok", "(", "cmd_line", ")", ":", "match", "=", "re", ".", "match", "(", "r'^\\[([0-9]{10})] PROCESS_(SERVICE)_CHECK_RESULT;'", "r'([^\\;]*);([^\\;]*);([^\\;]*);([^\\|]*)(?:\\|(.*))?'", ",", "cmd_line", ")", "if", "not", "match", ":", "match...
Create unknown check result brok and fill it with command data :param cmd_line: command line to extract data :type cmd_line: str :return: unknown check result brok :rtype: alignak.objects.brok.Brok
[ "Create", "unknown", "check", "result", "brok", "and", "fill", "it", "with", "command", "data" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/external_command.py#L676-L710
20,855
Alignak-monitoring/alignak
alignak/objects/hostdependency.py
Hostdependency.get_name
def get_name(self): """Get name based on dependent_host_name and host_name attributes Each attribute is substituted by 'unknown' if attribute does not exist :return: dependent_host_name/host_name :rtype: str """ dependent_host_name = 'unknown' if getattr(self, 'dependent_host_name', None): dependent_host_name = getattr( getattr(self, 'dependent_host_name'), 'host_name', 'unknown' ) host_name = 'unknown' if getattr(self, 'host_name', None): host_name = getattr(getattr(self, 'host_name'), 'host_name', 'unknown') return dependent_host_name + '/' + host_name
python
def get_name(self): dependent_host_name = 'unknown' if getattr(self, 'dependent_host_name', None): dependent_host_name = getattr( getattr(self, 'dependent_host_name'), 'host_name', 'unknown' ) host_name = 'unknown' if getattr(self, 'host_name', None): host_name = getattr(getattr(self, 'host_name'), 'host_name', 'unknown') return dependent_host_name + '/' + host_name
[ "def", "get_name", "(", "self", ")", ":", "dependent_host_name", "=", "'unknown'", "if", "getattr", "(", "self", ",", "'dependent_host_name'", ",", "None", ")", ":", "dependent_host_name", "=", "getattr", "(", "getattr", "(", "self", ",", "'dependent_host_name'"...
Get name based on dependent_host_name and host_name attributes Each attribute is substituted by 'unknown' if attribute does not exist :return: dependent_host_name/host_name :rtype: str
[ "Get", "name", "based", "on", "dependent_host_name", "and", "host_name", "attributes", "Each", "attribute", "is", "substituted", "by", "unknown", "if", "attribute", "does", "not", "exist" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/hostdependency.py#L110-L125
20,856
Alignak-monitoring/alignak
alignak/objects/hostdependency.py
Hostdependencies.linkify_hd_by_h
def linkify_hd_by_h(self, hosts): """Replace dependent_host_name and host_name in host dependency by the real object :param hosts: host list, used to look for a specific one :type hosts: alignak.objects.host.Hosts :return: None """ for hostdep in self: try: h_name = hostdep.host_name dh_name = hostdep.dependent_host_name host = hosts.find_by_name(h_name) if host is None: err = "Error: the host dependency got a bad host_name definition '%s'" % h_name hostdep.add_error(err) dephost = hosts.find_by_name(dh_name) if dephost is None: err = "Error: the host dependency got " \ "a bad dependent_host_name definition '%s'" % dh_name hostdep.add_error(err) if host: hostdep.host_name = host.uuid if dephost: hostdep.dependent_host_name = dephost.uuid except AttributeError as exp: err = "Error: the host dependency miss a property '%s'" % exp hostdep.add_error(err)
python
def linkify_hd_by_h(self, hosts): for hostdep in self: try: h_name = hostdep.host_name dh_name = hostdep.dependent_host_name host = hosts.find_by_name(h_name) if host is None: err = "Error: the host dependency got a bad host_name definition '%s'" % h_name hostdep.add_error(err) dephost = hosts.find_by_name(dh_name) if dephost is None: err = "Error: the host dependency got " \ "a bad dependent_host_name definition '%s'" % dh_name hostdep.add_error(err) if host: hostdep.host_name = host.uuid if dephost: hostdep.dependent_host_name = dephost.uuid except AttributeError as exp: err = "Error: the host dependency miss a property '%s'" % exp hostdep.add_error(err)
[ "def", "linkify_hd_by_h", "(", "self", ",", "hosts", ")", ":", "for", "hostdep", "in", "self", ":", "try", ":", "h_name", "=", "hostdep", ".", "host_name", "dh_name", "=", "hostdep", ".", "dependent_host_name", "host", "=", "hosts", ".", "find_by_name", "(...
Replace dependent_host_name and host_name in host dependency by the real object :param hosts: host list, used to look for a specific one :type hosts: alignak.objects.host.Hosts :return: None
[ "Replace", "dependent_host_name", "and", "host_name", "in", "host", "dependency", "by", "the", "real", "object" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/hostdependency.py#L224-L251
20,857
Alignak-monitoring/alignak
alignak/objects/hostdependency.py
Hostdependencies.linkify_hd_by_tp
def linkify_hd_by_tp(self, timeperiods): """Replace dependency_period by a real object in host dependency :param timeperiods: list of timeperiod, used to look for a specific one :type timeperiods: alignak.objects.timeperiod.Timeperiods :return: None """ for hostdep in self: try: tp_name = hostdep.dependency_period timeperiod = timeperiods.find_by_name(tp_name) if timeperiod: hostdep.dependency_period = timeperiod.uuid else: hostdep.dependency_period = '' except AttributeError as exp: # pragma: no cover, simple protectionn logger.error("[hostdependency] fail to linkify by timeperiod: %s", exp)
python
def linkify_hd_by_tp(self, timeperiods): for hostdep in self: try: tp_name = hostdep.dependency_period timeperiod = timeperiods.find_by_name(tp_name) if timeperiod: hostdep.dependency_period = timeperiod.uuid else: hostdep.dependency_period = '' except AttributeError as exp: # pragma: no cover, simple protectionn logger.error("[hostdependency] fail to linkify by timeperiod: %s", exp)
[ "def", "linkify_hd_by_tp", "(", "self", ",", "timeperiods", ")", ":", "for", "hostdep", "in", "self", ":", "try", ":", "tp_name", "=", "hostdep", ".", "dependency_period", "timeperiod", "=", "timeperiods", ".", "find_by_name", "(", "tp_name", ")", "if", "tim...
Replace dependency_period by a real object in host dependency :param timeperiods: list of timeperiod, used to look for a specific one :type timeperiods: alignak.objects.timeperiod.Timeperiods :return: None
[ "Replace", "dependency_period", "by", "a", "real", "object", "in", "host", "dependency" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/hostdependency.py#L253-L269
20,858
Alignak-monitoring/alignak
alignak/objects/hostextinfo.py
HostsExtInfo.merge_extinfo
def merge_extinfo(host, extinfo): """Merge extended host information into a host :param host: the host to edit :type host: alignak.objects.host.Host :param extinfo: the external info we get data from :type extinfo: alignak.objects.hostextinfo.HostExtInfo :return: None """ # Note that 2d_coords and 3d_coords are never merged, so not usable ! properties = ['notes', 'notes_url', 'icon_image', 'icon_image_alt', 'vrml_image', 'statusmap_image'] # host properties have precedence over hostextinfo properties for prop in properties: if getattr(host, prop) == '' and getattr(extinfo, prop) != '': setattr(host, prop, getattr(extinfo, prop))
python
def merge_extinfo(host, extinfo): # Note that 2d_coords and 3d_coords are never merged, so not usable ! properties = ['notes', 'notes_url', 'icon_image', 'icon_image_alt', 'vrml_image', 'statusmap_image'] # host properties have precedence over hostextinfo properties for prop in properties: if getattr(host, prop) == '' and getattr(extinfo, prop) != '': setattr(host, prop, getattr(extinfo, prop))
[ "def", "merge_extinfo", "(", "host", ",", "extinfo", ")", ":", "# Note that 2d_coords and 3d_coords are never merged, so not usable !", "properties", "=", "[", "'notes'", ",", "'notes_url'", ",", "'icon_image'", ",", "'icon_image_alt'", ",", "'vrml_image'", ",", "'statusm...
Merge extended host information into a host :param host: the host to edit :type host: alignak.objects.host.Host :param extinfo: the external info we get data from :type extinfo: alignak.objects.hostextinfo.HostExtInfo :return: None
[ "Merge", "extended", "host", "information", "into", "a", "host" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/hostextinfo.py#L136-L151
20,859
Alignak-monitoring/alignak
alignak/http/client.py
HTTPClient.set_proxy
def set_proxy(self, proxy): # pragma: no cover, not with unit tests """Set HTTP proxy :param proxy: proxy url :type proxy: str :return: None """ if proxy: logger.debug('PROXY SETTING PROXY %s', proxy) self._requests_con.proxies = { 'http': proxy, 'https': proxy, }
python
def set_proxy(self, proxy): # pragma: no cover, not with unit tests if proxy: logger.debug('PROXY SETTING PROXY %s', proxy) self._requests_con.proxies = { 'http': proxy, 'https': proxy, }
[ "def", "set_proxy", "(", "self", ",", "proxy", ")", ":", "# pragma: no cover, not with unit tests", "if", "proxy", ":", "logger", ".", "debug", "(", "'PROXY SETTING PROXY %s'", ",", "proxy", ")", "self", ".", "_requests_con", ".", "proxies", "=", "{", "'http'", ...
Set HTTP proxy :param proxy: proxy url :type proxy: str :return: None
[ "Set", "HTTP", "proxy" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/client.py#L176-L188
20,860
Alignak-monitoring/alignak
alignak/http/client.py
HTTPClient.post
def post(self, path, args, wait=False): """POST an HTTP request to a daemon :param path: path to do the request :type path: str :param args: args to add in the request :type args: dict :param wait: True for a long timeout :type wait: bool :return: Content of the HTTP response if server returned 200 :rtype: str """ uri = self.make_uri(path) timeout = self.make_timeout(wait) for (key, value) in list(args.items()): args[key] = serialize(value, True) try: logger.debug("post: %s, timeout: %s, params: %s", uri, timeout, args) rsp = self._requests_con.post(uri, json=args, timeout=timeout, verify=self.strong_ssl) logger.debug("got: %d - %s", rsp.status_code, rsp.text) if rsp.status_code != 200: raise HTTPClientDataException(rsp.status_code, rsp.text, uri) return rsp.content except (requests.Timeout, requests.ConnectTimeout): raise HTTPClientTimeoutException(timeout, uri) except requests.ConnectionError as exp: raise HTTPClientConnectionException(uri, exp.args[0]) except Exception as exp: raise HTTPClientException('Request error to %s: %s' % (uri, exp))
python
def post(self, path, args, wait=False): uri = self.make_uri(path) timeout = self.make_timeout(wait) for (key, value) in list(args.items()): args[key] = serialize(value, True) try: logger.debug("post: %s, timeout: %s, params: %s", uri, timeout, args) rsp = self._requests_con.post(uri, json=args, timeout=timeout, verify=self.strong_ssl) logger.debug("got: %d - %s", rsp.status_code, rsp.text) if rsp.status_code != 200: raise HTTPClientDataException(rsp.status_code, rsp.text, uri) return rsp.content except (requests.Timeout, requests.ConnectTimeout): raise HTTPClientTimeoutException(timeout, uri) except requests.ConnectionError as exp: raise HTTPClientConnectionException(uri, exp.args[0]) except Exception as exp: raise HTTPClientException('Request error to %s: %s' % (uri, exp))
[ "def", "post", "(", "self", ",", "path", ",", "args", ",", "wait", "=", "False", ")", ":", "uri", "=", "self", ".", "make_uri", "(", "path", ")", "timeout", "=", "self", ".", "make_timeout", "(", "wait", ")", "for", "(", "key", ",", "value", ")",...
POST an HTTP request to a daemon :param path: path to do the request :type path: str :param args: args to add in the request :type args: dict :param wait: True for a long timeout :type wait: bool :return: Content of the HTTP response if server returned 200 :rtype: str
[ "POST", "an", "HTTP", "request", "to", "a", "daemon" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/client.py#L219-L247
20,861
Alignak-monitoring/alignak
alignak/http/client.py
HTTPClient.put
def put(self, path, args, wait=False): # pragma: no cover, looks never used! # todo: remove this because it looks never used anywhere... """PUT and HTTP request to a daemon :param path: path to do the request :type path: str :param args: data to send in the request :type args: :return: Content of the HTTP response if server returned 200 :rtype: str """ uri = self.make_uri(path) timeout = self.make_timeout(wait) try: logger.debug("put: %s, timeout: %s, params: %s", uri, timeout, args) rsp = self._requests_con.put(uri, args, timeout=timeout, verify=self.strong_ssl) logger.debug("got: %d - %s", rsp.status_code, rsp.text) if rsp.status_code != 200: raise HTTPClientDataException(rsp.status_code, rsp.text, uri) return rsp.content except (requests.Timeout, requests.ConnectTimeout): raise HTTPClientTimeoutException(timeout, uri) except requests.ConnectionError as exp: raise HTTPClientConnectionException(uri, exp.args[0]) except Exception as exp: raise HTTPClientException('Request error to %s: %s' % (uri, exp))
python
def put(self, path, args, wait=False): # pragma: no cover, looks never used! # todo: remove this because it looks never used anywhere... uri = self.make_uri(path) timeout = self.make_timeout(wait) try: logger.debug("put: %s, timeout: %s, params: %s", uri, timeout, args) rsp = self._requests_con.put(uri, args, timeout=timeout, verify=self.strong_ssl) logger.debug("got: %d - %s", rsp.status_code, rsp.text) if rsp.status_code != 200: raise HTTPClientDataException(rsp.status_code, rsp.text, uri) return rsp.content except (requests.Timeout, requests.ConnectTimeout): raise HTTPClientTimeoutException(timeout, uri) except requests.ConnectionError as exp: raise HTTPClientConnectionException(uri, exp.args[0]) except Exception as exp: raise HTTPClientException('Request error to %s: %s' % (uri, exp))
[ "def", "put", "(", "self", ",", "path", ",", "args", ",", "wait", "=", "False", ")", ":", "# pragma: no cover, looks never used!", "# todo: remove this because it looks never used anywhere...", "uri", "=", "self", ".", "make_uri", "(", "path", ")", "timeout", "=", ...
PUT and HTTP request to a daemon :param path: path to do the request :type path: str :param args: data to send in the request :type args: :return: Content of the HTTP response if server returned 200 :rtype: str
[ "PUT", "and", "HTTP", "request", "to", "a", "daemon" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/client.py#L249-L274
20,862
Alignak-monitoring/alignak
alignak/objects/hostescalation.py
Hostescalations.explode
def explode(self, escalations): """Create instance of Escalation for each HostEscalation object :param escalations: list of escalation, used to add new ones :type escalations: alignak.objects.escalation.Escalations :return: None """ # Now we explode all escalations (host_name, hostgroup_name) to escalations for escalation in self: properties = escalation.__class__.properties name = getattr(escalation, 'host_name', getattr(escalation, 'hostgroup_name', '')) creation_dict = { 'escalation_name': 'Generated-HE-%s-%s' % (name, escalation.uuid) } for prop in properties: if hasattr(escalation, prop): creation_dict[prop] = getattr(escalation, prop) escalations.add_escalation(Escalation(creation_dict))
python
def explode(self, escalations): # Now we explode all escalations (host_name, hostgroup_name) to escalations for escalation in self: properties = escalation.__class__.properties name = getattr(escalation, 'host_name', getattr(escalation, 'hostgroup_name', '')) creation_dict = { 'escalation_name': 'Generated-HE-%s-%s' % (name, escalation.uuid) } for prop in properties: if hasattr(escalation, prop): creation_dict[prop] = getattr(escalation, prop) escalations.add_escalation(Escalation(creation_dict))
[ "def", "explode", "(", "self", ",", "escalations", ")", ":", "# Now we explode all escalations (host_name, hostgroup_name) to escalations", "for", "escalation", "in", "self", ":", "properties", "=", "escalation", ".", "__class__", ".", "properties", "name", "=", "getatt...
Create instance of Escalation for each HostEscalation object :param escalations: list of escalation, used to add new ones :type escalations: alignak.objects.escalation.Escalations :return: None
[ "Create", "instance", "of", "Escalation", "for", "each", "HostEscalation", "object" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/hostescalation.py#L109-L128
20,863
Alignak-monitoring/alignak
alignak/stats.py
Stats.register
def register(self, name, _type, statsd_host='localhost', statsd_port=8125, statsd_prefix='alignak', statsd_enabled=False, broks_enabled=False): """Init instance with real values :param name: daemon name :type name: str :param _type: daemon type :type _type: :param statsd_host: host to post data :type statsd_host: str :param statsd_port: port to post data :type statsd_port: int :param statsd_prefix: prefix to add to metric :type statsd_prefix: str :param statsd_enabled: bool to enable statsd :type statsd_enabled: bool :param broks_enabled: bool to enable broks sending :type broks_enabled: bool :return: None """ self.name = name # This attribute is not used, but I keep ascending compatibility with former interface! self._type = _type # local statsd part self.statsd_host = statsd_host self.statsd_port = int(statsd_port) self.statsd_prefix = statsd_prefix self.statsd_enabled = statsd_enabled # local broks part self.broks_enabled = broks_enabled logger.debug("StatsD configuration for %s - %s:%s, prefix: %s, " "enabled: %s, broks: %s, file: %s", self.name, self.statsd_host, self.statsd_port, self.statsd_prefix, self.statsd_enabled, self.broks_enabled, self.stats_file) if self.statsd_enabled and self.statsd_host is not None and self.statsd_host != 'None': logger.info("Sending %s statistics to: %s:%s, prefix: %s", self.name, self.statsd_host, self.statsd_port, self.statsd_prefix) if self.load_statsd(): logger.info('Alignak internal statistics are sent to StatsD.') else: logger.info('StatsD server is not available.') if self.stats_file: try: self.file_d = open(self.stats_file, 'a') logger.info("Alignak internal statistics are written in the file %s", self.stats_file) except OSError as exp: # pragma: no cover, should never happen... logger.exception("Error when opening the file '%s' : %s", self.stats_file, exp) self.file_d = None return self.statsd_enabled
python
def register(self, name, _type, statsd_host='localhost', statsd_port=8125, statsd_prefix='alignak', statsd_enabled=False, broks_enabled=False): self.name = name # This attribute is not used, but I keep ascending compatibility with former interface! self._type = _type # local statsd part self.statsd_host = statsd_host self.statsd_port = int(statsd_port) self.statsd_prefix = statsd_prefix self.statsd_enabled = statsd_enabled # local broks part self.broks_enabled = broks_enabled logger.debug("StatsD configuration for %s - %s:%s, prefix: %s, " "enabled: %s, broks: %s, file: %s", self.name, self.statsd_host, self.statsd_port, self.statsd_prefix, self.statsd_enabled, self.broks_enabled, self.stats_file) if self.statsd_enabled and self.statsd_host is not None and self.statsd_host != 'None': logger.info("Sending %s statistics to: %s:%s, prefix: %s", self.name, self.statsd_host, self.statsd_port, self.statsd_prefix) if self.load_statsd(): logger.info('Alignak internal statistics are sent to StatsD.') else: logger.info('StatsD server is not available.') if self.stats_file: try: self.file_d = open(self.stats_file, 'a') logger.info("Alignak internal statistics are written in the file %s", self.stats_file) except OSError as exp: # pragma: no cover, should never happen... logger.exception("Error when opening the file '%s' : %s", self.stats_file, exp) self.file_d = None return self.statsd_enabled
[ "def", "register", "(", "self", ",", "name", ",", "_type", ",", "statsd_host", "=", "'localhost'", ",", "statsd_port", "=", "8125", ",", "statsd_prefix", "=", "'alignak'", ",", "statsd_enabled", "=", "False", ",", "broks_enabled", "=", "False", ")", ":", "...
Init instance with real values :param name: daemon name :type name: str :param _type: daemon type :type _type: :param statsd_host: host to post data :type statsd_host: str :param statsd_port: port to post data :type statsd_port: int :param statsd_prefix: prefix to add to metric :type statsd_prefix: str :param statsd_enabled: bool to enable statsd :type statsd_enabled: bool :param broks_enabled: bool to enable broks sending :type broks_enabled: bool :return: None
[ "Init", "instance", "with", "real", "values" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/stats.py#L166-L222
20,864
Alignak-monitoring/alignak
alignak/stats.py
Stats.load_statsd
def load_statsd(self): """Create socket connection to statsd host Note that because of the UDP protocol used by StatsD, if no server is listening the socket connection will be accepted anyway :) :return: True if socket got created else False and an exception log is raised """ if not self.statsd_enabled: logger.info('Stats reporting is not enabled, connection is not allowed') return False if self.statsd_enabled and self.carbon: self.my_metrics.append(('.'.join([self.statsd_prefix, self.name, 'connection-test']), (int(time.time()), int(time.time())))) self.carbon.add_data_list(self.my_metrics) self.flush(log=True) else: try: logger.info('Trying to contact StatsD server...') self.statsd_addr = (socket.gethostbyname(self.statsd_host.encode('utf-8')), self.statsd_port) self.statsd_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) except (socket.error, socket.gaierror) as exp: logger.warning('Cannot create StatsD socket: %s', exp) return False except Exception as exp: # pylint: disable=broad-except logger.exception('Cannot create StatsD socket (other): %s', exp) return False logger.info('StatsD server contacted') return True
python
def load_statsd(self): if not self.statsd_enabled: logger.info('Stats reporting is not enabled, connection is not allowed') return False if self.statsd_enabled and self.carbon: self.my_metrics.append(('.'.join([self.statsd_prefix, self.name, 'connection-test']), (int(time.time()), int(time.time())))) self.carbon.add_data_list(self.my_metrics) self.flush(log=True) else: try: logger.info('Trying to contact StatsD server...') self.statsd_addr = (socket.gethostbyname(self.statsd_host.encode('utf-8')), self.statsd_port) self.statsd_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) except (socket.error, socket.gaierror) as exp: logger.warning('Cannot create StatsD socket: %s', exp) return False except Exception as exp: # pylint: disable=broad-except logger.exception('Cannot create StatsD socket (other): %s', exp) return False logger.info('StatsD server contacted') return True
[ "def", "load_statsd", "(", "self", ")", ":", "if", "not", "self", ".", "statsd_enabled", ":", "logger", ".", "info", "(", "'Stats reporting is not enabled, connection is not allowed'", ")", "return", "False", "if", "self", ".", "statsd_enabled", "and", "self", "."...
Create socket connection to statsd host Note that because of the UDP protocol used by StatsD, if no server is listening the socket connection will be accepted anyway :) :return: True if socket got created else False and an exception log is raised
[ "Create", "socket", "connection", "to", "statsd", "host" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/stats.py#L224-L255
20,865
Alignak-monitoring/alignak
alignak/stats.py
Stats.flush
def flush(self, log=False): """Send inner stored metrics to the defined Graphite Returns False if the sending failed with a warning log if log parameter is set :return: bool """ if not self.my_metrics: logger.debug("Flushing - no metrics to send") return True now = int(time.time()) if self.last_failure and self.last_failure + self.metrics_flush_pause > now: if not self.log_metrics_flush_pause: date = datetime.datetime.fromtimestamp( self.last_failure).strftime(self.date_fmt) logger.warning("Metrics flush paused on connection error " "(last failed: %s). " "Inner stored metric: %d. Trying to send...", date, self.metrics_count) self.log_metrics_flush_pause = True return True try: logger.debug("Flushing %d metrics to Graphite/carbon", self.metrics_count) if self.carbon.send_data(): self.my_metrics = [] else: logger.warning("Failed sending metrics to Graphite/carbon. " "Inner stored metric: %d", self.metrics_count) if log: logger.warning("Failed sending metrics to Graphite/carbon. " "Inner stored metric: %d", self.metrics_count) return False if self.log_metrics_flush_pause: logger.warning("Metrics flush restored. " "Remaining stored metric: %d", self.metrics_count) self.last_failure = 0 self.log_metrics_flush_pause = False except Exception as exp: # pylint: disable=broad-except if not self.log_metrics_flush_pause: logger.warning("Failed sending metrics to Graphite/carbon. " "Inner stored metric: %d", self.metrics_count) else: date = datetime.datetime.fromtimestamp( self.last_failure).strftime(self.date_fmt) logger.warning("Metrics flush paused on connection error " "(last failed: %s). " "Inner stored metric: %d. Trying to send...", date, self.metrics_count) logger.warning("Exception: %s", str(exp)) self.last_failure = now return False return True
python
def flush(self, log=False): if not self.my_metrics: logger.debug("Flushing - no metrics to send") return True now = int(time.time()) if self.last_failure and self.last_failure + self.metrics_flush_pause > now: if not self.log_metrics_flush_pause: date = datetime.datetime.fromtimestamp( self.last_failure).strftime(self.date_fmt) logger.warning("Metrics flush paused on connection error " "(last failed: %s). " "Inner stored metric: %d. Trying to send...", date, self.metrics_count) self.log_metrics_flush_pause = True return True try: logger.debug("Flushing %d metrics to Graphite/carbon", self.metrics_count) if self.carbon.send_data(): self.my_metrics = [] else: logger.warning("Failed sending metrics to Graphite/carbon. " "Inner stored metric: %d", self.metrics_count) if log: logger.warning("Failed sending metrics to Graphite/carbon. " "Inner stored metric: %d", self.metrics_count) return False if self.log_metrics_flush_pause: logger.warning("Metrics flush restored. " "Remaining stored metric: %d", self.metrics_count) self.last_failure = 0 self.log_metrics_flush_pause = False except Exception as exp: # pylint: disable=broad-except if not self.log_metrics_flush_pause: logger.warning("Failed sending metrics to Graphite/carbon. " "Inner stored metric: %d", self.metrics_count) else: date = datetime.datetime.fromtimestamp( self.last_failure).strftime(self.date_fmt) logger.warning("Metrics flush paused on connection error " "(last failed: %s). " "Inner stored metric: %d. Trying to send...", date, self.metrics_count) logger.warning("Exception: %s", str(exp)) self.last_failure = now return False return True
[ "def", "flush", "(", "self", ",", "log", "=", "False", ")", ":", "if", "not", "self", ".", "my_metrics", ":", "logger", ".", "debug", "(", "\"Flushing - no metrics to send\"", ")", "return", "True", "now", "=", "int", "(", "time", ".", "time", "(", ")"...
Send inner stored metrics to the defined Graphite Returns False if the sending failed with a warning log if log parameter is set :return: bool
[ "Send", "inner", "stored", "metrics", "to", "the", "defined", "Graphite" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/stats.py#L308-L362
20,866
Alignak-monitoring/alignak
alignak/stats.py
Stats.send_to_graphite
def send_to_graphite(self, metric, value, timestamp=None): """ Inner store a new metric and flush to Graphite if the flush threshold is reached. If no timestamp is provided, get the current time for the metric timestam. :param metric: metric name in dotted format :type metric: str :param value: :type value: float :param timestamp: metric timestamp :type timestamp: int """ # Manage Graphite part if not self.statsd_enabled or not self.carbon: return if timestamp is None: timestamp = int(time.time()) self.my_metrics.append(('.'.join([self.statsd_prefix, self.name, metric]), (timestamp, value))) if self.metrics_count >= self.metrics_flush_count: self.carbon.add_data_list(self.my_metrics) self.flush()
python
def send_to_graphite(self, metric, value, timestamp=None): # Manage Graphite part if not self.statsd_enabled or not self.carbon: return if timestamp is None: timestamp = int(time.time()) self.my_metrics.append(('.'.join([self.statsd_prefix, self.name, metric]), (timestamp, value))) if self.metrics_count >= self.metrics_flush_count: self.carbon.add_data_list(self.my_metrics) self.flush()
[ "def", "send_to_graphite", "(", "self", ",", "metric", ",", "value", ",", "timestamp", "=", "None", ")", ":", "# Manage Graphite part", "if", "not", "self", ".", "statsd_enabled", "or", "not", "self", ".", "carbon", ":", "return", "if", "timestamp", "is", ...
Inner store a new metric and flush to Graphite if the flush threshold is reached. If no timestamp is provided, get the current time for the metric timestam. :param metric: metric name in dotted format :type metric: str :param value: :type value: float :param timestamp: metric timestamp :type timestamp: int
[ "Inner", "store", "a", "new", "metric", "and", "flush", "to", "Graphite", "if", "the", "flush", "threshold", "is", "reached", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/stats.py#L364-L388
20,867
Alignak-monitoring/alignak
alignak/stats.py
Stats.counter
def counter(self, key, value, timestamp=None): """Set a counter value If the inner key does not exist is is created :param key: counter to update :type key: str :param value: counter value :type value: float :return: An alignak_stat brok if broks are enabled else None """ _min, _max, count, _sum = self.stats.get(key, (None, None, 0, 0)) count += 1 _sum += value if _min is None or value < _min: _min = value if _max is None or value > _max: _max = value self.stats[key] = (_min, _max, count, _sum) # Manage local statsd part if self.statsd_enabled and self.statsd_sock: # beware, we are sending ms here, timer is in seconds packet = '%s.%s.%s:%d|c' % (self.statsd_prefix, self.name, key, value) packet = packet.encode('utf-8') try: self.statsd_sock.sendto(packet, self.statsd_addr) except (socket.error, socket.gaierror): pass # cannot send? ok not a huge problem here and we cannot # log because it will be far too verbose :p # Manage Graphite part if self.statsd_enabled and self.carbon: self.send_to_graphite(key, value, timestamp=timestamp) # Manage file part if self.statsd_enabled and self.file_d: if timestamp is None: timestamp = int(time.time()) packet = self.line_fmt if not self.date_fmt: date = "%s" % timestamp else: date = datetime.datetime.fromtimestamp(timestamp).strftime(self.date_fmt) packet = packet.replace("#date#", date) packet = packet.replace("#counter#", '%s.%s.%s' % (self.statsd_prefix, self.name, key)) packet = packet.replace("#value#", '%d' % value) packet = packet.replace("#uom#", 'c') try: self.file_d.write(packet) except IOError: logger.warning("Could not write to the file: %s", packet) if self.broks_enabled: logger.debug("alignak stat brok: %s = %s", key, value) if timestamp is None: timestamp = int(time.time()) return Brok({'type': 'alignak_stat', 'data': { 'ts': timestamp, 'type': 'counter', 'metric': '%s.%s.%s' % (self.statsd_prefix, self.name, key), 'value': value, 'uom': 'c' }}) return None
python
def counter(self, key, value, timestamp=None): _min, _max, count, _sum = self.stats.get(key, (None, None, 0, 0)) count += 1 _sum += value if _min is None or value < _min: _min = value if _max is None or value > _max: _max = value self.stats[key] = (_min, _max, count, _sum) # Manage local statsd part if self.statsd_enabled and self.statsd_sock: # beware, we are sending ms here, timer is in seconds packet = '%s.%s.%s:%d|c' % (self.statsd_prefix, self.name, key, value) packet = packet.encode('utf-8') try: self.statsd_sock.sendto(packet, self.statsd_addr) except (socket.error, socket.gaierror): pass # cannot send? ok not a huge problem here and we cannot # log because it will be far too verbose :p # Manage Graphite part if self.statsd_enabled and self.carbon: self.send_to_graphite(key, value, timestamp=timestamp) # Manage file part if self.statsd_enabled and self.file_d: if timestamp is None: timestamp = int(time.time()) packet = self.line_fmt if not self.date_fmt: date = "%s" % timestamp else: date = datetime.datetime.fromtimestamp(timestamp).strftime(self.date_fmt) packet = packet.replace("#date#", date) packet = packet.replace("#counter#", '%s.%s.%s' % (self.statsd_prefix, self.name, key)) packet = packet.replace("#value#", '%d' % value) packet = packet.replace("#uom#", 'c') try: self.file_d.write(packet) except IOError: logger.warning("Could not write to the file: %s", packet) if self.broks_enabled: logger.debug("alignak stat brok: %s = %s", key, value) if timestamp is None: timestamp = int(time.time()) return Brok({'type': 'alignak_stat', 'data': { 'ts': timestamp, 'type': 'counter', 'metric': '%s.%s.%s' % (self.statsd_prefix, self.name, key), 'value': value, 'uom': 'c' }}) return None
[ "def", "counter", "(", "self", ",", "key", ",", "value", ",", "timestamp", "=", "None", ")", ":", "_min", ",", "_max", ",", "count", ",", "_sum", "=", "self", ".", "stats", ".", "get", "(", "key", ",", "(", "None", ",", "None", ",", "0", ",", ...
Set a counter value If the inner key does not exist is is created :param key: counter to update :type key: str :param value: counter value :type value: float :return: An alignak_stat brok if broks are enabled else None
[ "Set", "a", "counter", "value" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/stats.py#L467-L536
20,868
Alignak-monitoring/alignak
alignak/satellite.py
BaseSatellite.get_managed_configurations
def get_managed_configurations(self): """Get the configurations managed by this satellite The configurations managed by a satellite is a list of the configuration attached to the schedulers related to the satellites. A broker linked to several schedulers will return the list of the configuration parts of its scheduler links. :return: a dict of scheduler links with instance_id as key and hash, push_flavor and configuration identifier as values :rtype: dict """ res = {} for scheduler_link in list(self.schedulers.values()): res[scheduler_link.instance_id] = { 'hash': scheduler_link.hash, 'push_flavor': scheduler_link.push_flavor, 'managed_conf_id': scheduler_link.managed_conf_id } logger.debug("Get managed configuration: %s", res) return res
python
def get_managed_configurations(self): res = {} for scheduler_link in list(self.schedulers.values()): res[scheduler_link.instance_id] = { 'hash': scheduler_link.hash, 'push_flavor': scheduler_link.push_flavor, 'managed_conf_id': scheduler_link.managed_conf_id } logger.debug("Get managed configuration: %s", res) return res
[ "def", "get_managed_configurations", "(", "self", ")", ":", "res", "=", "{", "}", "for", "scheduler_link", "in", "list", "(", "self", ".", "schedulers", ".", "values", "(", ")", ")", ":", "res", "[", "scheduler_link", ".", "instance_id", "]", "=", "{", ...
Get the configurations managed by this satellite The configurations managed by a satellite is a list of the configuration attached to the schedulers related to the satellites. A broker linked to several schedulers will return the list of the configuration parts of its scheduler links. :return: a dict of scheduler links with instance_id as key and hash, push_flavor and configuration identifier as values :rtype: dict
[ "Get", "the", "configurations", "managed", "by", "this", "satellite" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L132-L151
20,869
Alignak-monitoring/alignak
alignak/satellite.py
BaseSatellite.get_scheduler_from_hostname
def get_scheduler_from_hostname(self, host_name): """Get scheduler linked to the given host_name :param host_name: host_name we want the scheduler from :type host_name: str :return: scheduler with id corresponding to the mapping table :rtype: dict """ scheduler_uuid = self.hosts_schedulers.get(host_name, None) return self.schedulers.get(scheduler_uuid, None)
python
def get_scheduler_from_hostname(self, host_name): scheduler_uuid = self.hosts_schedulers.get(host_name, None) return self.schedulers.get(scheduler_uuid, None)
[ "def", "get_scheduler_from_hostname", "(", "self", ",", "host_name", ")", ":", "scheduler_uuid", "=", "self", ".", "hosts_schedulers", ".", "get", "(", "host_name", ",", "None", ")", "return", "self", ".", "schedulers", ".", "get", "(", "scheduler_uuid", ",", ...
Get scheduler linked to the given host_name :param host_name: host_name we want the scheduler from :type host_name: str :return: scheduler with id corresponding to the mapping table :rtype: dict
[ "Get", "scheduler", "linked", "to", "the", "given", "host_name" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L153-L162
20,870
Alignak-monitoring/alignak
alignak/satellite.py
BaseSatellite.get_external_commands
def get_external_commands(self): """Get the external commands :return: External commands list :rtype: list """ res = self.external_commands logger.debug("Get and clear external commands list: %s", res) self.external_commands = [] return res
python
def get_external_commands(self): res = self.external_commands logger.debug("Get and clear external commands list: %s", res) self.external_commands = [] return res
[ "def", "get_external_commands", "(", "self", ")", ":", "res", "=", "self", ".", "external_commands", "logger", ".", "debug", "(", "\"Get and clear external commands list: %s\"", ",", "res", ")", "self", ".", "external_commands", "=", "[", "]", "return", "res" ]
Get the external commands :return: External commands list :rtype: list
[ "Get", "the", "external", "commands" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L164-L173
20,871
Alignak-monitoring/alignak
alignak/satellite.py
BaseSatellite.get_results_from_passive
def get_results_from_passive(self, scheduler_instance_id): """Get executed actions results from a passive satellite for a specific scheduler :param scheduler_instance_id: scheduler id :type scheduler_instance_id: int :return: Results list :rtype: list """ # Do I know this scheduler? # logger.info("My schedulers: %s %s", self.schedulers, type(self.schedulers)) if not self.schedulers: # Probably not yet configured ... logger.debug("I do not have any scheduler: %s", self.schedulers) return [] scheduler_link = None for link in list(self.schedulers.values()): if scheduler_instance_id == link.instance_id: scheduler_link = link break else: logger.warning("I do not know this scheduler: %s", scheduler_instance_id) return [] logger.debug("Get results for the scheduler: %s", scheduler_instance_id) ret, scheduler_link.wait_homerun = scheduler_link.wait_homerun, {} logger.debug("Results: %s" % (list(ret.values())) if ret else "No results available") return list(ret.values())
python
def get_results_from_passive(self, scheduler_instance_id): # Do I know this scheduler? # logger.info("My schedulers: %s %s", self.schedulers, type(self.schedulers)) if not self.schedulers: # Probably not yet configured ... logger.debug("I do not have any scheduler: %s", self.schedulers) return [] scheduler_link = None for link in list(self.schedulers.values()): if scheduler_instance_id == link.instance_id: scheduler_link = link break else: logger.warning("I do not know this scheduler: %s", scheduler_instance_id) return [] logger.debug("Get results for the scheduler: %s", scheduler_instance_id) ret, scheduler_link.wait_homerun = scheduler_link.wait_homerun, {} logger.debug("Results: %s" % (list(ret.values())) if ret else "No results available") return list(ret.values())
[ "def", "get_results_from_passive", "(", "self", ",", "scheduler_instance_id", ")", ":", "# Do I know this scheduler?", "# logger.info(\"My schedulers: %s %s\", self.schedulers, type(self.schedulers))", "if", "not", "self", ".", "schedulers", ":", "# Probably not yet configured ...", ...
Get executed actions results from a passive satellite for a specific scheduler :param scheduler_instance_id: scheduler id :type scheduler_instance_id: int :return: Results list :rtype: list
[ "Get", "executed", "actions", "results", "from", "a", "passive", "satellite", "for", "a", "specific", "scheduler" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L175-L203
20,872
Alignak-monitoring/alignak
alignak/satellite.py
BaseSatellite.get_events
def get_events(self): """Get event list from satellite :return: A copy of the events list :rtype: list """ res = copy.copy(self.events) del self.events[:] return res
python
def get_events(self): res = copy.copy(self.events) del self.events[:] return res
[ "def", "get_events", "(", "self", ")", ":", "res", "=", "copy", ".", "copy", "(", "self", ".", "events", ")", "del", "self", ".", "events", "[", ":", "]", "return", "res" ]
Get event list from satellite :return: A copy of the events list :rtype: list
[ "Get", "event", "list", "from", "satellite" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L352-L360
20,873
Alignak-monitoring/alignak
alignak/satellite.py
Satellite.manage_action_return
def manage_action_return(self, action): """Manage action return from Workers We just put them into the corresponding sched and we clean unused properties like my_scheduler :param action: the action to manage :type action: alignak.action.Action :return: None """ # Maybe our workers send us something else than an action # if so, just add this in other queues and return # todo: test a class instance if action.__class__.my_type not in ['check', 'notification', 'eventhandler']: self.add(action) return # Ok, it's a result. Get the concerned scheduler uuid scheduler_uuid = action.my_scheduler logger.debug("Got action return: %s / %s", scheduler_uuid, action.uuid) try: # Now that we know where to put the action result, we do not need any reference to # the scheduler nor the worker del action.my_scheduler del action.my_worker except AttributeError: # pragma: no cover, simple protection logger.error("AttributeError Got action return: %s / %s", scheduler_uuid, action) # And we remove it from the actions queue of the scheduler too try: del self.schedulers[scheduler_uuid].actions[action.uuid] except KeyError as exp: logger.error("KeyError del scheduler action: %s / %s - %s", scheduler_uuid, action.uuid, str(exp)) # We tag it as "return wanted", and move it in the wait return queue try: self.schedulers[scheduler_uuid].wait_homerun[action.uuid] = action except KeyError: # pragma: no cover, simple protection logger.error("KeyError Add home run action: %s / %s - %s", scheduler_uuid, action.uuid, str(exp))
python
def manage_action_return(self, action): # Maybe our workers send us something else than an action # if so, just add this in other queues and return # todo: test a class instance if action.__class__.my_type not in ['check', 'notification', 'eventhandler']: self.add(action) return # Ok, it's a result. Get the concerned scheduler uuid scheduler_uuid = action.my_scheduler logger.debug("Got action return: %s / %s", scheduler_uuid, action.uuid) try: # Now that we know where to put the action result, we do not need any reference to # the scheduler nor the worker del action.my_scheduler del action.my_worker except AttributeError: # pragma: no cover, simple protection logger.error("AttributeError Got action return: %s / %s", scheduler_uuid, action) # And we remove it from the actions queue of the scheduler too try: del self.schedulers[scheduler_uuid].actions[action.uuid] except KeyError as exp: logger.error("KeyError del scheduler action: %s / %s - %s", scheduler_uuid, action.uuid, str(exp)) # We tag it as "return wanted", and move it in the wait return queue try: self.schedulers[scheduler_uuid].wait_homerun[action.uuid] = action except KeyError: # pragma: no cover, simple protection logger.error("KeyError Add home run action: %s / %s - %s", scheduler_uuid, action.uuid, str(exp))
[ "def", "manage_action_return", "(", "self", ",", "action", ")", ":", "# Maybe our workers send us something else than an action", "# if so, just add this in other queues and return", "# todo: test a class instance", "if", "action", ".", "__class__", ".", "my_type", "not", "in", ...
Manage action return from Workers We just put them into the corresponding sched and we clean unused properties like my_scheduler :param action: the action to manage :type action: alignak.action.Action :return: None
[ "Manage", "action", "return", "from", "Workers", "We", "just", "put", "them", "into", "the", "corresponding", "sched", "and", "we", "clean", "unused", "properties", "like", "my_scheduler" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L462-L502
20,874
Alignak-monitoring/alignak
alignak/satellite.py
Satellite.create_and_launch_worker
def create_and_launch_worker(self, module_name='fork'): """Create and launch a new worker, and put it into self.workers It can be mortal or not :param module_name: the module name related to the worker default is "fork" for no module Indeed, it is actually the module 'python_name' :type module_name: str :return: None """ logger.info("Allocating new '%s' worker...", module_name) # If we are in the fork module, we do not specify a target target = None __warned = [] if module_name == 'fork': target = None else: for module in self.modules_manager.instances: # First, see if the module name matches... if module.get_name() == module_name: # ... and then if is a 'worker' module one or not if not module.properties.get('worker_capable', False): raise NotWorkerMod target = module.work if target is None: if module_name not in __warned: logger.warning("No target found for %s, NOT creating a worker for it...", module_name) __warned.append(module_name) return # We give to the Worker the instance name of the daemon (eg. poller-master) # and not the daemon type (poller) queue = Queue() worker = Worker(module_name, queue, self.returns_queue, self.processes_by_worker, max_plugins_output_length=self.max_plugins_output_length, target=target, loaded_into=self.name) # worker.module_name = module_name # save this worker self.workers[worker.get_id()] = worker # And save the Queue of this worker, with key = worker id # self.q_by_mod[module_name][worker.uuid] = queue self.q_by_mod[module_name][worker.get_id()] = queue # Ok, all is good. Start it! worker.start() logger.info("Started '%s' worker: %s (pid=%d)", module_name, worker.get_id(), worker.get_pid())
python
def create_and_launch_worker(self, module_name='fork'): logger.info("Allocating new '%s' worker...", module_name) # If we are in the fork module, we do not specify a target target = None __warned = [] if module_name == 'fork': target = None else: for module in self.modules_manager.instances: # First, see if the module name matches... if module.get_name() == module_name: # ... and then if is a 'worker' module one or not if not module.properties.get('worker_capable', False): raise NotWorkerMod target = module.work if target is None: if module_name not in __warned: logger.warning("No target found for %s, NOT creating a worker for it...", module_name) __warned.append(module_name) return # We give to the Worker the instance name of the daemon (eg. poller-master) # and not the daemon type (poller) queue = Queue() worker = Worker(module_name, queue, self.returns_queue, self.processes_by_worker, max_plugins_output_length=self.max_plugins_output_length, target=target, loaded_into=self.name) # worker.module_name = module_name # save this worker self.workers[worker.get_id()] = worker # And save the Queue of this worker, with key = worker id # self.q_by_mod[module_name][worker.uuid] = queue self.q_by_mod[module_name][worker.get_id()] = queue # Ok, all is good. Start it! worker.start() logger.info("Started '%s' worker: %s (pid=%d)", module_name, worker.get_id(), worker.get_pid())
[ "def", "create_and_launch_worker", "(", "self", ",", "module_name", "=", "'fork'", ")", ":", "logger", ".", "info", "(", "\"Allocating new '%s' worker...\"", ",", "module_name", ")", "# If we are in the fork module, we do not specify a target", "target", "=", "None", "__w...
Create and launch a new worker, and put it into self.workers It can be mortal or not :param module_name: the module name related to the worker default is "fork" for no module Indeed, it is actually the module 'python_name' :type module_name: str :return: None
[ "Create", "and", "launch", "a", "new", "worker", "and", "put", "it", "into", "self", ".", "workers", "It", "can", "be", "mortal", "or", "not" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L540-L589
20,875
Alignak-monitoring/alignak
alignak/satellite.py
Satellite.do_stop_workers
def do_stop_workers(self): """Stop all workers :return: None """ logger.info("Stopping all workers (%d)", len(self.workers)) for worker in list(self.workers.values()): try: logger.info(" - stopping '%s'", worker.get_id()) worker.terminate() worker.join(timeout=1) logger.info(" - stopped") # A already dead worker or in a worker except (AttributeError, AssertionError): pass except Exception as exp: # pylint: disable=broad-except logger.error("exception: %s", str(exp))
python
def do_stop_workers(self): logger.info("Stopping all workers (%d)", len(self.workers)) for worker in list(self.workers.values()): try: logger.info(" - stopping '%s'", worker.get_id()) worker.terminate() worker.join(timeout=1) logger.info(" - stopped") # A already dead worker or in a worker except (AttributeError, AssertionError): pass except Exception as exp: # pylint: disable=broad-except logger.error("exception: %s", str(exp))
[ "def", "do_stop_workers", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Stopping all workers (%d)\"", ",", "len", "(", "self", ".", "workers", ")", ")", "for", "worker", "in", "list", "(", "self", ".", "workers", ".", "values", "(", ")", ")", "...
Stop all workers :return: None
[ "Stop", "all", "workers" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L591-L607
20,876
Alignak-monitoring/alignak
alignak/satellite.py
Satellite.get_broks
def get_broks(self): """Get brok list from satellite :return: A copy of the broks list :rtype: list """ res = copy.copy(self.broks) del self.broks[:] return res
python
def get_broks(self): res = copy.copy(self.broks) del self.broks[:] return res
[ "def", "get_broks", "(", "self", ")", ":", "res", "=", "copy", ".", "copy", "(", "self", ".", "broks", ")", "del", "self", ".", "broks", "[", ":", "]", "return", "res" ]
Get brok list from satellite :return: A copy of the broks list :rtype: list
[ "Get", "brok", "list", "from", "satellite" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L644-L652
20,877
Alignak-monitoring/alignak
alignak/satellite.py
Satellite.check_and_del_zombie_workers
def check_and_del_zombie_workers(self): # pragma: no cover, not with unit tests... # pylint: disable= not-callable """Check if worker are fine and kill them if not. Dispatch the actions in the worker to another one TODO: see if unit tests would allow to check this code? :return: None """ # Active children make a join with everyone, useful :) # active_children() for p in active_children(): logger.debug("got child: %s", p) w_to_del = [] for worker in list(self.workers.values()): # If a worker goes down and we did not ask him, it's not # good: we can think that we have a worker and it's not True # So we del it logger.debug("checking if worker %s (pid=%d) is alive", worker.get_id(), worker.get_pid()) if not self.interrupted and not worker.is_alive(): logger.warning("The worker %s (pid=%d) went down unexpectedly!", worker.get_id(), worker.get_pid()) # Terminate immediately worker.terminate() worker.join(timeout=1) w_to_del.append(worker.get_id()) # OK, now really del workers from queues # And requeue the actions it was managed for worker_id in w_to_del: worker = self.workers[worker_id] # Del the queue of the module queue del self.q_by_mod[worker.module_name][worker.get_id()] for scheduler_uuid in self.schedulers: sched = self.schedulers[scheduler_uuid] for act in list(sched.actions.values()): if act.status == ACT_STATUS_QUEUED and act.my_worker == worker_id: # Got a check that will NEVER return if we do not restart it self.assign_to_a_queue(act) # So now we can really forgot it del self.workers[worker_id]
python
def check_and_del_zombie_workers(self): # pragma: no cover, not with unit tests... # pylint: disable= not-callable # Active children make a join with everyone, useful :) # active_children() for p in active_children(): logger.debug("got child: %s", p) w_to_del = [] for worker in list(self.workers.values()): # If a worker goes down and we did not ask him, it's not # good: we can think that we have a worker and it's not True # So we del it logger.debug("checking if worker %s (pid=%d) is alive", worker.get_id(), worker.get_pid()) if not self.interrupted and not worker.is_alive(): logger.warning("The worker %s (pid=%d) went down unexpectedly!", worker.get_id(), worker.get_pid()) # Terminate immediately worker.terminate() worker.join(timeout=1) w_to_del.append(worker.get_id()) # OK, now really del workers from queues # And requeue the actions it was managed for worker_id in w_to_del: worker = self.workers[worker_id] # Del the queue of the module queue del self.q_by_mod[worker.module_name][worker.get_id()] for scheduler_uuid in self.schedulers: sched = self.schedulers[scheduler_uuid] for act in list(sched.actions.values()): if act.status == ACT_STATUS_QUEUED and act.my_worker == worker_id: # Got a check that will NEVER return if we do not restart it self.assign_to_a_queue(act) # So now we can really forgot it del self.workers[worker_id]
[ "def", "check_and_del_zombie_workers", "(", "self", ")", ":", "# pragma: no cover, not with unit tests...", "# pylint: disable= not-callable", "# Active children make a join with everyone, useful :)", "# active_children()", "for", "p", "in", "active_children", "(", ")", ":", "logge...
Check if worker are fine and kill them if not. Dispatch the actions in the worker to another one TODO: see if unit tests would allow to check this code? :return: None
[ "Check", "if", "worker", "are", "fine", "and", "kill", "them", "if", "not", ".", "Dispatch", "the", "actions", "in", "the", "worker", "to", "another", "one" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L654-L699
20,878
Alignak-monitoring/alignak
alignak/satellite.py
Satellite.adjust_worker_number_by_load
def adjust_worker_number_by_load(self): """Try to create the minimum workers specified in the configuration :return: None """ if self.interrupted: logger.debug("Trying to adjust worker number. Ignoring because we are stopping.") return to_del = [] logger.debug("checking worker count." " Currently: %d workers, min per module : %d, max per module : %d", len(self.workers), self.min_workers, self.max_workers) # I want at least min_workers by module then if I can, I add worker for load balancing for mod in self.q_by_mod: # At least min_workers todo = max(0, self.min_workers - len(self.q_by_mod[mod])) for _ in range(todo): try: self.create_and_launch_worker(module_name=mod) # Maybe this modules is not a true worker one. # if so, just delete if from q_by_mod except NotWorkerMod: to_del.append(mod) break for mod in to_del: logger.warning("The module %s is not a worker one, I remove it from the worker list.", mod) del self.q_by_mod[mod]
python
def adjust_worker_number_by_load(self): if self.interrupted: logger.debug("Trying to adjust worker number. Ignoring because we are stopping.") return to_del = [] logger.debug("checking worker count." " Currently: %d workers, min per module : %d, max per module : %d", len(self.workers), self.min_workers, self.max_workers) # I want at least min_workers by module then if I can, I add worker for load balancing for mod in self.q_by_mod: # At least min_workers todo = max(0, self.min_workers - len(self.q_by_mod[mod])) for _ in range(todo): try: self.create_and_launch_worker(module_name=mod) # Maybe this modules is not a true worker one. # if so, just delete if from q_by_mod except NotWorkerMod: to_del.append(mod) break for mod in to_del: logger.warning("The module %s is not a worker one, I remove it from the worker list.", mod) del self.q_by_mod[mod]
[ "def", "adjust_worker_number_by_load", "(", "self", ")", ":", "if", "self", ".", "interrupted", ":", "logger", ".", "debug", "(", "\"Trying to adjust worker number. Ignoring because we are stopping.\"", ")", "return", "to_del", "=", "[", "]", "logger", ".", "debug", ...
Try to create the minimum workers specified in the configuration :return: None
[ "Try", "to", "create", "the", "minimum", "workers", "specified", "in", "the", "configuration" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L701-L731
20,879
Alignak-monitoring/alignak
alignak/satellite.py
Satellite._get_queue_for_the_action
def _get_queue_for_the_action(self, action): """Find action queue for the action depending on the module. The id is found with action modulo on action id :param a: the action that need action queue to be assigned :type action: object :return: worker id and queue. (0, None) if no queue for the module_type :rtype: tuple """ # get the module name, if not, take fork mod = getattr(action, 'module_type', 'fork') queues = list(self.q_by_mod[mod].items()) # Maybe there is no more queue, it's very bad! if not queues: return (0, None) # if not get action round robin index to get action queue based # on the action id self.rr_qid = (self.rr_qid + 1) % len(queues) (worker_id, queue) = queues[self.rr_qid] # return the id of the worker (i), and its queue return (worker_id, queue)
python
def _get_queue_for_the_action(self, action): # get the module name, if not, take fork mod = getattr(action, 'module_type', 'fork') queues = list(self.q_by_mod[mod].items()) # Maybe there is no more queue, it's very bad! if not queues: return (0, None) # if not get action round robin index to get action queue based # on the action id self.rr_qid = (self.rr_qid + 1) % len(queues) (worker_id, queue) = queues[self.rr_qid] # return the id of the worker (i), and its queue return (worker_id, queue)
[ "def", "_get_queue_for_the_action", "(", "self", ",", "action", ")", ":", "# get the module name, if not, take fork", "mod", "=", "getattr", "(", "action", ",", "'module_type'", ",", "'fork'", ")", "queues", "=", "list", "(", "self", ".", "q_by_mod", "[", "mod",...
Find action queue for the action depending on the module. The id is found with action modulo on action id :param a: the action that need action queue to be assigned :type action: object :return: worker id and queue. (0, None) if no queue for the module_type :rtype: tuple
[ "Find", "action", "queue", "for", "the", "action", "depending", "on", "the", "module", ".", "The", "id", "is", "found", "with", "action", "modulo", "on", "action", "id" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L734-L757
20,880
Alignak-monitoring/alignak
alignak/satellite.py
Satellite.add_actions
def add_actions(self, actions_list, scheduler_instance_id): """Add a list of actions to the satellite queues :param actions_list: Actions list to add :type actions_list: list :param scheduler_instance_id: sheduler link to assign the actions to :type scheduler_instance_id: SchedulerLink :return: None """ # We check for new check in each schedulers and put the result in new_checks scheduler_link = None for scheduler_id in self.schedulers: logger.debug("Trying to add an action, scheduler: %s", self.schedulers[scheduler_id]) if scheduler_instance_id == self.schedulers[scheduler_id].instance_id: scheduler_link = self.schedulers[scheduler_id] break else: logger.error("Trying to add actions from an unknwown scheduler: %s", scheduler_instance_id) return if not scheduler_link: logger.error("Trying to add actions, but scheduler link is not found for: %s, " "actions: %s", scheduler_instance_id, actions_list) return logger.debug("Found scheduler link: %s", scheduler_link) for action in actions_list: # First we look if the action is identified uuid = getattr(action, 'uuid', None) if uuid is None: try: action = unserialize(action, no_load=True) uuid = action.uuid except AlignakClassLookupException: logger.error('Cannot un-serialize action: %s', action) continue # If we already have this action, we are already working for it! if uuid in scheduler_link.actions: continue # Action is attached to a scheduler action.my_scheduler = scheduler_link.uuid scheduler_link.actions[action.uuid] = action self.assign_to_a_queue(action)
python
def add_actions(self, actions_list, scheduler_instance_id): # We check for new check in each schedulers and put the result in new_checks scheduler_link = None for scheduler_id in self.schedulers: logger.debug("Trying to add an action, scheduler: %s", self.schedulers[scheduler_id]) if scheduler_instance_id == self.schedulers[scheduler_id].instance_id: scheduler_link = self.schedulers[scheduler_id] break else: logger.error("Trying to add actions from an unknwown scheduler: %s", scheduler_instance_id) return if not scheduler_link: logger.error("Trying to add actions, but scheduler link is not found for: %s, " "actions: %s", scheduler_instance_id, actions_list) return logger.debug("Found scheduler link: %s", scheduler_link) for action in actions_list: # First we look if the action is identified uuid = getattr(action, 'uuid', None) if uuid is None: try: action = unserialize(action, no_load=True) uuid = action.uuid except AlignakClassLookupException: logger.error('Cannot un-serialize action: %s', action) continue # If we already have this action, we are already working for it! if uuid in scheduler_link.actions: continue # Action is attached to a scheduler action.my_scheduler = scheduler_link.uuid scheduler_link.actions[action.uuid] = action self.assign_to_a_queue(action)
[ "def", "add_actions", "(", "self", ",", "actions_list", ",", "scheduler_instance_id", ")", ":", "# We check for new check in each schedulers and put the result in new_checks", "scheduler_link", "=", "None", "for", "scheduler_id", "in", "self", ".", "schedulers", ":", "logge...
Add a list of actions to the satellite queues :param actions_list: Actions list to add :type actions_list: list :param scheduler_instance_id: sheduler link to assign the actions to :type scheduler_instance_id: SchedulerLink :return: None
[ "Add", "a", "list", "of", "actions", "to", "the", "satellite", "queues" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L759-L802
20,881
Alignak-monitoring/alignak
alignak/satellite.py
Satellite.assign_to_a_queue
def assign_to_a_queue(self, action): """Take an action and put it to a worker actions queue :param action: action to put :type action: alignak.action.Action :return: None """ (worker_id, queue) = self._get_queue_for_the_action(action) if not worker_id: return # Tag the action as "in the worker i" action.my_worker = worker_id action.status = ACT_STATUS_QUEUED msg = Message(_type='Do', data=action, source=self.name) logger.debug("Queuing message: %s", msg) queue.put_nowait(msg) logger.debug("Queued")
python
def assign_to_a_queue(self, action): (worker_id, queue) = self._get_queue_for_the_action(action) if not worker_id: return # Tag the action as "in the worker i" action.my_worker = worker_id action.status = ACT_STATUS_QUEUED msg = Message(_type='Do', data=action, source=self.name) logger.debug("Queuing message: %s", msg) queue.put_nowait(msg) logger.debug("Queued")
[ "def", "assign_to_a_queue", "(", "self", ",", "action", ")", ":", "(", "worker_id", ",", "queue", ")", "=", "self", ".", "_get_queue_for_the_action", "(", "action", ")", "if", "not", "worker_id", ":", "return", "# Tag the action as \"in the worker i\"", "action", ...
Take an action and put it to a worker actions queue :param action: action to put :type action: alignak.action.Action :return: None
[ "Take", "an", "action", "and", "put", "it", "to", "a", "worker", "actions", "queue" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L804-L822
20,882
Alignak-monitoring/alignak
alignak/satellite.py
Satellite.get_new_actions
def get_new_actions(self): """ Wrapper function for do_get_new_actions For stats purpose :return: None TODO: Use a decorator for timing this function """ try: _t0 = time.time() self.do_get_new_actions() statsmgr.timer('actions.got.time', time.time() - _t0) except RuntimeError: logger.error("Exception like issue #1007")
python
def get_new_actions(self): try: _t0 = time.time() self.do_get_new_actions() statsmgr.timer('actions.got.time', time.time() - _t0) except RuntimeError: logger.error("Exception like issue #1007")
[ "def", "get_new_actions", "(", "self", ")", ":", "try", ":", "_t0", "=", "time", ".", "time", "(", ")", "self", ".", "do_get_new_actions", "(", ")", "statsmgr", ".", "timer", "(", "'actions.got.time'", ",", "time", ".", "time", "(", ")", "-", "_t0", ...
Wrapper function for do_get_new_actions For stats purpose :return: None TODO: Use a decorator for timing this function
[ "Wrapper", "function", "for", "do_get_new_actions", "For", "stats", "purpose" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L824-L836
20,883
Alignak-monitoring/alignak
alignak/satellite.py
Satellite.main
def main(self): """Main satellite function. Do init and then mainloop :return: None """ try: # Start the daemon mode if not self.do_daemon_init_and_start(): self.exit_on_error(message="Daemon initialization error", exit_code=3) self.do_post_daemon_init() # We wait for initial conf self.wait_for_initial_conf() if self.new_conf: # Setup the received configuration self.setup_new_conf() # Allocate Mortal Threads self.adjust_worker_number_by_load() # Now main loop self.do_main_loop() logger.info("Exited from the main loop.") self.request_stop() except Exception: # pragma: no cover, this should never happen indeed ;) self.exit_on_exception(traceback.format_exc()) raise
python
def main(self): try: # Start the daemon mode if not self.do_daemon_init_and_start(): self.exit_on_error(message="Daemon initialization error", exit_code=3) self.do_post_daemon_init() # We wait for initial conf self.wait_for_initial_conf() if self.new_conf: # Setup the received configuration self.setup_new_conf() # Allocate Mortal Threads self.adjust_worker_number_by_load() # Now main loop self.do_main_loop() logger.info("Exited from the main loop.") self.request_stop() except Exception: # pragma: no cover, this should never happen indeed ;) self.exit_on_exception(traceback.format_exc()) raise
[ "def", "main", "(", "self", ")", ":", "try", ":", "# Start the daemon mode", "if", "not", "self", ".", "do_daemon_init_and_start", "(", ")", ":", "self", ".", "exit_on_error", "(", "message", "=", "\"Daemon initialization error\"", ",", "exit_code", "=", "3", ...
Main satellite function. Do init and then mainloop :return: None
[ "Main", "satellite", "function", ".", "Do", "init", "and", "then", "mainloop" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L1108-L1136
20,884
Alignak-monitoring/alignak
alignak/contactdowntime.py
ContactDowntime.check_activation
def check_activation(self, contacts): """Enter or exit downtime if necessary :return: None """ now = time.time() was_is_in_effect = self.is_in_effect self.is_in_effect = (self.start_time <= now <= self.end_time) # Raise a log entry when we get in the downtime if not was_is_in_effect and self.is_in_effect: self.enter(contacts) # Same for exit purpose if was_is_in_effect and not self.is_in_effect: self.exit(contacts)
python
def check_activation(self, contacts): now = time.time() was_is_in_effect = self.is_in_effect self.is_in_effect = (self.start_time <= now <= self.end_time) # Raise a log entry when we get in the downtime if not was_is_in_effect and self.is_in_effect: self.enter(contacts) # Same for exit purpose if was_is_in_effect and not self.is_in_effect: self.exit(contacts)
[ "def", "check_activation", "(", "self", ",", "contacts", ")", ":", "now", "=", "time", ".", "time", "(", ")", "was_is_in_effect", "=", "self", ".", "is_in_effect", "self", ".", "is_in_effect", "=", "(", "self", ".", "start_time", "<=", "now", "<=", "self...
Enter or exit downtime if necessary :return: None
[ "Enter", "or", "exit", "downtime", "if", "necessary" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/contactdowntime.py#L90-L105
20,885
Alignak-monitoring/alignak
alignak/util.py
split_semicolon
def split_semicolon(line, maxsplit=None): r"""Split a line on semicolons characters but not on the escaped semicolons :param line: line to split :type line: str :param maxsplit: maximal number of split (if None, no limit) :type maxsplit: None | int :return: split line :rtype: list >>> split_semicolon('a,b;c;;g') ['a,b', 'c', '', 'g'] >>> split_semicolon('a,b;c;;g', 2) ['a,b', 'c', ';g'] >>> split_semicolon(r'a,b;c\;;g', 2) ['a,b', 'c;', 'g'] """ # Split on ';' character split_line = line.split(';') split_line_size = len(split_line) # if maxsplit is not specified, we set it to the number of part if maxsplit is None or maxsplit < 0: maxsplit = split_line_size # Join parts to the next one, if ends with a '\' # because we mustn't split if the semicolon is escaped i = 0 while i < split_line_size - 1: # for each part, check if its ends with a '\' ends = split_line[i].endswith('\\') if ends: # remove the last character '\' split_line[i] = split_line[i][:-1] # append the next part to the current if it is not the last and the current # ends with '\' or if there is more than maxsplit parts if (ends or i >= maxsplit) and i < split_line_size - 1: split_line[i] = ";".join([split_line[i], split_line[i + 1]]) # delete the next part del split_line[i + 1] split_line_size -= 1 # increase i only if we don't have append because after append the new # string can end with '\' else: i += 1 return split_line
python
def split_semicolon(line, maxsplit=None): r"""Split a line on semicolons characters but not on the escaped semicolons :param line: line to split :type line: str :param maxsplit: maximal number of split (if None, no limit) :type maxsplit: None | int :return: split line :rtype: list >>> split_semicolon('a,b;c;;g') ['a,b', 'c', '', 'g'] >>> split_semicolon('a,b;c;;g', 2) ['a,b', 'c', ';g'] >>> split_semicolon(r'a,b;c\;;g', 2) ['a,b', 'c;', 'g'] """ # Split on ';' character split_line = line.split(';') split_line_size = len(split_line) # if maxsplit is not specified, we set it to the number of part if maxsplit is None or maxsplit < 0: maxsplit = split_line_size # Join parts to the next one, if ends with a '\' # because we mustn't split if the semicolon is escaped i = 0 while i < split_line_size - 1: # for each part, check if its ends with a '\' ends = split_line[i].endswith('\\') if ends: # remove the last character '\' split_line[i] = split_line[i][:-1] # append the next part to the current if it is not the last and the current # ends with '\' or if there is more than maxsplit parts if (ends or i >= maxsplit) and i < split_line_size - 1: split_line[i] = ";".join([split_line[i], split_line[i + 1]]) # delete the next part del split_line[i + 1] split_line_size -= 1 # increase i only if we don't have append because after append the new # string can end with '\' else: i += 1 return split_line
[ "def", "split_semicolon", "(", "line", ",", "maxsplit", "=", "None", ")", ":", "# Split on ';' character", "split_line", "=", "line", ".", "split", "(", "';'", ")", "split_line_size", "=", "len", "(", "split_line", ")", "# if maxsplit is not specified, we set it to ...
r"""Split a line on semicolons characters but not on the escaped semicolons :param line: line to split :type line: str :param maxsplit: maximal number of split (if None, no limit) :type maxsplit: None | int :return: split line :rtype: list >>> split_semicolon('a,b;c;;g') ['a,b', 'c', '', 'g'] >>> split_semicolon('a,b;c;;g', 2) ['a,b', 'c', ';g'] >>> split_semicolon(r'a,b;c\;;g', 2) ['a,b', 'c;', 'g']
[ "r", "Split", "a", "line", "on", "semicolons", "characters", "but", "not", "on", "the", "escaped", "semicolons" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L110-L165
20,886
Alignak-monitoring/alignak
alignak/util.py
format_t_into_dhms_format
def format_t_into_dhms_format(timestamp): """ Convert an amount of second into day, hour, min and sec :param timestamp: seconds :type timestamp: int :return: 'Ad Bh Cm Ds' :rtype: str >>> format_t_into_dhms_format(456189) '5d 6h 43m 9s' >>> format_t_into_dhms_format(3600) '0d 1h 0m 0s' """ mins, timestamp = divmod(timestamp, 60) hour, mins = divmod(mins, 60) day, hour = divmod(hour, 24) return '%sd %sh %sm %ss' % (day, hour, mins, timestamp)
python
def format_t_into_dhms_format(timestamp): mins, timestamp = divmod(timestamp, 60) hour, mins = divmod(mins, 60) day, hour = divmod(hour, 24) return '%sd %sh %sm %ss' % (day, hour, mins, timestamp)
[ "def", "format_t_into_dhms_format", "(", "timestamp", ")", ":", "mins", ",", "timestamp", "=", "divmod", "(", "timestamp", ",", "60", ")", "hour", ",", "mins", "=", "divmod", "(", "mins", ",", "60", ")", "day", ",", "hour", "=", "divmod", "(", "hour", ...
Convert an amount of second into day, hour, min and sec :param timestamp: seconds :type timestamp: int :return: 'Ad Bh Cm Ds' :rtype: str >>> format_t_into_dhms_format(456189) '5d 6h 43m 9s' >>> format_t_into_dhms_format(3600) '0d 1h 0m 0s'
[ "Convert", "an", "amount", "of", "second", "into", "day", "hour", "min", "and", "sec" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L230-L248
20,887
Alignak-monitoring/alignak
alignak/util.py
merge_periods
def merge_periods(data): """ Merge periods to have better continous periods. Like 350-450, 400-600 => 350-600 :param data: list of periods :type data: list :return: better continous periods :rtype: list """ # sort by start date newdata = sorted(data, key=lambda drange: drange[0]) end = 0 for period in newdata: if period[0] != end and period[0] != (end - 1): end = period[1] # dat = np.array(newdata) dat = newdata new_intervals = [] cur_start = None cur_end = None for (dt_start, dt_end) in dat: if cur_end is None: cur_start = dt_start cur_end = dt_end continue else: if cur_end >= dt_start: # merge, keep existing cur_start, extend cur_end cur_end = dt_end else: # new interval, save previous and reset current to this new_intervals.append((cur_start, cur_end)) cur_start = dt_start cur_end = dt_end # make sure final interval is saved new_intervals.append((cur_start, cur_end)) return new_intervals
python
def merge_periods(data): # sort by start date newdata = sorted(data, key=lambda drange: drange[0]) end = 0 for period in newdata: if period[0] != end and period[0] != (end - 1): end = period[1] # dat = np.array(newdata) dat = newdata new_intervals = [] cur_start = None cur_end = None for (dt_start, dt_end) in dat: if cur_end is None: cur_start = dt_start cur_end = dt_end continue else: if cur_end >= dt_start: # merge, keep existing cur_start, extend cur_end cur_end = dt_end else: # new interval, save previous and reset current to this new_intervals.append((cur_start, cur_end)) cur_start = dt_start cur_end = dt_end # make sure final interval is saved new_intervals.append((cur_start, cur_end)) return new_intervals
[ "def", "merge_periods", "(", "data", ")", ":", "# sort by start date", "newdata", "=", "sorted", "(", "data", ",", "key", "=", "lambda", "drange", ":", "drange", "[", "0", "]", ")", "end", "=", "0", "for", "period", "in", "newdata", ":", "if", "period"...
Merge periods to have better continous periods. Like 350-450, 400-600 => 350-600 :param data: list of periods :type data: list :return: better continous periods :rtype: list
[ "Merge", "periods", "to", "have", "better", "continous", "periods", ".", "Like", "350", "-", "450", "400", "-", "600", "=", ">", "350", "-", "600" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L251-L289
20,888
Alignak-monitoring/alignak
alignak/util.py
list_split
def list_split(val, split_on_comma=True): """Try to split each member of a list with comma separator. If we don't have to split just return val :param val: value to split :type val: :param split_on_comma: :type split_on_comma: bool :return: list with members split on comma :rtype: list >>> list_split(['a,b,c'], False) ['a,b,c'] >>> list_split(['a,b,c']) ['a', 'b', 'c'] >>> list_split('') [] """ if not split_on_comma: return val new_val = [] for subval in val: # This may happen when re-serializing if isinstance(subval, list): continue new_val.extend(subval.split(',')) return new_val
python
def list_split(val, split_on_comma=True): if not split_on_comma: return val new_val = [] for subval in val: # This may happen when re-serializing if isinstance(subval, list): continue new_val.extend(subval.split(',')) return new_val
[ "def", "list_split", "(", "val", ",", "split_on_comma", "=", "True", ")", ":", "if", "not", "split_on_comma", ":", "return", "val", "new_val", "=", "[", "]", "for", "subval", "in", "val", ":", "# This may happen when re-serializing", "if", "isinstance", "(", ...
Try to split each member of a list with comma separator. If we don't have to split just return val :param val: value to split :type val: :param split_on_comma: :type split_on_comma: bool :return: list with members split on comma :rtype: list >>> list_split(['a,b,c'], False) ['a,b,c'] >>> list_split(['a,b,c']) ['a', 'b', 'c'] >>> list_split('') []
[ "Try", "to", "split", "each", "member", "of", "a", "list", "with", "comma", "separator", ".", "If", "we", "don", "t", "have", "to", "split", "just", "return", "val" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L364-L393
20,889
Alignak-monitoring/alignak
alignak/util.py
to_best_int_float
def to_best_int_float(val): """Get best type for value between int and float :param val: value :type val: :return: int(float(val)) if int(float(val)) == float(val), else float(val) :rtype: int | float >>> to_best_int_float("20.1") 20.1 >>> to_best_int_float("20.0") 20 >>> to_best_int_float("20") 20 """ integer = int(float(val)) flt = float(val) # If the f is a .0 value, # best match is int if integer == flt: return integer return flt
python
def to_best_int_float(val): integer = int(float(val)) flt = float(val) # If the f is a .0 value, # best match is int if integer == flt: return integer return flt
[ "def", "to_best_int_float", "(", "val", ")", ":", "integer", "=", "int", "(", "float", "(", "val", ")", ")", "flt", "=", "float", "(", "val", ")", "# If the f is a .0 value,", "# best match is int", "if", "integer", "==", "flt", ":", "return", "integer", "...
Get best type for value between int and float :param val: value :type val: :return: int(float(val)) if int(float(val)) == float(val), else float(val) :rtype: int | float >>> to_best_int_float("20.1") 20.1 >>> to_best_int_float("20.0") 20 >>> to_best_int_float("20") 20
[ "Get", "best", "type", "for", "value", "between", "int", "and", "float" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L396-L419
20,890
Alignak-monitoring/alignak
alignak/util.py
dict_to_serialized_dict
def dict_to_serialized_dict(ref, the_dict): """Serialize the list of elements to a dictionary Used for the retention store :param ref: Not used :type ref: :param the_dict: dictionary to convert :type the_dict: dict :return: dict of serialized :rtype: dict """ result = {} for elt in list(the_dict.values()): if not getattr(elt, 'serialize', None): continue result[elt.uuid] = elt.serialize() return result
python
def dict_to_serialized_dict(ref, the_dict): result = {} for elt in list(the_dict.values()): if not getattr(elt, 'serialize', None): continue result[elt.uuid] = elt.serialize() return result
[ "def", "dict_to_serialized_dict", "(", "ref", ",", "the_dict", ")", ":", "result", "=", "{", "}", "for", "elt", "in", "list", "(", "the_dict", ".", "values", "(", ")", ")", ":", "if", "not", "getattr", "(", "elt", ",", "'serialize'", ",", "None", ")"...
Serialize the list of elements to a dictionary Used for the retention store :param ref: Not used :type ref: :param the_dict: dictionary to convert :type the_dict: dict :return: dict of serialized :rtype: dict
[ "Serialize", "the", "list", "of", "elements", "to", "a", "dictionary" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L587-L604
20,891
Alignak-monitoring/alignak
alignak/util.py
list_to_serialized
def list_to_serialized(ref, the_list): """Serialize the list of elements Used for the retention store :param ref: Not used :type ref: :param the_list: dictionary to convert :type the_list: dict :return: dict of serialized :rtype: dict """ result = [] for elt in the_list: if not getattr(elt, 'serialize', None): continue result.append(elt.serialize()) return result
python
def list_to_serialized(ref, the_list): result = [] for elt in the_list: if not getattr(elt, 'serialize', None): continue result.append(elt.serialize()) return result
[ "def", "list_to_serialized", "(", "ref", ",", "the_list", ")", ":", "result", "=", "[", "]", "for", "elt", "in", "the_list", ":", "if", "not", "getattr", "(", "elt", ",", "'serialize'", ",", "None", ")", ":", "continue", "result", ".", "append", "(", ...
Serialize the list of elements Used for the retention store :param ref: Not used :type ref: :param the_list: dictionary to convert :type the_list: dict :return: dict of serialized :rtype: dict
[ "Serialize", "the", "list", "of", "elements" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L607-L624
20,892
Alignak-monitoring/alignak
alignak/util.py
to_hostnames_list
def to_hostnames_list(ref, tab): # pragma: no cover, to be deprecated? """Convert Host list into a list of host_name :param ref: Not used :type ref: :param tab: Host list :type tab: list[alignak.objects.host.Host] :return: host_name list :rtype: list """ res = [] for host in tab: if hasattr(host, 'host_name'): res.append(host.host_name) return res
python
def to_hostnames_list(ref, tab): # pragma: no cover, to be deprecated? res = [] for host in tab: if hasattr(host, 'host_name'): res.append(host.host_name) return res
[ "def", "to_hostnames_list", "(", "ref", ",", "tab", ")", ":", "# pragma: no cover, to be deprecated?", "res", "=", "[", "]", "for", "host", "in", "tab", ":", "if", "hasattr", "(", "host", ",", "'host_name'", ")", ":", "res", ".", "append", "(", "host", "...
Convert Host list into a list of host_name :param ref: Not used :type ref: :param tab: Host list :type tab: list[alignak.objects.host.Host] :return: host_name list :rtype: list
[ "Convert", "Host", "list", "into", "a", "list", "of", "host_name" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L642-L656
20,893
Alignak-monitoring/alignak
alignak/util.py
sort_by_number_values
def sort_by_number_values(x00, y00): # pragma: no cover, looks like not used! """Compare x00, y00 base on number of values :param x00: first elem to compare :type x00: list :param y00: second elem to compare :type y00: list :return: x00 > y00 (-1) if len(x00) > len(y00), x00 == y00 (0) if id equals, x00 < y00 (1) else :rtype: int """ if len(x00) < len(y00): return 1 if len(x00) > len(y00): return -1 # So is equal return 0
python
def sort_by_number_values(x00, y00): # pragma: no cover, looks like not used! if len(x00) < len(y00): return 1 if len(x00) > len(y00): return -1 # So is equal return 0
[ "def", "sort_by_number_values", "(", "x00", ",", "y00", ")", ":", "# pragma: no cover, looks like not used!", "if", "len", "(", "x00", ")", "<", "len", "(", "y00", ")", ":", "return", "1", "if", "len", "(", "x00", ")", ">", "len", "(", "y00", ")", ":",...
Compare x00, y00 base on number of values :param x00: first elem to compare :type x00: list :param y00: second elem to compare :type y00: list :return: x00 > y00 (-1) if len(x00) > len(y00), x00 == y00 (0) if id equals, x00 < y00 (1) else :rtype: int
[ "Compare", "x00", "y00", "base", "on", "number", "of", "values" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L738-L753
20,894
Alignak-monitoring/alignak
alignak/util.py
strip_and_uniq
def strip_and_uniq(tab): """Strip every element of a list and keep a list of ordered unique values :param tab: list to strip :type tab: list :return: stripped list with unique values :rtype: list """ _list = [] for elt in tab: val = elt.strip() if val and val not in _list: _list.append(val) return _list
python
def strip_and_uniq(tab): _list = [] for elt in tab: val = elt.strip() if val and val not in _list: _list.append(val) return _list
[ "def", "strip_and_uniq", "(", "tab", ")", ":", "_list", "=", "[", "]", "for", "elt", "in", "tab", ":", "val", "=", "elt", ".", "strip", "(", ")", "if", "val", "and", "val", "not", "in", "_list", ":", "_list", ".", "append", "(", "val", ")", "re...
Strip every element of a list and keep a list of ordered unique values :param tab: list to strip :type tab: list :return: stripped list with unique values :rtype: list
[ "Strip", "every", "element", "of", "a", "list", "and", "keep", "a", "list", "of", "ordered", "unique", "values" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L777-L790
20,895
Alignak-monitoring/alignak
alignak/util.py
filter_host_by_name
def filter_host_by_name(name): """Filter for host Filter on name :param name: name to filter :type name: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for host. Accept if host_name == name""" host = items["host"] if host is None: return False return host.host_name == name return inner_filter
python
def filter_host_by_name(name): def inner_filter(items): """Inner filter for host. Accept if host_name == name""" host = items["host"] if host is None: return False return host.host_name == name return inner_filter
[ "def", "filter_host_by_name", "(", "name", ")", ":", "def", "inner_filter", "(", "items", ")", ":", "\"\"\"Inner filter for host. Accept if host_name == name\"\"\"", "host", "=", "items", "[", "\"host\"", "]", "if", "host", "is", "None", ":", "return", "False", "r...
Filter for host Filter on name :param name: name to filter :type name: str :return: Filter :rtype: bool
[ "Filter", "for", "host", "Filter", "on", "name" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L938-L955
20,896
Alignak-monitoring/alignak
alignak/util.py
filter_host_by_regex
def filter_host_by_regex(regex): """Filter for host Filter on regex :param regex: regex to filter :type regex: str :return: Filter :rtype: bool """ host_re = re.compile(regex) def inner_filter(items): """Inner filter for host. Accept if regex match host_name""" host = items["host"] if host is None: return False return host_re.match(host.host_name) is not None return inner_filter
python
def filter_host_by_regex(regex): host_re = re.compile(regex) def inner_filter(items): """Inner filter for host. Accept if regex match host_name""" host = items["host"] if host is None: return False return host_re.match(host.host_name) is not None return inner_filter
[ "def", "filter_host_by_regex", "(", "regex", ")", ":", "host_re", "=", "re", ".", "compile", "(", "regex", ")", "def", "inner_filter", "(", "items", ")", ":", "\"\"\"Inner filter for host. Accept if regex match host_name\"\"\"", "host", "=", "items", "[", "\"host\""...
Filter for host Filter on regex :param regex: regex to filter :type regex: str :return: Filter :rtype: bool
[ "Filter", "for", "host", "Filter", "on", "regex" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L958-L976
20,897
Alignak-monitoring/alignak
alignak/util.py
filter_host_by_group
def filter_host_by_group(group): """Filter for host Filter on group :param group: group name to filter :type group: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for host. Accept if group in host.hostgroups""" host = items["host"] if host is None: return False return group in [items["hostgroups"][g].hostgroup_name for g in host.hostgroups] return inner_filter
python
def filter_host_by_group(group): def inner_filter(items): """Inner filter for host. Accept if group in host.hostgroups""" host = items["host"] if host is None: return False return group in [items["hostgroups"][g].hostgroup_name for g in host.hostgroups] return inner_filter
[ "def", "filter_host_by_group", "(", "group", ")", ":", "def", "inner_filter", "(", "items", ")", ":", "\"\"\"Inner filter for host. Accept if group in host.hostgroups\"\"\"", "host", "=", "items", "[", "\"host\"", "]", "if", "host", "is", "None", ":", "return", "Fal...
Filter for host Filter on group :param group: group name to filter :type group: str :return: Filter :rtype: bool
[ "Filter", "for", "host", "Filter", "on", "group" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L979-L996
20,898
Alignak-monitoring/alignak
alignak/util.py
filter_host_by_tag
def filter_host_by_tag(tpl): """Filter for host Filter on tag :param tpl: tag to filter :type tpl: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for host. Accept if tag in host.tags""" host = items["host"] if host is None: return False return tpl in [t.strip() for t in host.tags] return inner_filter
python
def filter_host_by_tag(tpl): def inner_filter(items): """Inner filter for host. Accept if tag in host.tags""" host = items["host"] if host is None: return False return tpl in [t.strip() for t in host.tags] return inner_filter
[ "def", "filter_host_by_tag", "(", "tpl", ")", ":", "def", "inner_filter", "(", "items", ")", ":", "\"\"\"Inner filter for host. Accept if tag in host.tags\"\"\"", "host", "=", "items", "[", "\"host\"", "]", "if", "host", "is", "None", ":", "return", "False", "retu...
Filter for host Filter on tag :param tpl: tag to filter :type tpl: str :return: Filter :rtype: bool
[ "Filter", "for", "host", "Filter", "on", "tag" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L999-L1016
20,899
Alignak-monitoring/alignak
alignak/util.py
filter_service_by_name
def filter_service_by_name(name): """Filter for service Filter on name :param name: name to filter :type name: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for service. Accept if service_description == name""" service = items["service"] if service is None: return False return service.service_description == name return inner_filter
python
def filter_service_by_name(name): def inner_filter(items): """Inner filter for service. Accept if service_description == name""" service = items["service"] if service is None: return False return service.service_description == name return inner_filter
[ "def", "filter_service_by_name", "(", "name", ")", ":", "def", "inner_filter", "(", "items", ")", ":", "\"\"\"Inner filter for service. Accept if service_description == name\"\"\"", "service", "=", "items", "[", "\"service\"", "]", "if", "service", "is", "None", ":", ...
Filter for service Filter on name :param name: name to filter :type name: str :return: Filter :rtype: bool
[ "Filter", "for", "service", "Filter", "on", "name" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L1019-L1036