Beispiel #1
0
    def init_cse_base(self):
        # get config values
        onem2m_config = self.config["onem2m"]
        self._cse_base = cse_base_name = onem2m_config.get(
            "cse_base", "onem2m")

        # TODO(rst): check later
        # node_link = 'dummy'

        # cse type
        cse_type = onem2m_config.get("cse_type")
        try:
            cse_type = getattr(CSETypeIDE,
                               str(cse_type).replace("-", "_").upper())
        except (AttributeError, TypeError, ValueError):
            raise ConfigurationError("Invalid value for 'cse_type': %s" %
                                     (cse_type, ))
        cse_type = CSETypeIDE(cse_type)

        # cse id
        try:
            self._rel_cse_id = "/" + onem2m_config["cse_id"]
        except KeyError:
            raise ConfigurationError("Missing configuration key: cse_id")

        # sp id
        try:
            self._abs_cse_id = "//" + onem2m_config["sp_id"] + self._rel_cse_id
        except KeyError:
            raise ConfigurationError("Missing configuration key: sp_id")

        # time
        now = datetime_now()

        # resource
        cse_base = CSEBase(resourceName=cse_base_name,
                           resourceID='cb0',
                           parentID=None,
                           resourceType=model.ResourceTypeE['CSEBase'],
                           creationTime=now,
                           lastModifiedTime=now,
                           cseType=cse_type,
                           CSE_ID=self._rel_cse_id,
                           supportedResourceType=[
                               model.ResourceTypeE[x.typename]
                               for x in self.controller_classes.keys()
                           ],
                           pointOfAccess=[],
                           path=cse_base_name)
        db_session = self._api.start_onem2m_session()

        try:
            result = db_session.store(cse_base)
        except Exception as error:
            self.logger.exception("Initialization error")
            db_session.rollback()
            raise error
        else:
            db_session.commit()
            return result
    def _init(self):
        try:
            onem2m_config = self.config["onem2m"]
        except KeyError:
            raise ConfigurationError("No onem2m config part!")

        # cse id
        try:
            self.cse_id = "/" + onem2m_config["cse_id"]
        except KeyError:
            raise ConfigurationError("Missing configuration key: cse_id")

        # cse type
        cse_type = onem2m_config.get("cse_type")
        try:
            cse_type = getattr(CSETypeIDE,
                               str(cse_type).replace("-", "_").upper())
        except (AttributeError, TypeError, ValueError):
            raise ConfigurationError("Invalid value for 'cse_type': %s" %
                                     (cse_type, ))
        self.cse_type = CSETypeIDE(cse_type)

        self.cse_base = onem2m_config.get("cse_base", "onem2m")
        self.labels = self.config.get("labels", [])

        self.__registrations = []
        self._initialized()
    def _start(self):
        servers = []
        additional_hostnames = self.config["global"].get(
            "additional_hostnames") or []

        if not isinstance(additional_hostnames, list):
            raise ConfigurationError("additional_hostnames is not a list")

        for endpoint in self.config.get("connectors", []):
            interface = endpoint["interface"]
            port = endpoint["port"]
            host = endpoint["host"]
            keyfile = endpoint.get("key")
            certfile = endpoint.get("crt")
            is_wan = endpoint.get("is_wan")

            if not host:
                host = self._guess_host(interface)
                self.logger.debug("No host specified for connector on '%s'. "
                                  "Guessing %s", interface, host)
                connectors = self._guess_alternatives(interface)
            else:
                connectors = []

            is_coaps = keyfile and certfile

            if is_coaps:
                scheme = "coaps"
                ssl_args = {"keyfile": keyfile, "certfile": certfile}
            else:
                scheme = "coap"
                ssl_args = None

            base_uri = "%s://%s:%s" % (scheme, host, port)
            connectors = [base_uri] + ["%s://%s:%s" % (scheme, host, port)
                                       for host in connectors]

            for hostname in additional_hostnames:
                alternative = "%s://%s" % (scheme, hostname, )
                if urlparse(alternative).port in (None, ''):
                    alternative = "%s:%s" % (alternative, port)
                connectors.append(alternative)

            if endpoint.is_wan is None:
                # TODO: guess if an interface is a WAN interface
                raise NotImplementedError()
            connector = Connector(base_uri, connectors, is_wan)

            servers.append(CoapServer(self.api.handle_request,
                                      connector=connector, address=interface,
                                      server_port=port, ssl_args=ssl_args))

            self.api.register_connector(connector)

        rack = self.__rack = GEventServerRack(servers)

        rack.start()
        self._started()
    def _handle_remote_cse_update_expiration_time(self,
                                                  remote_cse,
                                                  instance=None):
        """ Sends a update request for the RemoteCSE resource.
            Retrieves resource data afterwards.

            @return: RemoteCSE instance representing the created resource.
        """
        try:
            remote_cse_id = "/" + remote_cse["cse_id"]
        except KeyError:
            raise ConfigurationError('Missing parameter (cse_id) in %s' %
                                     remote_cse)
        # cse type
        remote_cse_type = remote_cse.get("cse_type")
        try:
            remote_cse_type = getattr(
                CSETypeIDE,
                str(remote_cse_type).replace("-", "_").upper())
        except (AttributeError, TypeError, ValueError):
            raise ConfigurationError("Invalid value for 'cse_type': %s" %
                                     (remote_cse_type, ))

        def _update_own_remote_cse_remotely():
            cse = RemoteCSE(expirationTime=instance.expirationTime)
            # todo: need to check format here?
            to = remote_cse_id + "/" + instance.resourceID
            request = OneM2MRequest(OneM2MOperation.update,
                                    to,
                                    fr=self.originator,
                                    ty=RemoteCSE,
                                    pc=cse)
            return self.api.send_onem2m_request(request)

        try:
            _update_own_remote_cse_remotely().get()
        except CSETargetNotReachable as e_not_reachable:
            raise e_not_reachable
        except OneM2MErrorResponse as error_response:
            if error_response.response_status_code == STATUS_CONFLICT:
                raise CSEConflict()
        else:
            pass
Beispiel #5
0
 def __subscribe(remote_cse):
     try:
         remote_cse_id = "/" + remote_cse["cse_id"]
     except KeyError:
         raise ConfigurationError('Missing parameter (cse_id) in %s' %
                                  remote_cse)
     subs = Subscription(notificationURI=self.api.get_onem2m_endpoints())
     to = remote_cse_id + "/" + remote_cse.get("cse_base", "onem2m")
     request = OneM2MRequest(OneM2MOperation.create, to,
                             self.originator,
                             ty=Subscription,
                             pc=subs)
     return self.api.send_onem2m_request(request)
def load_db_module(config, **override_params):
    try:
        dbconfig = config["database"]
    except KeyError:
        raise ConfigurationError("db configuration is missing")

    try:
        db_fq_name = dbconfig["driver"]
    except KeyError:
        raise ConfigurationError(
            "db configuration is missing a 'driver' entry")

    package, _, clsname = db_fq_name.rpartition(".")

    if not package or not clsname:
        raise ConfigurationError("Invalid DB driver string")

    module = import_module(package)

    cls = getattr(module, clsname)

    dbconfig.update(override_params)

    return cls(dbconfig)
    def _handle_remote_cse_delete(self, remote_cse):
        """ Sends a delete request for the RemoteCSE resource.
        """
        try:
            remote_cse_id = "/" + remote_cse["cse_id"]
        except KeyError:
            raise ConfigurationError('Missing parameter (cse_id) in %s' %
                                     remote_cse)
        remote_cse_base = remote_cse.get("cse_base", "onem2m")

        def _delete_remote_cse_base():
            to = remote_cse_id + '/' + remote_cse_base + self.cse_id
            request = OneM2MRequest(OneM2MOperation.delete, to,
                                    self.originator)
            return self.api.send_onem2m_request(request)

        _delete_remote_cse_base()
    def __init__(self, *args, **kw):
        super(GEventSQLDBAdapter, self).__init__(*args, **kw)

        self._shelves = set()
        self._mapped_column_names = {}

        try:
            driver = self.config["backend"]
            connectionstring = self.config["connectionstring"]
        except KeyError as e:
            raise ConfigurationError("DB configuration key missing: %s" % (e,))

        poolsize = self.config.get("concurrency", DEFAULT_CONCURRENCY)
        if driver == "sqlite3" and poolsize != 1:
            self.logger.warn(
                "Limiting DB Connection pool size to 1 for sqlite DB")
            poolsize = 1

        try:
            self._pool = DBPool(connectionstring=connectionstring,
                                poolsize=poolsize,
                                modulename=driver)
        except Exception as e:
            self.logger.debug("DB module loading failed", exc_info=True)
            raise DBError("Failed to load database backend driver '%s': %s" %
                          (driver, e))

        if driver == "sqlite3":
            self.__sql_creator = SQLiteSQLCreator()
        else:
            self.__sql_creator = SQLCreator()

        # this is necessary for generating inserts with mapped column names
        # (that contain e.g. "-")
        self.__sql_creator.mapped_column_names = self._mapped_column_names

        self._map_types()

        if self._pool.paramstyle not in ("qmark", "format", "quote"):
            raise NotImplementedError("paramstyle", self._pool.paramstyle)
def prepare_config(config):
    try:
        global_config = config["global"]
    except KeyError:
        global_config = config["global"] = {}

    try:
        etsi_version = global_config["etsi_version"]
    except KeyError:
        etsi_version = global_config["etsi_version"] = LATEST_VERSION

    try:
        etsi_compatibility = global_config["etsi_compatibility"]
    except KeyError:
        global_config["etsi_compatibility"] = etsi_version
    else:
        if etsi_compatibility > etsi_version:
            raise ConfigurationError("'etsi_version' (%s) must be greater or "
                                     "equal to 'etsi_compatibility' (%s)" %
                                     (etsi_version, etsi_compatibility))

    global_config.setdefault("ignore_extra_attributes", False)

    return config
    def _handle_remote_cse(self, remote_cse):
        """ Sends a create request for the RemoteCSE resource.
            Retrieves resource data afterwards.

            @return: RemoteCSE instance representing the created resource.
        """

        try:
            remote_cse_id = "/" + remote_cse["cse_id"]
        except KeyError:
            raise ConfigurationError('Missing parameter (cse_id) in %s' %
                                     remote_cse)

        # cse type
        remote_cse_type = remote_cse.get("cse_type")
        try:
            remote_cse_type = getattr(
                CSETypeIDE,
                str(remote_cse_type).replace("-", "_").upper())
        except (AttributeError, TypeError, ValueError):
            raise ConfigurationError("Invalid value for 'cse_type': %s" %
                                     (remote_cse_type, ))
        remote_cse_type = CSETypeIDE(remote_cse_type)

        remote_cse_base = remote_cse.get("cse_base", "onem2m")

        remote_cse_uri = remote_cse_id + '/' + remote_cse_base

        self.logger.info("registering %s at %s", self.cse_id, remote_cse_id)

        def _create_own_remote_cse_remotely():
            endpoints = self.api.get_onem2m_endpoints()

            from openmtc.util import datetime_the_future

            # init RemoteCSE object
            cse = RemoteCSE(resourceName=self.cse_id[1:],
                            labels=self.labels,
                            cseType=self.cse_type,
                            pointOfAccess=endpoints,
                            CSEBase=self.cse_base,
                            CSE_ID=self.cse_id,
                            requestReachability=bool(len(endpoints)),
                            expirationTime=datetime_the_future(
                                self.get_offset))
            if remote_cse.get('own_poa'):
                cse.pointOfAccess = remote_cse.get('own_poa')

            request = OneM2MRequest(OneM2MOperation.create,
                                    remote_cse_uri,
                                    self.originator,
                                    ty=RemoteCSE,
                                    pc=cse)

            return self.api.send_onem2m_request(request)

        def _retrieve_remote_cse_base():
            request = OneM2MRequest(OneM2MOperation.retrieve,
                                    remote_cse_uri,
                                    self.originator,
                                    ty=CSEBase)
            return self.api.send_onem2m_request(request)

        def _create_remote_cse_locally(cse_base):
            cse = RemoteCSE(resourceName=remote_cse_id[1:],
                            CSEBase=remote_cse_base,
                            CSE_ID=remote_cse_id,
                            cseType=remote_cse_type,
                            pointOfAccess=cse_base.pointOfAccess)
            cse.pointOfAccess = remote_cse.get('poa')

            request = OneM2MRequest(OneM2MOperation.create,
                                    self.cse_base,
                                    self.originator,
                                    ty=RemoteCSE,
                                    pc=cse)

            return self.api.handle_onem2m_request(request)

        try:
            instance = _create_own_remote_cse_remotely().get().content

            def _update_function(updated_instance):
                self._handle_remote_cse_update_expiration_time(
                    remote_cse, updated_instance)

            self.refresher.start(instance, send_update=_update_function)
        except CSETargetNotReachable as e_not_reachable:
            # TODO(rst): print error message
            raise e_not_reachable
        except OneM2MErrorResponse as error_response:
            if error_response.response_status_code == STATUS_CONFLICT:
                # TODO(rst): handle conflict here
                raise CSEConflict()
        else:
            retrieved_cse_base = _retrieve_remote_cse_base().get().content
            if retrieved_cse_base is None:
                raise CSENotFound()
            _create_remote_cse_locally(retrieved_cse_base).get()
Beispiel #11
0
    def __init__(self, issuer, request_dict, context, logger):

        self.logger = logger
        self.issuer = issuer
        self.context = context

        self.logger.info("request dict is " + str(request_dict))

        if "method" in request_dict:
            # if request_dict.has_key("method"):
            self.method = request_dict[
                "method"]  # create, update, retrieve, update

        else:
            raise IntentError("Extra field method is not present")
            return

        try:
            self.method = request_dict[
                "method"]  # create, update, retrieve, update
            self.logger.info("method: %s", self.method)
        except KeyError:
            raise ConfigurationError("Extra field method is not present")

        if request_dict.has_key("path"):
            self.path = request_dict.get(
                "path"
            )  # http://something, e.g. "http://some.host:1234/m2m/applications"
            self.logger.info("path: " + str(self.path))
        else:
            raise IntentError("Extra field path is not present")
            return

        if request_dict.has_key("content_type"):
            self.content_type = request_dict.get(
                "content_type")  # application/json
        else:
            self.logger.info(
                "Extra field content_type not provided, default value application/json used"
            )
            self.content_type = "application/json"
        self.logger.info("content_type: " + str(self.content_type))

        if request_dict.has_key("requestId"):
            self.intentRequestId = request_dict.get("requestId")
            self.logger.info("requestId is " + self.intentRequestId)
        else:
            self.logger.info("Extra field requestId is not present")

        if request_dict.has_key("replyAction"):
            self.replyAction = request_dict.get("replyAction")
            self.logger.info("replyAction: " + str(self.replyAction))
        else:
            raise IntentError("Extra field replyAction is not present")
            return
        if request_dict.has_key("searchStrings"):
            self.searchStrings = request_dict.get("searchStrings")
            self.logger.info("searchStrings: " + str(self.searchStrings))
        else:
            self.logger.info("no searchStrings present")

        if request_dict.has_key("requestCategory"):
            self.requestCategory = request_dict.get("requestCategory")
            self.logger.info("requestCategory: " + str(self.requestCategory))
        else:
            self.logger.info("no requestCategory present, assuming default 7")
            self.requestCategory = 7

        if request_dict.has_key("tolerantDelay"):
            self.tolerantDelay = request_dict.get("tolerantDelay")
            self.logger.info("tolerantDelay: " + str(self.tolerantDelay))
        else:
            self.logger.info("no tolerantDelay present, assuming default 30s")
            self.tolerantDelay = 30

        if request_dict.has_key("contactURI"):
            self.contactURI = request_dict.get("contactURI")
            self.logger.info("contactURI: " + str(self.contactURI))
        else:
            self.logger.info("no contactURI present")

        if request_dict.has_key("content"):
            self.content = request_dict.get("content")
            self.logger.info("content: " + str(self.content))
        else:
            self.logger.info("Extra field content was not provided")

        if len(self.content) is 0:
            self.logger.info("content is empty")
Beispiel #12
0
    def _start(self):
        servers = []
        additional_hostnames = self.config["global"].get(
            "additional_hostnames", [])

        if not isinstance(additional_hostnames, list):
            raise ConfigurationError("additional_hostnames is not a list")

        require_auth = self.config["global"].get("require_auth", True)
        for endpoint in self.config.get("connectors", []):
            interface = endpoint["interface"]
            port = endpoint["port"]
            host = endpoint["host"]
            keyfile = endpoint.get("key")
            certfile = endpoint.get("crt")

            if not host:
                host = self._guess_host(interface)
                self.logger.info(
                    "No host specified for connector on '%s'. "
                    "Guessing %s", interface, host)
                connectors = self._guess_alternatives(interface)
            else:
                connectors = []

            is_https = keyfile and certfile

            scheme = "https" if is_https else "http"
            base_uri = "%s://%s:%s" % (scheme, host, port)
            connectors = [
                "%s://%s:%s" % (scheme, host, port) for host in connectors
            ]

            default_port = getservbyname(scheme)

            if port == default_port:
                connectors.append("%s://%s" % (scheme, host))

            for hostname in additional_hostnames:
                alternative = "%s://%s" % (scheme, hostname)
                parsed_alternative = urlparse(alternative)
                alternative_port = parsed_alternative.port
                if alternative_port in (None, ''):
                    alternative_port = port
                    alternative = "%s:%s" % (alternative, port)
                connectors.append(alternative)

                if alternative_port == default_port:
                    connectors.append("%s://%s" %
                                      (scheme, parsed_alternative.hostname))

            if endpoint.is_wan is None:
                # TODO: guess if an interface is a WAN interface
                raise NotImplementedError()
            connector = Connector(base_uri, connectors, endpoint.is_wan)

            application = OpenMTCWSGIApplication(self.api.handle_request,
                                                 connector=connector,
                                                 server_address=interface,
                                                 require_auth=require_auth)

            if is_https:
                servers.append(
                    WSGIServer((interface, port),
                               application,
                               environ={'SERVER_NAME': 'openmtc.local'},
                               keyfile=keyfile,
                               certfile=certfile))
            else:
                servers.append(
                    WSGIServer((interface, port),
                               application,
                               environ={'SERVER_NAME': 'openmtc.local'}))

            self.api.register_connector(connector)

        rack = self.__rack = GEventServerRack(servers)

        rack.start()

        self._started()
    def _start(self):
        servers = []
        prefer_xml = bool(self.config["global"].get("prefer_xml"))
        additional_hostnames = self.config["global"].get(
            "additional_hostnames") or []

        if not isinstance(additional_hostnames, list):
            raise ConfigurationError("additional_hostnames is not a list")

        pretty = self.config.get("pretty_print", "auto")

        if pretty and pretty is not True:
            try:
                pretty = pretty.lower()
            except AttributeError:
                pretty = True
            else:
                if pretty == "auto":
                    pretty = None
                else:
                    pretty = True

        require_auth = self.config["global"].get("require_auth", True)

        for endpoint in self.config.get("endpoints") or []:
            interface = endpoint.get("interface") or ""
            port = endpoint["port"]
            personality = endpoint["personality"]
            host = endpoint.get("host")
            keyfile = endpoint.get("key")
            certfile = endpoint.get("crt")

            if not host:
                host = self._guess_host(interface)
                self.logger.info(
                    "No host specified for %s endpoint on '%s'. Guessing %s",
                    personality, interface, host)
                alternatives = self._guess_alternatives(interface)
            else:
                alternatives = []

            application = SCLWSGIApplication(
                self.api.handle_request_indication,
                base_uri=None,
                server_address=interface,
                reference_point=personality,
                prefer_xml=prefer_xml,
                require_auth=require_auth,
                etsi_version_v2=self.etsi_version_v2,
                etsi_compatibility=self.etsi_compatibility_needed)

            if keyfile and certfile:
                scheme = "https"
                base_uri = application.base_uri = "https://%s:%s" % (host,
                                                                     port)
                servers.append(
                    WSGIServer((interface, port),
                               application,
                               keyfile=keyfile,
                               certfile=certfile))
            else:
                scheme = "http"
                base_uri = application.base_uri = "http://%s:%s" % (host, port)
                servers.append(WSGIServer((interface, port), application))

            self.api.register_endpoint(personality, base_uri)

            alternatives = [
                "%s://%s:%s" % (scheme, host, port) for host in alternatives
            ]

            default_port = getservbyname(scheme)

            if port == default_port:
                alternatives.append("%s://%s" % (scheme, host))

            if additional_hostnames:
                for hostname in additional_hostnames:
                    alternative = "%s://%s" % (scheme, hostname)
                    parsed_alternative = urlparse(alternative)
                    alternative_port = parsed_alternative.port
                    if alternative_port in (None, ''):
                        alternative_port = port
                        alternative = "%s:%s" % (alternative, port)
                    alternatives.append(alternative)

                    if alternative_port == default_port:
                        alternatives.append(
                            "%s://%s" % (scheme, parsed_alternative.hostname))

            if alternatives:
                self.api.register_alternative_endpoints(
                    personality, alternatives)

        rack = self.__rack = GEventServerRack(servers)

        rack.start()

        self._started()