Example #1
0
    def create(self, device):
        """ Returns boolean indicating device creation success. """

        try:
            svc = json.dumps({
                "services": [{
                    "resource": "devm",
                    "apikey": self.service,
                    "entity_type": 'device'
                }]
            })
            response = requests.post(self.baseUrl + '/services',
                                     headers=self._headers,
                                     data=svc)
            if not (response.status_code == 409 or
                    (response.status_code >= 200
                     and response.status_code < 300)):
                error = "Failed to configure ingestion subsystem: service creation failed"
                raise HTTPRequestError(500, error)
        except requests.ConnectionError:
            raise HTTPRequestError(
                500, "Cannot reach ingestion subsystem (service)")

        try:
            response = requests.post(
                self.baseUrl + '/devices',
                headers=self._headers,
                data=json.dumps({'devices': [self.__get_config(device)]}))
            if not (response.status_code >= 200
                    and response.status_code < 300):
                error = "Failed to configure ingestion subsystem: device creation failed"
                raise HTTPRequestError(500, error)
        except requests.ConnectionError:
            raise HTTPRequestError(
                500, "Cannot reach ingestion subsystem (device)")
Example #2
0
    def create(self, device_id, device_type='device'):
        """ Returns subscription id on success. """

        try:
            svc = json.dumps({
                "entities": [{
                    "type": device_type,
                    "isPattern": "false",
                    "id": device_id
                }],
                "reference":
                self.targetUrl,
                "duration":
                "P10Y",
                "notifyConditions": [{
                    "type": "ONCHANGE"
                }]
            })
            response = requests.post(self.baseUrl,
                                     headers=self._headers,
                                     data=svc)
            if not (response.status_code == 409 or
                    (response.status_code >= 200
                     and response.status_code < 300)):
                raise HTTPRequestError(500, "Failed to create subscription")

            # return the newly created subs
            reply = response.json()
            return reply['subscribeResponse']['subscriptionId']
        except ValueError:
            LOGGER.error('Failed to create subscription')
            raise HTTPRequestError(500, "Failed to create subscription")
        except requests.ConnectionError:
            raise HTTPRequestError(500, "Broker is not reachable")
Example #3
0
    def remove(self, subsId):
        """ Returns boolean indicating subscription removal success. """

        try:
            response = requests.delete(self.baseUrl + '/' + subsId,
                                       headers=self._noBodyHeaders)
            if not (200 <= response.status_code < 300):
                raise HTTPRequestError(500, "Failed to remove subscription")
        except requests.ConnectionError:
            raise HTTPRequestError(500, "Broker is not reachable")
Example #4
0
def parse_payload(request, schema):
    try:
        content_type = request.headers.get('Content-Type')
        if (content_type is None) or (content_type != "application/json"):
            raise HTTPRequestError(400, "Payload must be valid JSON, and Content-Type set accordingly")
        json_payload = json.loads(request.data)
    except ValueError:
        raise HTTPRequestError(400, "Payload must be valid JSON, and Content-Type set accordingly")

    data, errors = schema.load(json_payload)
    if errors:
        results = {'message':'failed to parse input', 'errors': errors}
        raise HTTPRequestError(400, results)
    return data, json_payload
Example #5
0
    def remove(self, deviceid):
        """ Returns boolean indicating device removal success. """

        try:
            response = requests.delete(self.baseUrl + '/devices/' + deviceid,
                                       headers=self._noBodyHeaders)
            if 200 <= response.status_code < 300:
                response = requests.delete('%s/%s' % (self.orionUrl, deviceid),
                                           headers=self._noBodyHeaders)
                if not (200 <= response.status_code < 300):
                    error = "Failed to configure ingestion subsystem: device removal failed"
                    raise HTTPRequestError(500, error)
        except requests.ConnectionError:
            raise HTTPRequestError(500, "Cannot reach ingestion subsystem")
def assert_device_relation_exists(device_id, template_id):
    try:
        return DeviceTemplateMap.query.filter_by(
            device_id=device_id, template_id=template_id).one()
    except sqlalchemy.orm.exc.NoResultFound:
        raise HTTPRequestError(
            404, "Device %s is not associated with template %s" %
            (device_id, template_id))
def load_attrs(attr_list, parent_template, base_type, db):
    for attr in attr_list:
        entity, errors = attr_schema.load(attr)
        if errors:
            results = {'message': 'failed to parse attr', 'errors': errors}
            raise HTTPRequestError(400, results)

        orm_attr = base_type(template=parent_template, **entity)
        db.session.add(orm_attr)
Example #8
0
def init_tenant_context(request, db):
    try:
        token = request.headers['authorization']
    except KeyError:
        raise HTTPRequestError(401, "No authorization token has been supplied")

    tenant = get_allowed_service(token)
    init_tenant(tenant, db)
    return tenant
Example #9
0
    def create_update_device(self, device, is_update=True):
        target_url = "%s/%s/attrs?type=device" % (self.baseUrl, device['id'])
        body = json.dumps(OrionHandler.parse_device(device, not is_update))
        if is_update == False:
            target_url = self.baseUrl

        try:
            LOGGER.info("about to create device in ctx broker")
            LOGGER.debug("%s", body)
            response = requests.post(target_url,
                                     headers=self._headers,
                                     data=body)
            if response.status_code >= 200 and response.status_code < 300:
                LOGGER.debug("Broker update successful")
            else:
                LOGGER.info("Failed to update ctx broker: %d",
                            response.status_code)
                try:
                    LOGGER.debug("%s", response.json())
                except Exception as e:
                    LOGGER.error(e)
        except requests.ConnectionError:
            raise HTTPRequestError(500, "Broker is not reachable")
def assert_template_exists(template_id):
    try:
        return DeviceTemplate.query.filter_by(id=template_id).one()
    except sqlalchemy.orm.exc.NoResultFound:
        raise HTTPRequestError(404, "No such template: %s" % template_id)
def assert_device_exists(device_id):
    try:
        return Device.query.filter_by(id=device_id).one()
    except sqlalchemy.orm.exc.NoResultFound:
        raise HTTPRequestError(404, "No such device: %s" % device_id)
def handle_consistency_exception(error):
    # message = error.message.replace('\n','')
    message = re.sub(r"(^\(.*?\))|\n", "", error.message)
    raise HTTPRequestError(400, message)