sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def construct_request_uri(local_dir, base_path, **kwargs): """ Constructs a special redirect_uri to be used when communicating with one OP. Each OP should get their own redirect_uris. :param local_dir: Local directory in which to place the file :param base_path: Base URL to start with :param kwargs: :return: 2-tuple with (filename, url) """ _filedir = local_dir if not os.path.isdir(_filedir): os.makedirs(_filedir) _webpath = base_path _name = rndstr(10) + ".jwt" filename = os.path.join(_filedir, _name) while os.path.exists(filename): _name = rndstr(10) filename = os.path.join(_filedir, _name) _webname = "%s%s" % (_webpath, _name) return filename, _webname
Constructs a special redirect_uri to be used when communicating with one OP. Each OP should get their own redirect_uris. :param local_dir: Local directory in which to place the file :param base_path: Base URL to start with :param kwargs: :return: 2-tuple with (filename, url)
entailment
def init_services(service_definitions, service_context, state_db, client_authn_factory=None): """ Initiates a set of services :param service_definitions: A dictionary cotaining service definitions :param service_context: A reference to the service context, this is the same for all service instances. :param state_db: A reference to the state database. Shared by all the services. :param client_authn_factory: A list of methods the services can use to authenticate the client to a service. :return: A dictionary, with service name as key and the service instance as value. """ service = {} for service_name, service_configuration in service_definitions.items(): try: kwargs = service_configuration['kwargs'] except KeyError: kwargs = {} kwargs.update({'service_context': service_context, 'state_db': state_db, 'client_authn_factory': client_authn_factory}) if isinstance(service_configuration['class'], str): _srv = util.importer(service_configuration['class'])(**kwargs) else: _srv = service_configuration['class'](**kwargs) try: service[_srv.service_name] = _srv except AttributeError: raise ValueError("Could not load '{}'".format(service_name)) return service
Initiates a set of services :param service_definitions: A dictionary cotaining service definitions :param service_context: A reference to the service context, this is the same for all service instances. :param state_db: A reference to the state database. Shared by all the services. :param client_authn_factory: A list of methods the services can use to authenticate the client to a service. :return: A dictionary, with service name as key and the service instance as value.
entailment
def gather_request_args(self, **kwargs): """ Go through the attributes that the message class can contain and add values if they are missing but exists in the client info or when there are default values. :param kwargs: Initial set of attributes. :return: Possibly augmented set of attributes """ ar_args = kwargs.copy() # Go through the list of claims defined for the message class # there are a couple of places where informtation can be found # access them in the order of priority # 1. A keyword argument # 2. configured set of default attribute values # 3. default attribute values defined in the OIDC standard document for prop in self.msg_type.c_param.keys(): if prop in ar_args: continue else: try: ar_args[prop] = getattr(self.service_context, prop) except AttributeError: try: ar_args[prop] = self.conf['request_args'][prop] except KeyError: try: ar_args[prop] = self.service_context.register_args[ prop] except KeyError: try: ar_args[prop] = self.default_request_args[prop] except KeyError: pass return ar_args
Go through the attributes that the message class can contain and add values if they are missing but exists in the client info or when there are default values. :param kwargs: Initial set of attributes. :return: Possibly augmented set of attributes
entailment
def method_args(self, context, **kwargs): """ Collect the set of arguments that should be used by a set of methods :param context: Which service we're working for :param kwargs: A set of keyword arguments that are added at run-time. :return: A set of keyword arguments """ try: _args = self.conf[context].copy() except KeyError: _args = kwargs else: _args.update(kwargs) return _args
Collect the set of arguments that should be used by a set of methods :param context: Which service we're working for :param kwargs: A set of keyword arguments that are added at run-time. :return: A set of keyword arguments
entailment
def do_pre_construct(self, request_args, **kwargs): """ Will run the pre_construct methods one by one in the order given. :param request_args: Request arguments :param kwargs: Extra key word arguments :return: A tuple of request_args and post_args. post_args are to be used by the post_construct methods. """ _args = self.method_args('pre_construct', **kwargs) post_args = {} for meth in self.pre_construct: request_args, _post_args = meth(request_args, service=self, **_args) post_args.update(_post_args) return request_args, post_args
Will run the pre_construct methods one by one in the order given. :param request_args: Request arguments :param kwargs: Extra key word arguments :return: A tuple of request_args and post_args. post_args are to be used by the post_construct methods.
entailment
def do_post_construct(self, request_args, **kwargs): """ Will run the post_construct methods one at the time in order. :param request_args: Request arguments :param kwargs: Arguments used by the post_construct method :return: Possible modified set of request arguments. """ _args = self.method_args('post_construct', **kwargs) for meth in self.post_construct: request_args = meth(request_args, service=self, **_args) return request_args
Will run the post_construct methods one at the time in order. :param request_args: Request arguments :param kwargs: Arguments used by the post_construct method :return: Possible modified set of request arguments.
entailment
def construct(self, request_args=None, **kwargs): """ Instantiate the request as a message class instance with attribute values gathered in a pre_construct method or in the gather_request_args method. :param request_args: :param kwargs: extra keyword arguments :return: message class instance """ if request_args is None: request_args = {} # run the pre_construct methods. Will return a possibly new # set of request arguments but also a set of arguments to # be used by the post_construct methods. request_args, post_args = self.do_pre_construct(request_args, **kwargs) # If 'state' appears among the keyword argument and is not # expected to appear in the request, remove it. if 'state' in self.msg_type.c_param and 'state' in kwargs: # Don't overwrite something put there by the constructor if 'state' not in request_args: request_args['state'] = kwargs['state'] # logger.debug("request_args: %s" % sanitize(request_args)) _args = self.gather_request_args(**request_args) # logger.debug("kwargs: %s" % sanitize(kwargs)) # initiate the request as in an instance of the self.msg_type # message type request = self.msg_type(**_args) return self.do_post_construct(request, **post_args)
Instantiate the request as a message class instance with attribute values gathered in a pre_construct method or in the gather_request_args method. :param request_args: :param kwargs: extra keyword arguments :return: message class instance
entailment
def init_authentication_method(self, request, authn_method, http_args=None, **kwargs): """ Will run the proper client authentication method. Each such method will place the necessary information in the necessary place. A method may modify the request. :param request: The request, a Message class instance :param authn_method: Client authentication method :param http_args: HTTP header arguments :param kwargs: Extra keyword arguments :return: Extended set of HTTP header arguments """ if http_args is None: http_args = {} if authn_method: logger.debug('Client authn method: {}'.format(authn_method)) return self.client_authn_factory(authn_method).construct( request, self, http_args=http_args, **kwargs) else: return http_args
Will run the proper client authentication method. Each such method will place the necessary information in the necessary place. A method may modify the request. :param request: The request, a Message class instance :param authn_method: Client authentication method :param http_args: HTTP header arguments :param kwargs: Extra keyword arguments :return: Extended set of HTTP header arguments
entailment
def construct_request(self, request_args=None, **kwargs): """ The method where everything is setup for sending the request. The request information is gathered and the where and how of sending the request is decided. :param request_args: Initial request arguments :param kwargs: Extra keyword arguments :return: A dictionary with the keys 'url' and possibly 'body', 'kwargs', 'request' and 'ht_args'. """ if request_args is None: request_args = {} # remove arguments that should not be included in the request # _args = dict( # [(k, v) for k, v in kwargs.items() if v and k not in SPECIAL_ARGS]) return self.construct(request_args, **kwargs)
The method where everything is setup for sending the request. The request information is gathered and the where and how of sending the request is decided. :param request_args: Initial request arguments :param kwargs: Extra keyword arguments :return: A dictionary with the keys 'url' and possibly 'body', 'kwargs', 'request' and 'ht_args'.
entailment
def get_endpoint(self): """ Find the service endpoint :return: The service endpoint (a URL) """ if self.endpoint: return self.endpoint else: return self.service_context.provider_info[self.endpoint_name]
Find the service endpoint :return: The service endpoint (a URL)
entailment
def get_authn_header(self, request, authn_method, **kwargs): """ Construct an authorization specification to be sent in the HTTP header. :param request: The service request :param authn_method: Which authentication/authorization method to use :param kwargs: Extra keyword arguments :return: A set of keyword arguments to be sent in the HTTP header. """ headers = {} # If I should deal with client authentication if authn_method: h_arg = self.init_authentication_method(request, authn_method, **kwargs) try: headers = h_arg['headers'] except KeyError: pass return headers
Construct an authorization specification to be sent in the HTTP header. :param request: The service request :param authn_method: Which authentication/authorization method to use :param kwargs: Extra keyword arguments :return: A set of keyword arguments to be sent in the HTTP header.
entailment
def get_request_parameters(self, request_body_type="", method="", authn_method='', request_args=None, http_args=None, **kwargs): """ Builds the request message and constructs the HTTP headers. This is the starting point for a pipeline that will: - construct the request message - add/remove information to/from the request message in the way a specific client authentication method requires. - gather a set of HTTP headers like Content-type and Authorization. - serialize the request message into the necessary format (JSON, urlencoded, signed JWT) :param request_body_type: Which serialization to use for the HTTP body :param method: HTTP method used. :param authn_method: Client authentication method :param request_args: Message arguments :param http_args: Initial HTTP header arguments :param kwargs: extra keyword arguments :return: Dictionary with the necessary information for the HTTP request """ if not method: method = self.http_method if not authn_method: authn_method = self.get_authn_method() if not request_body_type: request_body_type = self.request_body_type request = self.construct_request(request_args=request_args, **kwargs) _info = {'method': method} _args = kwargs.copy() if self.service_context.issuer: _args['iss'] = self.service_context.issuer # Client authentication by usage of the Authorization HTTP header # or by modifying the request object _headers = self.get_authn_header(request, authn_method, authn_endpoint=self.endpoint_name, **_args) # Find out where to send this request try: endpoint_url = kwargs['endpoint'] except KeyError: endpoint_url = self.get_endpoint() _info['url'] = get_http_url(endpoint_url, request, method=method) # If there is to be a body part if method == 'POST': # How should it be serialized if request_body_type == 'urlencoded': content_type = URL_ENCODED elif request_body_type in ['jws', 'jwe', 'jose']: content_type = JOSE_ENCODED else: # request_body_type == 'json' content_type = JSON_ENCODED _info['body'] = get_http_body(request, content_type) _headers.update({'Content-Type': content_type}) if _headers: _info['headers'] = _headers return _info
Builds the request message and constructs the HTTP headers. This is the starting point for a pipeline that will: - construct the request message - add/remove information to/from the request message in the way a specific client authentication method requires. - gather a set of HTTP headers like Content-type and Authorization. - serialize the request message into the necessary format (JSON, urlencoded, signed JWT) :param request_body_type: Which serialization to use for the HTTP body :param method: HTTP method used. :param authn_method: Client authentication method :param request_args: Message arguments :param http_args: Initial HTTP header arguments :param kwargs: extra keyword arguments :return: Dictionary with the necessary information for the HTTP request
entailment
def get_urlinfo(info): """ Pick out the fragment or query part from a URL. :param info: A URL possibly containing a query or a fragment part :return: the query/fragment part """ # If info is a whole URL pick out the query or fragment part if '?' in info or '#' in info: parts = urlparse(info) scheme, netloc, path, params, query, fragment = parts[:6] # either query of fragment if query: info = query else: info = fragment return info
Pick out the fragment or query part from a URL. :param info: A URL possibly containing a query or a fragment part :return: the query/fragment part
entailment
def gather_verify_arguments(self): """ Need to add some information before running verify() :return: dictionary with arguments to the verify call """ kwargs = {'client_id': self.service_context.client_id, 'iss': self.service_context.issuer, 'keyjar': self.service_context.keyjar, 'verify': True} return kwargs
Need to add some information before running verify() :return: dictionary with arguments to the verify call
entailment
def parse_response(self, info, sformat="", state="", **kwargs): """ This the start of a pipeline that will: 1 Deserializes a response into it's response message class. Or :py:class:`oidcmsg.oauth2.ErrorResponse` if it's an error message 2 verifies the correctness of the response by running the verify method belonging to the message class used. 3 runs the do_post_parse_response method iff the response was not an error response. :param info: The response, can be either in a JSON or an urlencoded format :param sformat: Which serialization that was used :param state: The state :param kwargs: Extra key word arguments :return: The parsed and to some extend verified response """ if not sformat: sformat = self.response_body_type logger.debug('response format: {}'.format(sformat)) if sformat in ['jose', 'jws', 'jwe']: resp = self.post_parse_response(info, state=state) if not resp: logger.error('Missing or faulty response') raise ResponseError("Missing or faulty response") return resp # If format is urlencoded 'info' may be a URL # in which case I have to get at the query/fragment part if sformat == "urlencoded": info = self.get_urlinfo(info) if sformat == 'jwt': args = {'allowed_sign_algs': self.service_context.get_sign_alg(self.service_name)} enc_algs = self.service_context.get_enc_alg_enc(self.service_name) args['allowed_enc_algs'] = enc_algs['alg'] args['allowed_enc_encs'] = enc_algs['enc'] _jwt = JWT(key_jar=self.service_context.keyjar, **args) _jwt.iss = self.service_context.client_id info = _jwt.unpack(info) sformat = "dict" logger.debug('response_cls: {}'.format(self.response_cls.__name__)) try: resp = self.response_cls().deserialize( info, sformat, iss=self.service_context.issuer, **kwargs) except Exception as err: resp = None if sformat == 'json': # Could be JWS or JWE but wrongly tagged # Adding issuer is just a fail-safe. If one things was wrong # then two can be. try: resp = self.response_cls().deserialize( info, 'jwt', iss=self.service_context.issuer, **kwargs) except Exception as err2: pass if resp is None: logger.error('Error while deserializing: {}'.format(err)) raise msg = 'Initial response parsing => "{}"' logger.debug(msg.format(resp.to_dict())) # is this an error message if is_error_message(resp): logger.debug('Error response: {}'.format(resp)) else: vargs = self.gather_verify_arguments() logger.debug("Verify response with {}".format(vargs)) try: # verify the message. If something is wrong an exception is # thrown resp.verify(**vargs) except Exception as err: logger.error( 'Got exception while verifying response: {}'.format(err)) raise resp = self.post_parse_response(resp, state=state) if not resp: logger.error('Missing or faulty response') raise ResponseError("Missing or faulty response") return resp
This the start of a pipeline that will: 1 Deserializes a response into it's response message class. Or :py:class:`oidcmsg.oauth2.ErrorResponse` if it's an error message 2 verifies the correctness of the response by running the verify method belonging to the message class used. 3 runs the do_post_parse_response method iff the response was not an error response. :param info: The response, can be either in a JSON or an urlencoded format :param sformat: Which serialization that was used :param state: The state :param kwargs: Extra key word arguments :return: The parsed and to some extend verified response
entailment
def get_conf_attr(self, attr, default=None): """ Get the value of a attribute in the configuration :param attr: The attribute :param default: If the attribute doesn't appear in the configuration return this value :return: The value of attribute in the configuration or the default value """ if attr in self.conf: return self.conf[attr] else: return default
Get the value of a attribute in the configuration :param attr: The attribute :param default: If the attribute doesn't appear in the configuration return this value :return: The value of attribute in the configuration or the default value
entailment
def add_code_challenge(request_args, service, **kwargs): """ PKCE RFC 7636 support To be added as a post_construct method to an :py:class:`oidcservice.oidc.service.Authorization` instance :param service: The service that uses this function :param request_args: Set of request arguments :param kwargs: Extra set of keyword arguments :return: Updated set of request arguments """ try: cv_len = service.service_context.config['code_challenge']['length'] except KeyError: cv_len = 64 # Use default # code_verifier: string of length cv_len code_verifier = unreserved(cv_len) _cv = code_verifier.encode() try: _method = service.service_context.config['code_challenge']['method'] except KeyError: _method = 'S256' try: # Pick hash method _hash_method = CC_METHOD[_method] # Use it on the code_verifier _hv = _hash_method(_cv).digest() # base64 encode the hash value code_challenge = b64e(_hv).decode('ascii') except KeyError: raise Unsupported( 'PKCE Transformation method:{}'.format(_method)) _item = Message(code_verifier=code_verifier,code_challenge_method=_method) service.store_item(_item, 'pkce', request_args['state']) request_args.update({"code_challenge": code_challenge, "code_challenge_method": _method}) return request_args
PKCE RFC 7636 support To be added as a post_construct method to an :py:class:`oidcservice.oidc.service.Authorization` instance :param service: The service that uses this function :param request_args: Set of request arguments :param kwargs: Extra set of keyword arguments :return: Updated set of request arguments
entailment
def add_code_verifier(request_args, service, **kwargs): """ PKCE RFC 7636 support To be added as a post_construct method to an :py:class:`oidcservice.oidc.service.AccessToken` instance :param service: The service that uses this function :param request_args: Set of request arguments :return: updated set of request arguments """ _item = service.get_item(Message, 'pkce', kwargs['state']) request_args.update({'code_verifier': _item['code_verifier']}) return request_args
PKCE RFC 7636 support To be added as a post_construct method to an :py:class:`oidcservice.oidc.service.AccessToken` instance :param service: The service that uses this function :param request_args: Set of request arguments :return: updated set of request arguments
entailment
def gather_verify_arguments(self): """ Need to add some information before running verify() :return: dictionary with arguments to the verify call """ _ctx = self.service_context kwargs = { 'client_id': _ctx.client_id, 'iss': _ctx.issuer, 'keyjar': _ctx.keyjar, 'verify': True, 'skew': _ctx.clock_skew } for attr, param in IDT2REG.items(): try: kwargs[attr] = _ctx.registration_response[param] except KeyError: pass try: kwargs['allow_missing_kid'] = self.service_context.allow[ 'missing_kid'] except KeyError: pass return kwargs
Need to add some information before running verify() :return: dictionary with arguments to the verify call
entailment
def post_parse_response(self, response, **kwargs): """ Add scope claim to response, from the request, if not present in the response :param response: The response :param kwargs: Extra Keyword arguments :return: A possibly augmented response """ if "scope" not in response: try: _key = kwargs['state'] except KeyError: pass else: if _key: item = self.get_item(oauth2.AuthorizationRequest, 'auth_request', _key) try: response["scope"] = item["scope"] except KeyError: pass return response
Add scope claim to response, from the request, if not present in the response :param response: The response :param kwargs: Extra Keyword arguments :return: A possibly augmented response
entailment
def get_id_token_hint(self, request_args=None, **kwargs): """ Add id_token_hint to request :param request_args: :param kwargs: :return: """ request_args = self.multiple_extend_request_args( request_args, kwargs['state'], ['id_token'], ['auth_response', 'token_response', 'refresh_token_response'], orig=True ) try: request_args['id_token_hint'] = request_args['id_token'] except KeyError: pass else: del request_args['id_token'] return request_args, {}
Add id_token_hint to request :param request_args: :param kwargs: :return:
entailment
def get_state(self, key): """ Get the state connected to a given key. :param key: Key into the state database :return: A :py:class:´oidcservice.state_interface.State` instance """ _data = self.state_db.get(key) if not _data: raise KeyError(key) else: return State().from_json(_data)
Get the state connected to a given key. :param key: Key into the state database :return: A :py:class:´oidcservice.state_interface.State` instance
entailment
def store_item(self, item, item_type, key): """ Store a service response. :param item: The item as a :py:class:`oidcmsg.message.Message` subclass instance or a JSON document. :param item_type: The type of request or response :param key: The key under which the information should be stored in the state database """ try: _state = self.get_state(key) except KeyError: _state = State() try: _state[item_type] = item.to_json() except AttributeError: _state[item_type] = item self.state_db.set(key, _state.to_json())
Store a service response. :param item: The item as a :py:class:`oidcmsg.message.Message` subclass instance or a JSON document. :param item_type: The type of request or response :param key: The key under which the information should be stored in the state database
entailment
def get_iss(self, key): """ Get the Issuer ID :param key: Key to the information in the state database :return: The issuer ID """ _state = self.get_state(key) if not _state: raise KeyError(key) return _state['iss']
Get the Issuer ID :param key: Key to the information in the state database :return: The issuer ID
entailment
def get_item(self, item_cls, item_type, key): """ Get a piece of information (a request or a response) from the state database. :param item_cls: The :py:class:`oidcmsg.message.Message` subclass that described the item. :param item_type: Which request/response that is wanted :param key: The key to the information in the state database :return: A :py:class:`oidcmsg.message.Message` instance """ _state = self.get_state(key) try: return item_cls(**_state[item_type]) except TypeError: return item_cls().from_json(_state[item_type])
Get a piece of information (a request or a response) from the state database. :param item_cls: The :py:class:`oidcmsg.message.Message` subclass that described the item. :param item_type: Which request/response that is wanted :param key: The key to the information in the state database :return: A :py:class:`oidcmsg.message.Message` instance
entailment
def extend_request_args(self, args, item_cls, item_type, key, parameters, orig=False): """ Add a set of parameters and their value to a set of request arguments. :param args: A dictionary :param item_cls: The :py:class:`oidcmsg.message.Message` subclass that describes the item :param item_type: The type of item, this is one of the parameter names in the :py:class:`oidcservice.state_interface.State` class. :param key: The key to the information in the database :param parameters: A list of parameters who's values this method will return. :param orig: Where the value of a claim is a signed JWT return that. :return: A dictionary with keys from the list of parameters and values being the values of those parameters in the item. If the parameter does not a appear in the item it will not appear in the returned dictionary. """ try: item = self.get_item(item_cls, item_type, key) except KeyError: pass else: for parameter in parameters: if orig: try: args[parameter] = item[parameter] except KeyError: pass else: try: args[parameter] = item[verified_claim_name(parameter)] except KeyError: try: args[parameter] = item[parameter] except KeyError: pass return args
Add a set of parameters and their value to a set of request arguments. :param args: A dictionary :param item_cls: The :py:class:`oidcmsg.message.Message` subclass that describes the item :param item_type: The type of item, this is one of the parameter names in the :py:class:`oidcservice.state_interface.State` class. :param key: The key to the information in the database :param parameters: A list of parameters who's values this method will return. :param orig: Where the value of a claim is a signed JWT return that. :return: A dictionary with keys from the list of parameters and values being the values of those parameters in the item. If the parameter does not a appear in the item it will not appear in the returned dictionary.
entailment
def multiple_extend_request_args(self, args, key, parameters, item_types, orig=False): """ Go through a set of items (by their type) and add the attribute-value that match the list of parameters to the arguments If the same parameter occurs in 2 different items then the value in the later one will be the one used. :param args: Initial set of arguments :param key: Key to the State information in the state database :param parameters: A list of parameters that we're looking for :param item_types: A list of item_type specifying which items we are interested in. :param orig: Where the value of a claim is a signed JWT return that. :return: A possibly augmented set of arguments. """ _state = self.get_state(key) for typ in item_types: try: _item = Message(**_state[typ]) except KeyError: continue for parameter in parameters: if orig: try: args[parameter] = _item[parameter] except KeyError: pass else: try: args[parameter] = _item[verified_claim_name(parameter)] except KeyError: try: args[parameter] = _item[parameter] except KeyError: pass return args
Go through a set of items (by their type) and add the attribute-value that match the list of parameters to the arguments If the same parameter occurs in 2 different items then the value in the later one will be the one used. :param args: Initial set of arguments :param key: Key to the State information in the state database :param parameters: A list of parameters that we're looking for :param item_types: A list of item_type specifying which items we are interested in. :param orig: Where the value of a claim is a signed JWT return that. :return: A possibly augmented set of arguments.
entailment
def store_X2state(self, x, state, xtyp): """ Store the connection between some value (x) and a state value. This allows us later in the game to find the state if we have x. :param x: The value of x :param state: The state value :param xtyp: The type of value x is (e.g. nonce, ...) """ self.state_db.set(KEY_PATTERN[xtyp].format(x), state) try: _val = self.state_db.get("ref{}ref".format(state)) except KeyError: _val = None if _val is None: refs = {xtyp:x} else: refs = json.loads(_val) refs[xtyp] = x self.state_db.set("ref{}ref".format(state), json.dumps(refs))
Store the connection between some value (x) and a state value. This allows us later in the game to find the state if we have x. :param x: The value of x :param state: The state value :param xtyp: The type of value x is (e.g. nonce, ...)
entailment
def get_state_by_X(self, x, xtyp): """ Find the state value by providing the x value. Will raise an exception if the x value is absent from the state data base. :param x: The x value :return: The state value """ _state = self.state_db.get(KEY_PATTERN[xtyp].format(x)) if _state: return _state else: raise KeyError('Unknown {}: "{}"'.format(xtyp, x))
Find the state value by providing the x value. Will raise an exception if the x value is absent from the state data base. :param x: The x value :return: The state value
entailment
def filename_from_webname(self, webname): """ A 1<->1 map is maintained between a URL pointing to a file and the name of the file in the file system. As an example if the base_url is 'https://example.com' and a jwks_uri is 'https://example.com/jwks_uri.json' then the filename of the corresponding file on the local filesystem would be 'jwks_uri'. Relative to the directory from which the RP instance is run. :param webname: The published URL :return: local filename """ if not webname.startswith(self.base_url): raise ValueError("Webname doesn't match base_url") _name = webname[len(self.base_url):] if _name.startswith('/'): return _name[1:] else: return _name
A 1<->1 map is maintained between a URL pointing to a file and the name of the file in the file system. As an example if the base_url is 'https://example.com' and a jwks_uri is 'https://example.com/jwks_uri.json' then the filename of the corresponding file on the local filesystem would be 'jwks_uri'. Relative to the directory from which the RP instance is run. :param webname: The published URL :return: local filename
entailment
def generate_request_uris(self, path): """ Need to generate a redirect_uri path that is unique for a OP/RP combo This is to counter the mix-up attack. :param path: Leading path :return: A list of one unique URL """ m = hashlib.sha256() try: m.update(as_bytes(self.provider_info['issuer'])) except KeyError: m.update(as_bytes(self.issuer)) m.update(as_bytes(self.base_url)) if not path.startswith('/'): return ['{}/{}/{}'.format(self.base_url, path, m.hexdigest())] else: return ['{}{}/{}'.format(self.base_url, path, m.hexdigest())]
Need to generate a redirect_uri path that is unique for a OP/RP combo This is to counter the mix-up attack. :param path: Leading path :return: A list of one unique URL
entailment
def import_keys(self, keyspec): """ The client needs it's own set of keys. It can either dynamically create them or load them from local storage. This method can also fetch other entities keys provided the URL points to a JWKS. :param keyspec: """ for where, spec in keyspec.items(): if where == 'file': for typ, files in spec.items(): if typ == 'rsa': for fil in files: _key = RSAKey( key=import_private_rsa_key_from_file(fil), use='sig') _kb = KeyBundle() _kb.append(_key) self.keyjar.add_kb('', _kb) elif where == 'url': for iss, url in spec.items(): kb = KeyBundle(source=url) self.keyjar.add_kb(iss, kb)
The client needs it's own set of keys. It can either dynamically create them or load them from local storage. This method can also fetch other entities keys provided the URL points to a JWKS. :param keyspec:
entailment
def assertion_jwt(client_id, keys, audience, algorithm, lifetime=600): """ Create a signed Json Web Token containing some information. :param client_id: The Client ID :param keys: Signing keys :param audience: Who is the receivers for this assertion :param algorithm: Signing algorithm :param lifetime: The lifetime of the signed Json Web Token :return: A Signed Json Web Token """ _now = utc_time_sans_frac() at = AuthnToken(iss=client_id, sub=client_id, aud=audience, jti=rndstr(32), exp=_now + lifetime, iat=_now) logger.debug('AuthnToken: {}'.format(at.to_dict())) return at.to_jwt(key=keys, algorithm=algorithm)
Create a signed Json Web Token containing some information. :param client_id: The Client ID :param keys: Signing keys :param audience: Who is the receivers for this assertion :param algorithm: Signing algorithm :param lifetime: The lifetime of the signed Json Web Token :return: A Signed Json Web Token
entailment
def find_token(request, token_type, service, **kwargs): """ The access token can be in a number of places. There are priority rules as to which one to use, abide by those: 1 If it's among the request parameters use that 2 If among the extra keyword arguments 3 Acquired by a previous run service. :param request: :param token_type: :param service: :param kwargs: :return: """ if request is not None: try: _token = request[token_type] except KeyError: pass else: del request[token_type] # Required under certain circumstances :-) not under other request.c_param[token_type] = SINGLE_OPTIONAL_STRING return _token try: return kwargs["access_token"] except KeyError: # I should pick the latest acquired token, this should be the right # order for that. _arg = service.multiple_extend_request_args( {}, kwargs['state'], ['access_token'], ['auth_response', 'token_response', 'refresh_token_response']) return _arg['access_token']
The access token can be in a number of places. There are priority rules as to which one to use, abide by those: 1 If it's among the request parameters use that 2 If among the extra keyword arguments 3 Acquired by a previous run service. :param request: :param token_type: :param service: :param kwargs: :return:
entailment
def valid_service_context(service_context, when=0): """ Check if the client_secret has expired :param service_context: A :py:class:`oidcservice.service_context.ServiceContext` instance :param when: A time stamp against which the expiration time is to be checked :return: True if the client_secret is still valid """ eta = getattr(service_context, 'client_secret_expires_at', 0) now = when or utc_time_sans_frac() if eta != 0 and eta < now: return False return True
Check if the client_secret has expired :param service_context: A :py:class:`oidcservice.service_context.ServiceContext` instance :param when: A time stamp against which the expiration time is to be checked :return: True if the client_secret is still valid
entailment
def construct(self, request, service=None, http_args=None, **kwargs): """ Construct a dictionary to be added to the HTTP request headers :param request: The request :param service: A :py:class:`oidcservice.service.Service` instance :param http_args: HTTP arguments :return: dictionary of HTTP arguments """ if http_args is None: http_args = {} if "headers" not in http_args: http_args["headers"] = {} # get the username (client_id) and the password (client_secret) try: passwd = kwargs["password"] except KeyError: try: passwd = request["client_secret"] except KeyError: passwd = service.service_context.client_secret try: user = kwargs["user"] except KeyError: user = service.service_context.client_id # The credential is username and password concatenated with a ':' # in between and then base 64 encoded becomes the authentication # token. credentials = "{}:{}".format(quote_plus(user), quote_plus(passwd)) authz = base64.urlsafe_b64encode(credentials.encode("utf-8")).decode( "utf-8") http_args["headers"]["Authorization"] = "Basic {}".format(authz) # If client_secret was part of the request message instance remove it try: del request["client_secret"] except (KeyError, TypeError): pass # If we're doing an access token request with an authorization code # then we should add client_id to the request if it's not already # there if isinstance(request, AccessTokenRequest) and request[ 'grant_type'] == 'authorization_code': if 'client_id' not in request: try: request['client_id'] = service.service_context.client_id except AttributeError: pass else: # remove client_id if not required by the request definition try: _req = request.c_param["client_id"][VREQUIRED] except (KeyError, AttributeError): _req = False # if it's not required remove it if not _req: try: del request["client_id"] except KeyError: pass return http_args
Construct a dictionary to be added to the HTTP request headers :param request: The request :param service: A :py:class:`oidcservice.service.Service` instance :param http_args: HTTP arguments :return: dictionary of HTTP arguments
entailment
def construct(self, request=None, service=None, http_args=None, **kwargs): """ Constructing the Authorization header. The value of the Authorization header is "Bearer <access_token>". :param request: Request class instance :param service: Service :param http_args: HTTP header arguments :param kwargs: extra keyword arguments :return: """ if service.service_name == 'refresh_token': _acc_token = find_token(request, 'refresh_token', service, **kwargs) else: _acc_token = find_token(request, 'access_token', service, **kwargs) if not _acc_token: raise KeyError('No access or refresh token available') # The authorization value starts with 'Bearer' when bearer tokens # are used _bearer = "Bearer {}".format(_acc_token) # Add 'Authorization' to the headers if http_args is None: http_args = {"headers": {}} http_args["headers"]["Authorization"] = _bearer else: try: http_args["headers"]["Authorization"] = _bearer except KeyError: http_args["headers"] = {"Authorization": _bearer} return http_args
Constructing the Authorization header. The value of the Authorization header is "Bearer <access_token>". :param request: Request class instance :param service: Service :param http_args: HTTP header arguments :param kwargs: extra keyword arguments :return:
entailment
def construct(self, request, service=None, http_args=None, **kwargs): """ Will add a token to the request if not present :param request: The request :param service_context: A :py:class:`oidcservice.service.Service` instance :param http_args: HTTP arguments :param kwargs: extra keyword arguments :return: A possibly modified dictionary with HTTP arguments. """ _acc_token = '' for _token_type in ['access_token', 'refresh_token']: _acc_token = find_token(request, _token_type, service, **kwargs) if _acc_token: break if not _acc_token: raise KeyError('No access or refresh token available') else: request["access_token"] = _acc_token return http_args
Will add a token to the request if not present :param request: The request :param service_context: A :py:class:`oidcservice.service.Service` instance :param http_args: HTTP arguments :param kwargs: extra keyword arguments :return: A possibly modified dictionary with HTTP arguments.
entailment
def choose_algorithm(self, context, **kwargs): """ Pick signing algorithm :param context: Signing context :param kwargs: extra keyword arguments :return: Name of a signing algorithm """ try: algorithm = kwargs["algorithm"] except KeyError: # different contexts uses different signing algorithms algorithm = DEF_SIGN_ALG[context] if not algorithm: raise AuthnFailure("Missing algorithm specification") return algorithm
Pick signing algorithm :param context: Signing context :param kwargs: extra keyword arguments :return: Name of a signing algorithm
entailment
def get_signing_key(self, algorithm, service_context): """ Pick signing key based on signing algorithm to be used :param algorithm: Signing algorithm :param service_context: A :py:class:`oidcservice.service_context.ServiceContext` instance :return: A key """ return service_context.keyjar.get_signing_key( alg2keytype(algorithm), alg=algorithm)
Pick signing key based on signing algorithm to be used :param algorithm: Signing algorithm :param service_context: A :py:class:`oidcservice.service_context.ServiceContext` instance :return: A key
entailment
def get_key_by_kid(self, kid, algorithm, service_context): """ Pick a key that matches a given key ID and signing algorithm. :param kid: Key ID :param algorithm: Signing algorithm :param service_context: A :py:class:`oidcservice.service_context.ServiceContext` instance :return: A matching key """ _key = service_context.keyjar.get_key_by_kid(kid) if _key: ktype = alg2keytype(algorithm) if _key.kty != ktype: raise NoMatchingKey("Wrong key type") else: return _key else: raise NoMatchingKey("No key with kid:%s" % kid)
Pick a key that matches a given key ID and signing algorithm. :param kid: Key ID :param algorithm: Signing algorithm :param service_context: A :py:class:`oidcservice.service_context.ServiceContext` instance :return: A matching key
entailment
def construct(self, request, service=None, http_args=None, **kwargs): """ Constructs a client assertion and signs it with a key. The request is modified as a side effect. :param request: The request :param service: A :py:class:`oidcservice.service.Service` instance :param http_args: HTTP arguments :param kwargs: Extra arguments :return: Constructed HTTP arguments, in this case none """ if 'client_assertion' in kwargs: request["client_assertion"] = kwargs['client_assertion'] if 'client_assertion_type' in kwargs: request[ 'client_assertion_type'] = kwargs['client_assertion_type'] else: request["client_assertion_type"] = JWT_BEARER elif 'client_assertion' in request: if 'client_assertion_type' not in request: request["client_assertion_type"] = JWT_BEARER else: algorithm = None _context = service.service_context # audience for the signed JWT depends on which endpoint # we're talking to. if kwargs['authn_endpoint'] in ['token_endpoint']: try: algorithm = _context.behaviour[ 'token_endpoint_auth_signing_alg'] except (KeyError, AttributeError): pass audience = _context.provider_info['token_endpoint'] else: audience = _context.provider_info['issuer'] if not algorithm: algorithm = self.choose_algorithm(**kwargs) ktype = alg2keytype(algorithm) try: if 'kid' in kwargs: signing_key = [self.get_key_by_kid(kwargs["kid"], algorithm, _context)] elif ktype in _context.kid["sig"]: try: signing_key = [self.get_key_by_kid( _context.kid["sig"][ktype], algorithm, _context)] except KeyError: signing_key = self.get_signing_key(algorithm, _context) else: signing_key = self.get_signing_key(algorithm, _context) except NoMatchingKey as err: logger.error("%s" % sanitize(err)) raise try: _args = {'lifetime': kwargs['lifetime']} except KeyError: _args = {} # construct the signed JWT with the assertions and add # it as value to the 'client_assertion' claim of the request request["client_assertion"] = assertion_jwt( _context.client_id, signing_key, audience, algorithm, **_args) request["client_assertion_type"] = JWT_BEARER try: del request["client_secret"] except KeyError: pass # If client_id is not required to be present, remove it. if not request.c_param["client_id"][VREQUIRED]: try: del request["client_id"] except KeyError: pass return {}
Constructs a client assertion and signs it with a key. The request is modified as a side effect. :param request: The request :param service: A :py:class:`oidcservice.service.Service` instance :param http_args: HTTP arguments :param kwargs: Extra arguments :return: Constructed HTTP arguments, in this case none
entailment
def get_endpoint(self): """ Find the issuer ID and from it construct the service endpoint :return: Service endpoint """ try: _iss = self.service_context.issuer except AttributeError: _iss = self.endpoint if _iss.endswith('/'): return OIDCONF_PATTERN.format(_iss[:-1]) else: return OIDCONF_PATTERN.format(_iss)
Find the issuer ID and from it construct the service endpoint :return: Service endpoint
entailment
def _update_service_context(self, resp, **kwargs): """ Deal with Provider Config Response. Based on the provider info response a set of parameters in different places needs to be set. :param resp: The provider info response :param service_context: Information collected/used by services """ issuer = self.service_context.issuer # Verify that the issuer value received is the same as the # url that was used as service endpoint (without the .well-known part) if "issuer" in resp: _pcr_issuer = resp["issuer"] if resp["issuer"].endswith("/"): if issuer.endswith("/"): _issuer = issuer else: _issuer = issuer + "/" else: if issuer.endswith("/"): _issuer = issuer[:-1] else: _issuer = issuer # In some cases we can live with the two URLs not being # the same. But this is an excepted that has to be explicit try: self.service_context.allow['issuer_mismatch'] except KeyError: if _issuer != _pcr_issuer: raise OidcServiceError( "provider info issuer mismatch '%s' != '%s'" % ( _issuer, _pcr_issuer)) else: # No prior knowledge _pcr_issuer = issuer self.service_context.issuer = _pcr_issuer self.service_context.provider_info = resp # If there are services defined set the service endpoint to be # the URLs specified in the provider information. try: _srvs = self.service_context.service except AttributeError: pass else: if self.service_context.service: for key, val in resp.items(): # All service endpoint parameters in the provider info has # a name ending in '_endpoint' so I can look specifically # for those if key.endswith("_endpoint"): for _srv in self.service_context.service.values(): # Every service has an endpoint_name assigned # when initiated. This name *MUST* match the # endpoint names used in the provider info if _srv.endpoint_name == key: _srv.endpoint = val # If I already have a Key Jar then I'll add then provider keys to # that. Otherwise a new Key Jar is minted try: kj = self.service_context.keyjar except KeyError: kj = KeyJar() # Load the keys. Note that this only means that the key specification # is loaded not necessarily that any keys are fetched. if 'jwks_uri' in resp: kj.load_keys(_pcr_issuer, jwks_uri=resp['jwks_uri']) elif 'jwks' in resp: kj.load_keys(_pcr_issuer, jwks=resp['jwks']) self.service_context.keyjar = kj
Deal with Provider Config Response. Based on the provider info response a set of parameters in different places needs to be set. :param resp: The provider info response :param service_context: Information collected/used by services
entailment
def query(self, resource): """ Given a resource identifier find the domain specifier and then construct the webfinger request. Implements http://openid.net/specs/openid-connect-discovery-1_0.html#NormalizationSteps :param resource: """ if resource[0] in ['=', '@', '!']: # Have no process for handling these raise ValueError('Not allowed resource identifier') try: part = urlsplit(resource) except Exception: raise ValueError('Unparsable resource') else: if not part[SCHEME]: if not part[NETLOC]: _path = part[PATH] if not part[QUERY] and not part[FRAGMENT]: if '/' in _path or ':' in _path: resource = "https://{}".format(resource) part = urlsplit(resource) authority = part[NETLOC] else: if '@' in _path: authority = _path.split('@')[1] else: authority = _path resource = 'acct:{}'.format(_path) elif part[QUERY]: resource = "https://{}?{}".format(_path, part[QUERY]) parts = urlsplit(resource) authority = parts[NETLOC] else: resource = "https://{}".format(_path) part = urlsplit(resource) authority = part[NETLOC] else: raise ValueError('Missing netloc') else: _scheme = part[SCHEME] if _scheme not in ['http', 'https', 'acct']: # assume it to be a hostname port combo, # eg. example.com:8080 resource = 'https://{}'.format(resource) part = urlsplit(resource) authority = part[NETLOC] resource = self.create_url(part, [FRAGMENT]) elif _scheme in ['http', 'https'] and not part[NETLOC]: raise ValueError( 'No authority part in the resource specification') elif _scheme == 'acct': _path = part[PATH] for c in ['/', '?']: _path = _path.split(c)[0] if '@' in _path: authority = _path.split('@')[1] else: raise ValueError( 'No authority part in the resource specification') authority = authority.split('#')[0] resource = self.create_url(part, [FRAGMENT]) else: authority = part[NETLOC] resource = self.create_url(part, [FRAGMENT]) location = WF_URL.format(authority) return oidc.WebFingerRequest( resource=resource, rel=OIC_ISSUER).request(location)
Given a resource identifier find the domain specifier and then construct the webfinger request. Implements http://openid.net/specs/openid-connect-discovery-1_0.html#NormalizationSteps :param resource:
entailment
def get_http_url(url, req, method='GET'): """ Add a query part representing the request to a url that may already contain a query part. Only done if the HTTP method used is 'GET' or 'DELETE'. :param url: The URL :param req: The request as a :py:class:`oidcmsg.message.Message` instance :param method: The HTTP method :return: A possibly modified URL """ if method in ["GET", "DELETE"]: if req.keys(): _req = req.copy() comp = urlsplit(str(url)) if comp.query: _req.update(parse_qs(comp.query)) _query = str(_req.to_urlencoded()) return urlunsplit((comp.scheme, comp.netloc, comp.path, _query, comp.fragment)) else: return url else: return url
Add a query part representing the request to a url that may already contain a query part. Only done if the HTTP method used is 'GET' or 'DELETE'. :param url: The URL :param req: The request as a :py:class:`oidcmsg.message.Message` instance :param method: The HTTP method :return: A possibly modified URL
entailment
def get_http_body(req, content_type=URL_ENCODED): """ Get the message into the format that should be places in the body part of a HTTP request. :param req: The service request as a :py:class:`oidcmsg.message.Message` instance :param content_type: The format of the body part. :return: The correctly formatet service request. """ if URL_ENCODED in content_type: return req.to_urlencoded() elif JSON_ENCODED in content_type: return req.to_json() elif JOSE_ENCODED in content_type: return req # already packaged else: raise UnSupported( "Unsupported content type: '%s'" % content_type)
Get the message into the format that should be places in the body part of a HTTP request. :param req: The service request as a :py:class:`oidcmsg.message.Message` instance :param content_type: The format of the body part. :return: The correctly formatet service request.
entailment
def modsplit(s): """Split importable""" if ':' in s: c = s.split(':') if len(c) != 2: raise ValueError("Syntax error: {s}") return c[0], c[1] else: c = s.split('.') if len(c) < 2: raise ValueError("Syntax error: {s}") return '.'.join(c[:-1]), c[-1]
Split importable
entailment
def importer(name): """Import by name""" c1, c2 = modsplit(name) module = importlib.import_module(c1) return getattr(module, c2)
Import by name
entailment
def rndstr(size=16): """ Returns a string of random ascii characters or digits :param size: The length of the string :return: string """ _basech = string.ascii_letters + string.digits return "".join([rnd.choice(_basech) for _ in range(size)])
Returns a string of random ascii characters or digits :param size: The length of the string :return: string
entailment
def add_redirect_uris(request_args, service=None, **kwargs): """ Add redirect_uris to the request arguments. :param request_args: Incomming request arguments :param service: A link to the service :param kwargs: Possible extra keyword arguments :return: A possibly augmented set of request arguments. """ _context = service.service_context if "redirect_uris" not in request_args: # Callbacks is a dictionary with callback type 'code', 'implicit', # 'form_post' as keys. try: _cbs = _context.callbacks except AttributeError: request_args['redirect_uris'] = _context.redirect_uris else: # Filter out local additions. _uris = [v for k, v in _cbs.items() if not k.startswith('__')] request_args['redirect_uris'] = _uris return request_args, {}
Add redirect_uris to the request arguments. :param request_args: Incomming request arguments :param service: A link to the service :param kwargs: Possible extra keyword arguments :return: A possibly augmented set of request arguments.
entailment
def match_preferences(self, pcr=None, issuer=None): """ Match the clients preferences against what the provider can do. This is to prepare for later client registration and or what functionality the client actually will use. In the client configuration the client preferences are expressed. These are then compared with the Provider Configuration information. If the Provider has left some claims out, defaults specified in the standard will be used. :param pcr: Provider configuration response if available :param issuer: The issuer identifier """ if not pcr: pcr = self.service_context.provider_info regreq = oidc.RegistrationRequest for _pref, _prov in PREFERENCE2PROVIDER.items(): try: vals = self.service_context.client_preferences[_pref] except KeyError: continue try: _pvals = pcr[_prov] except KeyError: try: # If the provider have not specified use what the # standard says is mandatory if at all. _pvals = PROVIDER_DEFAULT[_pref] except KeyError: logger.info( 'No info from provider on {} and no default'.format( _pref)) _pvals = vals if isinstance(vals, str): if vals in _pvals: self.service_context.behaviour[_pref] = vals else: try: vtyp = regreq.c_param[_pref] except KeyError: # Allow non standard claims if isinstance(vals, list): self.service_context.behaviour[_pref] = [ v for v in vals if v in _pvals] elif vals in _pvals: self.service_context.behaviour[_pref] = vals else: if isinstance(vtyp[0], list): self.service_context.behaviour[_pref] = [] for val in vals: if val in _pvals: self.service_context.behaviour[_pref].append( val) else: for val in vals: if val in _pvals: self.service_context.behaviour[_pref] = val break if _pref not in self.service_context.behaviour: raise ConfigurationError( "OP couldn't match preference:%s" % _pref, pcr) for key, val in self.service_context.client_preferences.items(): if key in self.service_context.behaviour: continue try: vtyp = regreq.c_param[key] if isinstance(vtyp[0], list): pass elif isinstance(val, list) and not isinstance(val, str): val = val[0] except KeyError: pass if key not in PREFERENCE2PROVIDER: self.service_context.behaviour[key] = val logger.debug( 'service_context behaviour: {}'.format( self.service_context.behaviour))
Match the clients preferences against what the provider can do. This is to prepare for later client registration and or what functionality the client actually will use. In the client configuration the client preferences are expressed. These are then compared with the Provider Configuration information. If the Provider has left some claims out, defaults specified in the standard will be used. :param pcr: Provider configuration response if available :param issuer: The issuer identifier
entailment
def soundexCode(self, char): '''Return the soundex code for given character :param char: Character whose soundex code is needed :return: Returns soundex code if character is found in charmap else returns 0 ''' lang = get_language(char) try: if lang == "en_US": return _soundex_map["soundex_en"][charmap[lang].index(char)] else: return _soundex_map["soundex"][charmap[lang].index(char)] except: # Case of exception KeyError because we don't have soundex # mapping for the character pass return 0
Return the soundex code for given character :param char: Character whose soundex code is needed :return: Returns soundex code if character is found in charmap else returns 0
entailment
def soundex(self, name, length=8): '''Calculate soundex of given string This function calculates soundex for Indian language string as well as English string. This function is exposed as service method for JSONRPC in SILPA framework. :param name: String whose Soundex value to be calculated :param length: Length of final Soundex string, if soundex caculated is more than this it will be truncated to length. :return: Soundex string of `name' ''' sndx = [] fc = name[0] # translate alpha chars in name to soundex digits for c in name[1:].lower(): d = str(self.soundexCode(c)) # remove all 0s from the soundex code if d == '0': continue # duplicate consecutive soundex digits are skipped if len(sndx) == 0: sndx.append(d) elif d != sndx[-1]: sndx.append(d) # append first character to result sndx.insert(0, fc) if get_language(name[0]) == 'en_US': # Don't padd return ''.join(sndx) if len(sndx) < length: sndx.extend(repeat('0', length)) return ''.join(sndx[:length]) return ''.join(sndx[:length])
Calculate soundex of given string This function calculates soundex for Indian language string as well as English string. This function is exposed as service method for JSONRPC in SILPA framework. :param name: String whose Soundex value to be calculated :param length: Length of final Soundex string, if soundex caculated is more than this it will be truncated to length. :return: Soundex string of `name'
entailment
def compare(self, string1, string2): '''Compare soundex of given strings This function checks if 2 given strings are phonetically sounds same by doing soundex code comparison :param string1: First string for comparison :param string2: Second string for comparison :return: Returns 0 if both strings are same, 1 if strings sound phonetically same and from same language, 2 if strings are phonetically same and from different languages. Returns -1 if strings are not equal. We can't perform English cross language comparision if English string is passed as one function will return -1. ''' # do a quick check if string1 == string2: return 0 string1_lang = get_language(string1[0]) string2_lang = get_language(string2[0]) if (string1_lang == 'en_US' and string2_lang != 'en_US') or \ (string1_lang != 'en_US' and string2_lang == 'en_US'): # Can't Soundex compare English and Indic string return -1 soundex1 = self.soundex(string1) soundex2 = self.soundex(string2) if soundex1[1:] == soundex2[1:]: # Strings sound phonetically same if string1_lang == string2_lang: # They are from same language return 1 else: # Different language return 2 # Strings are not same return -1
Compare soundex of given strings This function checks if 2 given strings are phonetically sounds same by doing soundex code comparison :param string1: First string for comparison :param string2: Second string for comparison :return: Returns 0 if both strings are same, 1 if strings sound phonetically same and from same language, 2 if strings are phonetically same and from different languages. Returns -1 if strings are not equal. We can't perform English cross language comparision if English string is passed as one function will return -1.
entailment
def get_response_for_url(self, url): """ Accepts a fully-qualified url. Returns an HttpResponse, passing through all headers and the status code. """ if not url or "//" not in url: raise ValueError("Missing or invalid url: %s" % url) render_url = self.BASE_URL + url headers = { 'X-Prerender-Token': self.token, } r = self.session.get(render_url, headers=headers, allow_redirects=False) assert r.status_code < 500 return self.build_django_response_from_requests_response(r)
Accepts a fully-qualified url. Returns an HttpResponse, passing through all headers and the status code.
entailment
def update_url(self, url=None, regex=None): """ Accepts a fully-qualified url, or regex. Returns True if successful, False if not successful. """ if not url and not regex: raise ValueError("Neither a url or regex was provided to update_url.") headers = { 'X-Prerender-Token': self.token, 'Content-Type': 'application/json', } data = { 'prerenderToken': settings.PRERENDER_TOKEN, } if url: data["url"] = url if regex: data["regex"] = regex r = self.session.post(self.RECACHE_URL, headers=headers, data=data) return r.status_code < 500
Accepts a fully-qualified url, or regex. Returns True if successful, False if not successful.
entailment
def update_url(self, url=None): """ Accepts a fully-qualified url. Returns True if successful, False if not successful. """ if not url: raise ValueError("Neither a url or regex was provided to update_url.") post_url = "%s%s" % (self.BASE_URL, url) r = self.session.post(post_url) return int(r.status_code) < 500
Accepts a fully-qualified url. Returns True if successful, False if not successful.
entailment
def create(self, validated_data): """Override ``create`` to provide a user via request.user by default. This is required since the read_only ``user`` field is not included by default anymore since https://github.com/encode/django-rest-framework/pull/5886. """ if 'user' not in validated_data: validated_data['user'] = self.context['request'].user return super(RefreshTokenSerializer, self).create(validated_data)
Override ``create`` to provide a user via request.user by default. This is required since the read_only ``user`` field is not included by default anymore since https://github.com/encode/django-rest-framework/pull/5886.
entailment
def has_object_permission(self, request, view, obj): """ Allow staff or superusers, and the owner of the object itself. """ user = request.user if not user.is_authenticated: return False elif user.is_staff or user.is_superuser: return True return user == obj.user
Allow staff or superusers, and the owner of the object itself.
entailment
def clear(self): """Release the semaphore of all of its bounds, setting the internal counter back to its original bind limit. Notify an equivalent amount of threads that they can run.""" with self._cond: to_notify = self._initial - self._value self._value = self._initial self._cond.notify(to_notify)
Release the semaphore of all of its bounds, setting the internal counter back to its original bind limit. Notify an equivalent amount of threads that they can run.
entailment
def _api_wrapper(fn): """API function decorator that performs rate limiting and error checking.""" def _convert(value): if isinstance(value, _datetime.date): return value.strftime('%s') return value @_six.wraps(fn) def _fn(self, command, **params): # sanitize the params by removing the None values with self.startup_lock: if self.timer.ident is None: self.timer.setDaemon(True) self.timer.start() params = dict((key, _convert(value)) for key, value in _six.iteritems(params) if value is not None) self.semaphore.acquire() resp = fn(self, command, **params) try: respdata = resp.json(object_hook=_AutoCastDict) except: # use more specific error if available or fallback to ValueError resp.raise_for_status() raise Exception('No JSON object could be decoded') # check for 'error' then check for status due to Poloniex inconsistency if 'error' in respdata: raise PoloniexCommandException(respdata['error']) resp.raise_for_status() return respdata return _fn
API function decorator that performs rate limiting and error checking.
entailment
def _public(self, command, **params): """Invoke the 'command' public API with optional params.""" params['command'] = command response = self.session.get(self._public_url, params=params) return response
Invoke the 'command' public API with optional params.
entailment
def returnOrderBook(self, currencyPair='all', depth='50'): """Returns the order book for a given market, as well as a sequence number for use with the Push API and an indicator specifying whether the market is frozen. You may set currencyPair to "all" to get the order books of all markets.""" return self._public('returnOrderBook', currencyPair=currencyPair, depth=depth)
Returns the order book for a given market, as well as a sequence number for use with the Push API and an indicator specifying whether the market is frozen. You may set currencyPair to "all" to get the order books of all markets.
entailment
def returnTradeHistory(self, currencyPair, start=None, end=None): """Returns the past 200 trades for a given market, or up to 50,000 trades between a range specified in UNIX timestamps by the "start" and "end" GET parameters.""" return self._public('returnTradeHistory', currencyPair=currencyPair, start=start, end=end)
Returns the past 200 trades for a given market, or up to 50,000 trades between a range specified in UNIX timestamps by the "start" and "end" GET parameters.
entailment
def returnChartData(self, currencyPair, period, start=0, end=2**32-1): """Returns candlestick chart data. Required GET parameters are "currencyPair", "period" (candlestick period in seconds; valid values are 300, 900, 1800, 7200, 14400, and 86400), "start", and "end". "Start" and "end" are given in UNIX timestamp format and used to specify the date range for the data returned.""" return self._public('returnChartData', currencyPair=currencyPair, period=period, start=start, end=end)
Returns candlestick chart data. Required GET parameters are "currencyPair", "period" (candlestick period in seconds; valid values are 300, 900, 1800, 7200, 14400, and 86400), "start", and "end". "Start" and "end" are given in UNIX timestamp format and used to specify the date range for the data returned.
entailment
def _private(self, command, **params): """Invoke the 'command' public API with optional params.""" if not self._apikey or not self._secret: raise PoloniexCredentialsException('missing apikey/secret') with self.nonce_lock: params.update({'command': command, 'nonce': next(self.nonce_iter)}) response = self.session.post( self._private_url, data=params, auth=Poloniex._PoloniexAuth(self._apikey, self._secret)) return response
Invoke the 'command' public API with optional params.
entailment
def returnDepositsWithdrawals(self, start=0, end=2**32-1): """Returns your deposit and withdrawal history within a range, specified by the "start" and "end" POST parameters, both of which should be given as UNIX timestamps.""" return self._private('returnDepositsWithdrawals', start=start, end=end)
Returns your deposit and withdrawal history within a range, specified by the "start" and "end" POST parameters, both of which should be given as UNIX timestamps.
entailment
def returnTradeHistory(self, currencyPair='all', start=None, end=None, limit=500): """Returns your trade history for a given market, specified by the "currencyPair" POST parameter. You may specify "all" as the currencyPair to receive your trade history for all markets. You may optionally specify a range via "start" and/or "end" POST parameters, given in UNIX timestamp format; if you do not specify a range, it will be limited to one day.""" return self._private('returnTradeHistory', currencyPair=currencyPair, start=start, end=end, limit=limit)
Returns your trade history for a given market, specified by the "currencyPair" POST parameter. You may specify "all" as the currencyPair to receive your trade history for all markets. You may optionally specify a range via "start" and/or "end" POST parameters, given in UNIX timestamp format; if you do not specify a range, it will be limited to one day.
entailment
def returnTradeHistoryPublic(self, currencyPair, start=None, end=None): """Returns the past 200 trades for a given market, or up to 50,000 trades between a range specified in UNIX timestamps by the "start" and "end" GET parameters.""" return super(Poloniex, self).returnTradeHistory(currencyPair, start, end)
Returns the past 200 trades for a given market, or up to 50,000 trades between a range specified in UNIX timestamps by the "start" and "end" GET parameters.
entailment
def buy(self, currencyPair, rate, amount, fillOrKill=None, immediateOrCancel=None, postOnly=None): """Places a limit buy order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". If successful, the method will return the order number. You may optionally set "fillOrKill", "immediateOrCancel", "postOnly" to 1. A fill-or-kill order will either fill in its entirety or be completely aborted. An immediate-or-cancel order can be partially or completely filled, but any portion of the order that cannot be filled immediately will be canceled rather than left on the order book. A post-only order will only be placed if no portion of it fills immediately; this guarantees you will never pay the taker fee on any part of the order that fills.""" return self._private('buy', currencyPair=currencyPair, rate=rate, amount=amount, fillOrKill=fillOrKill, immediateOrCancel=immediateOrCancel, postOnly=postOnly)
Places a limit buy order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". If successful, the method will return the order number. You may optionally set "fillOrKill", "immediateOrCancel", "postOnly" to 1. A fill-or-kill order will either fill in its entirety or be completely aborted. An immediate-or-cancel order can be partially or completely filled, but any portion of the order that cannot be filled immediately will be canceled rather than left on the order book. A post-only order will only be placed if no portion of it fills immediately; this guarantees you will never pay the taker fee on any part of the order that fills.
entailment
def moveOrder(self, orderNumber, rate, amount=None, postOnly=None, immediateOrCancel=None): """Cancels an order and places a new one of the same type in a single atomic transaction, meaning either both operations will succeed or both will fail. Required POST parameters are "orderNumber" and "rate"; you may optionally specify "amount" if you wish to change the amount of the new order. "postOnly" or "immediateOrCancel" may be specified for exchange orders, but will have no effect on margin orders. """ return self._private('moveOrder', orderNumber=orderNumber, rate=rate, amount=amount, postOnly=postOnly, immediateOrCancel=immediateOrCancel)
Cancels an order and places a new one of the same type in a single atomic transaction, meaning either both operations will succeed or both will fail. Required POST parameters are "orderNumber" and "rate"; you may optionally specify "amount" if you wish to change the amount of the new order. "postOnly" or "immediateOrCancel" may be specified for exchange orders, but will have no effect on margin orders.
entailment
def withdraw(self, currency, amount, address, paymentId=None): """Immediately places a withdrawal for a given currency, with no email confirmation. In order to use this method, the withdrawal privilege must be enabled for your API key. Required POST parameters are "currency", "amount", and "address". For XMR withdrawals, you may optionally specify "paymentId".""" return self._private('withdraw', currency=currency, amount=amount, address=address, paymentId=paymentId)
Immediately places a withdrawal for a given currency, with no email confirmation. In order to use this method, the withdrawal privilege must be enabled for your API key. Required POST parameters are "currency", "amount", and "address". For XMR withdrawals, you may optionally specify "paymentId".
entailment
def transferBalance(self, currency, amount, fromAccount, toAccount): """Transfers funds from one account to another (e.g. from your exchange account to your margin account). Required POST parameters are "currency", "amount", "fromAccount", and "toAccount".""" return self._private('transferBalance', currency=currency, amount=amount, fromAccount=fromAccount, toAccount=toAccount)
Transfers funds from one account to another (e.g. from your exchange account to your margin account). Required POST parameters are "currency", "amount", "fromAccount", and "toAccount".
entailment
def marginBuy(self, currencyPair, rate, amount, lendingRate=None): """Places a margin buy order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". You may optionally specify a maximum lending rate using the "lendingRate" parameter. If successful, the method will return the order number and any trades immediately resulting from your order.""" return self._private('marginBuy', currencyPair=currencyPair, rate=rate, amount=amount, lendingRate=lendingRate)
Places a margin buy order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". You may optionally specify a maximum lending rate using the "lendingRate" parameter. If successful, the method will return the order number and any trades immediately resulting from your order.
entailment
def marginSell(self, currencyPair, rate, amount, lendingRate=None): """Places a margin sell order in a given market. Parameters and output are the same as for the marginBuy method.""" return self._private('marginSell', currencyPair=currencyPair, rate=rate, amount=amount, lendingRate=lendingRate)
Places a margin sell order in a given market. Parameters and output are the same as for the marginBuy method.
entailment
def createLoanOffer(self, currency, amount, duration, autoRenew, lendingRate): """Creates a loan offer for a given currency. Required POST parameters are "currency", "amount", "duration", "autoRenew" (0 or 1), and "lendingRate". """ return self._private('createLoanOffer', currency=currency, amount=amount, duration=duration, autoRenew=autoRenew, lendingRate=lendingRate)
Creates a loan offer for a given currency. Required POST parameters are "currency", "amount", "duration", "autoRenew" (0 or 1), and "lendingRate".
entailment
def returnLendingHistory(self, start=0, end=2**32-1, limit=None): """Returns your lending history within a time range specified by the "start" and "end" POST parameters as UNIX timestamps. "limit" may also be specified to limit the number of rows returned. """ return self._private('returnLendingHistory', start=start, end=end, limit=limit)
Returns your lending history within a time range specified by the "start" and "end" POST parameters as UNIX timestamps. "limit" may also be specified to limit the number of rows returned.
entailment
def get_cid(): """Return the currently set correlation id (if any). If no correlation id has been set and ``CID_GENERATE`` is enabled in the settings, a new correlation id is set and returned. FIXME (dbaty): in version 2, just `return getattr(_thread_locals, 'CID', None)` We want the simplest thing here and let `generate_new_cid` do the job. """ cid = getattr(_thread_locals, 'CID', None) if cid is None and getattr(settings, 'CID_GENERATE', False): cid = str(uuid.uuid4()) set_cid(cid) return cid
Return the currently set correlation id (if any). If no correlation id has been set and ``CID_GENERATE`` is enabled in the settings, a new correlation id is set and returned. FIXME (dbaty): in version 2, just `return getattr(_thread_locals, 'CID', None)` We want the simplest thing here and let `generate_new_cid` do the job.
entailment
def generate_new_cid(upstream_cid=None): """Generate a new correlation id, possibly based on the given one.""" if upstream_cid is None: return str(uuid.uuid4()) if getattr(settings, 'CID_GENERATE', False) else None if ( getattr(settings, 'CID_CONCATENATE_IDS', False) and getattr(settings, 'CID_GENERATE', False) ): return '%s, %s' % (upstream_cid, str(uuid.uuid4())) return upstream_cid
Generate a new correlation id, possibly based on the given one.
entailment
def import_from_string(val, setting_name): """ Attempt to import a class from a string representation. """ try: # Nod to tastypie's use of importlib. parts = val.split('.') module_path, class_name = '.'.join(parts[:-1]), parts[-1] module = importlib.import_module(module_path) return getattr(module, class_name) except (ImportError, AttributeError) as e: msg = "Could not import '%s' for Graph Auth setting '%s'. %s: %s." % (val, setting_name, e.__class__.__name__, e) raise ImportError(msg)
Attempt to import a class from a string representation.
entailment
def check_ups_estimated_minutes_remaining(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.2.1.33.1.2.3.0 MIB excerpt An estimate of the time to battery charge depletion under the present load conditions if the utility power is off and remains off, or if it were to be lost and remain off. """ the_helper.add_metric( label=the_helper.options.type, value=the_snmp_value, uom="minutes") the_helper.set_summary("Remaining runtime on battery is {} minutes".format(the_snmp_value))
OID .1.3.6.1.2.1.33.1.2.3.0 MIB excerpt An estimate of the time to battery charge depletion under the present load conditions if the utility power is off and remains off, or if it were to be lost and remain off.
entailment
def check_ups_input_frequency(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.2.1.33.1.3.3.1.2.1 MIB excerpt The present input frequency. """ a_frequency = calc_frequency_from_snmpvalue(the_snmp_value) the_helper.add_metric( label=the_helper.options.type, value=a_frequency, uom='Hz') the_helper.set_summary("Input Frequency is {} Hz".format(a_frequency))
OID .1.3.6.1.2.1.33.1.3.3.1.2.1 MIB excerpt The present input frequency.
entailment
def check_ups_output_current(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.2.1.33.1.4.4.1.3.1 MIB excerpt The present output current. """ a_current = calc_output_current_from_snmpvalue(the_snmp_value) the_helper.add_metric( label=the_helper.options.type, value=a_current, uom='A') the_helper.set_summary("Output Current is {} A".format(a_current))
OID .1.3.6.1.2.1.33.1.4.4.1.3.1 MIB excerpt The present output current.
entailment
def check_ups_alarms_present(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.2.1.33.1.6.1.0 MIB excerpt The present number of active alarm conditions. """ if the_snmp_value != '0': the_helper.add_status(pynag.Plugins.critical) else: the_helper.add_status(pynag.Plugins.ok) the_helper.set_summary("{} active alarms ".format(the_snmp_value))
OID .1.3.6.1.2.1.33.1.6.1.0 MIB excerpt The present number of active alarm conditions.
entailment
def check_xups_bat_capacity(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.4.1.534.1.2.4.0 MIB Excerpt Battery percent charge. """ the_helper.add_metric( label=the_helper.options.type, value=a_snmp_value, uom='%') the_helper.set_summary("Remaining Battery Capacity {} %".format(the_snmp_value))
OID .1.3.6.1.4.1.534.1.2.4.0 MIB Excerpt Battery percent charge.
entailment
def check_xups_env_ambient_temp(the_session, the_helper, the_snmp_value, the_unit=1): """ OID .1.3.6.1.4.1.534.1.6.1.0 MIB Excerpt The reading of the ambient temperature in the vicinity of the UPS or SNMP agent. """ the_helper.add_metric( label=the_helper.options.type, value=the_snmp_value, uom='degree') the_helper.set_summary("Environment Temperature is {} degree".format(the_snmp_value))
OID .1.3.6.1.4.1.534.1.6.1.0 MIB Excerpt The reading of the ambient temperature in the vicinity of the UPS or SNMP agent.
entailment
def check_ressources(sess): """ check the Ressources of the Fortinet Controller all thresholds are currently hard coded. should be fine. """ # get the data cpu_value = get_data(sess, cpu_oid, helper) memory_value = get_data(sess, memory_oid, helper) filesystem_value = get_data(sess, filesystem_oid, helper) helper.add_summary("Controller Status") helper.add_long_output("Controller Ressources - CPU: %s%%" % cpu_value) helper.add_metric("CPU", cpu_value, "0:90", "0:90", "", "", "%%") if int(cpu_value) > 90: helper.status(critical) helper.add_summary("Controller Ressources - CPU: %s%%" % cpu_value) helper.add_long_output("Memory: %s%%" % memory_value) helper.add_metric("Memory", memory_value, "0:90", "0:90", "", "", "%%") if int(memory_value) > 90: helper.add_summary("Memory: %s%%" % memory_value) helper.status(critical) helper.add_long_output("Filesystem: %s%%" % filesystem_value) helper.add_metric("Filesystem", filesystem_value, "0:90", "0:90", "", "", "%%") if int(filesystem_value) > 90: helper.add_summary("Filesystem: %s%%" % filesystem_value) helper.status(critical)
check the Ressources of the Fortinet Controller all thresholds are currently hard coded. should be fine.
entailment
def check_controller(sess): """ check the status of the controller """ controller_operational = get_data(sess, operational_oid, helper) controller_availability = get_data(sess, availability_oid, helper) controller_alarm = get_data(sess, alarm_oid, helper) # Add summary helper.add_summary("Controller Status") # Add all states to the long output helper.add_long_output("Controller Operational State: %s" % operational_states[int(controller_operational)]) helper.add_long_output("Controller Availability State: %s" % availability_states[int(controller_availability)]) helper.add_long_output("Controller Alarm State: %s" % alarm_states[int(controller_alarm)]) # Operational State if controller_operational != "1" and controller_operational != "4": helper.status(critical) helper.add_summary("Controller Operational State: %s" % operational_states[int(controller_operational)]) # Avaiability State if controller_availability != "3": helper.status(critical) helper.add_summary("Controller Availability State: %s" % availability_states[int(controller_availability)]) # Alarm State if controller_alarm == "2": helper.status(warning) helper.add_summary("Controller Alarm State: %s" % alarm_states[int(controller_alarm)]) if controller_alarm == "3" or controller_alarm == "4": helper.status(critical) helper.add_summary("Controller Alarm State: %s" % alarm_states[int(controller_alarm)])
check the status of the controller
entailment
def check_accesspoints(sess): """ check the status of all connected access points """ ap_names = walk_data(sess, name_ap_oid, helper)[0] ap_operationals = walk_data(sess, operational_ap_oid, helper)[0] ap_availabilitys = walk_data(sess, availability_ap_oid, helper)[0] ap_alarms = walk_data(sess, alarm_ap_oid, helper)[0] #ap_ip = walk_data(sess, ip_ap_oid, helper) # no result helper.add_summary("Access Points Status") for x in range(len(ap_names)): ap_name = ap_names[x] ap_operational = ap_operationals[x] ap_availability = ap_availabilitys[x] ap_alarm = ap_alarms[x] # Add all states to the long output helper.add_long_output("%s - Operational: %s - Availabilty: %s - Alarm: %s" % (ap_name, operational_states[int(ap_operational)], availability_states[int(ap_availability)], alarm_states[int(ap_alarm)])) # Operational State if ap_operational != "1" and ap_operational != "4": helper.status(critical) helper.add_summary("%s Operational State: %s" % (ap_name, operational_states[int(ap_operational)])) # Avaiability State if ap_availability != "3": helper.status(critical) helper.add_summary("%s Availability State: %s" % (ap_name, availability_states[int(ap_availability)])) # Alarm State if ap_alarm == "2": helper.status(warning) helper.add_summary("%s Controller Alarm State: %s" % (ap_name, alarm_states[int(ap_alarm)])) if ap_alarm == "3" or ap_alarm == "4": helper.status(critical) helper.add_summary("%s Controller Alarm State: %s" % (ap_name, alarm_states[int(ap_alarm)]))
check the status of all connected access points
entailment
def normal_check(name, status, device_type): """if the status is "ok" in the NORMAL_STATE dict, return ok + string if the status is not "ok", return critical + string""" status_string = NORMAL_STATE.get(int(status), "unknown") if status_string == "ok": return ok, "{} '{}': {}".format(device_type, name, status_string) elif status_string == "unknown": return unknown, "{} '{}': {}".format(device_type, name, status_string) return critical, "{} '{}': {}".format(device_type, name, status_string)
if the status is "ok" in the NORMAL_STATE dict, return ok + string if the status is not "ok", return critical + string
entailment
def probe_check(name, status, device_type): """if the status is "ok" in the PROBE_STATE dict, return ok + string if the status is not "ok", return critical + string""" status_string = PROBE_STATE.get(int(status), "unknown") if status_string == "ok": return ok, "{} '{}': {}".format(device_type, name, status_string) if status_string == "unknown": return unknown, "{} '{}': {}".format(device_type, name, status_string) return critical, "{} '{}': {}".format(device_type, name, status_string)
if the status is "ok" in the PROBE_STATE dict, return ok + string if the status is not "ok", return critical + string
entailment
def add_device_information(helper, session): """ add general device information to summary """ host_name_data = helper.get_snmp_value(session, helper, DEVICE_INFORMATION_OIDS['oid_host_name']) product_type_data = helper.get_snmp_value(session, helper, DEVICE_INFORMATION_OIDS['oid_product_type']) service_tag_data = helper.get_snmp_value(session, helper, DEVICE_INFORMATION_OIDS['oid_service_tag']) helper.add_summary('Name: {} - Typ: {} - Service tag: {}'.format( host_name_data, product_type_data, service_tag_data))
add general device information to summary
entailment
def process_status(self, helper, session, check): """"process a single status""" snmp_result_status = helper.get_snmp_value(session, helper, DEVICE_GLOBAL_OIDS['oid_' + check]) if check == "system_lcd": helper.update_status(helper, normal_check("global", snmp_result_status, "LCD status")) elif check == "global_storage": helper.update_status(helper, normal_check("global", snmp_result_status, "Storage status")) elif check == "system_power": helper.update_status(helper, self.check_system_power_status(snmp_result_status)) elif check == "global_system": helper.update_status(helper, normal_check("global", snmp_result_status, "Device status"))
process a single status
entailment
def process_states(self, helper, session, check): """process status values from a table""" snmp_result_status = helper.walk_snmp_values(session, helper, DEVICE_STATES_OIDS["oid_" + check], check) snmp_result_names = helper.walk_snmp_values(session, helper, DEVICE_NAMES_OIDS["oid_" + check], check) for i, _result in enumerate(snmp_result_status): if check == "power_unit": helper.update_status( helper, normal_check(snmp_result_names[i], snmp_result_status[i], "Power unit")) elif check == "drive": helper.update_status( helper, self.check_drives(snmp_result_names[i], snmp_result_status[i])) elif check == "power_unit_redundancy": helper.update_status( helper, self.check_power_unit_redundancy(snmp_result_names[i], snmp_result_status[i])) elif check == "chassis_intrusion": helper.update_status( helper, normal_check(snmp_result_names[i], snmp_result_status[i], "Chassis intrusion sensor")) elif check == "cooling_unit": helper.update_status( helper, normal_check(snmp_result_names[i], snmp_result_status[i], "Cooling unit"))
process status values from a table
entailment
def process_temperature_sensors(helper, session): """process the temperature sensors""" snmp_result_temp_sensor_names = helper.walk_snmp_values( session, helper, DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_location'], "temperature sensors") snmp_result_temp_sensor_states = helper.walk_snmp_values( session, helper, DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_status'], "temperature sensors") snmp_result_temp_sensor_values = helper.walk_snmp_values( session, helper, DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_reading'], "temperature sensors") for i, _result in enumerate(snmp_result_temp_sensor_states): helper.update_status( helper, probe_check(snmp_result_temp_sensor_names[i], snmp_result_temp_sensor_states[i], "Temperature sensor")) if i < len(snmp_result_temp_sensor_values): helper.add_metric(label=snmp_result_temp_sensor_names[i] + " -Celsius-", value=float(snmp_result_temp_sensor_values[i]) / 10)
process the temperature sensors
entailment
def check_drives(drivename, drivestatus): """ check the drive status """ return DISK_STATES[int(drivestatus)]["icingastatus"], "Drive '{}': {}".format( drivename, DISK_STATES[int(drivestatus)]["result"])
check the drive status
entailment
def check_power_unit_redundancy(power_unit_name_data, power_unit_redundancy_data): """ check the status of the power units """ return (POWER_UNIT_REDUNDANCY_STATE[int(power_unit_redundancy_data)]["icingastatus"], "Power unit '{}' redundancy: {}".format(power_unit_name_data, POWER_UNIT_REDUNDANCY_STATE[ int(power_unit_redundancy_data)] ["result"]))
check the status of the power units
entailment
def check_global_status(flag, name, oid): """ check a global status check_global_status(True, "Global Storage", '.1.3.6.1.4.1.232.3.1.3.0') """ # only check the status, if the "no" flag is not set if flag: # get the data via snmp myData = get_data(sess, oid, helper) data_summary_output, data_long_output = state_summary(myData, name, normal_state, helper) add_output(data_summary_output, data_long_output, helper)
check a global status check_global_status(True, "Global Storage", '.1.3.6.1.4.1.232.3.1.3.0')
entailment
def check_server_power(): """ Check if the server is powered on Skip this check, if the --noPowerState is set """ if power_state_flag: power_state = get_data(sess, oid_power_state, helper) power_state_summary_output, power_state_long_output = state_summary(power_state, 'Server power', server_power_state, helper, server_power_state[3]) add_output(power_state_summary_output, power_state_long_output, helper)
Check if the server is powered on Skip this check, if the --noPowerState is set
entailment