Exemple #1
0
def _execute_register(device: dict, created: str, log: list):
    """
    Tries to POST the device and updates the `device` dict with the resource from the database; if the device could
    not be uploaded the `device` param will contain the database version of the device, not the inputting one. This is
    because the majority of the information of a device is immutable (in concrete the fields used to compute
    the ETAG).

    :param device: Inputting device. It is replaced (keeping the reference) with the db version.
    :param created: Set the _created value to be the same for the device as for the register
    :param log: A log where to append the resulting device if execute_register has been successful
    :raise InnerRequestError: any internal error in the POST that is not about the device already existing.
    """
    device['hid'] = 'dummy'
    new = True
    try:
        if created:
            device['created'] = created
        db_device = execute_post_internal(Naming.resource(device['@type']), device)
    except InnerRequestError as e:
        new = False
        try:
            db_device = _get_existing_device(e)
            # We add a benchmark todo move to another place?
            device['_id'] = db_device['_id']
            ComponentDomain.benchmark(device)
        except DeviceNotFound:
            raise e
    else:
        log.append(db_device)
    device.clear()
    device.update(db_device)
    device['new'] = new  # Note that the device is 'cleared' before
    return db_device
Exemple #2
0
 def exec_hard_drive_events(self, event_log, events):
     for i, event in events:
         event['device'] = self.components[i]['_id']
         self.set_created_conditionally(event)
         event_log.append(
             execute_post_internal(Naming.resource(event['@type']), event))
         event.update(event_log[-1])
Exemple #3
0
def transfer_property(receives: list):
    for receive in receives:
        if receive['automaticallyAllocate']:
            allocate_type = DeviceEventDomain.new_type('Allocate')
            a = execute_post_internal(Naming.resource(allocate_type), {
                '@type': allocate_type,
                'to': receive['receiver'],
                'devices': receive['devices']
            })
            receive['_created'] = receive['_updated'] = a['_created'] + datetime.timedelta(milliseconds=1)
Exemple #4
0
def _execute_register(device: dict, created: str, log: list):
    """
    Tries to POST the device and updates the `device` dict with the resource from the database; if the device could
    not be uploaded the `device` param will contain the database version of the device, not the inputting one. This is
    because the majority of the information of a device is immutable (in concrete the fields used to compute
    the ETAG).

    :param device: Inputting device. It is replaced (keeping the reference) with the db version.
    :param created: Set the _created value to be the same for the device as for the register
    :param log: A log where to append the resulting device if execute_register has been successful
    :raise InnerRequestError: any internal error in the POST that is not about the device already existing.
    """
    new = True
    try:
        if created:
            device['created'] = created
        db_device = execute_post_internal(Naming.resource(device['@type']),
                                          device)
    except InnerRequestError as e:
        new = False
        try:
            db_device = _get_existing_device(e)
            # We add a benchmark todo move to another place?
            device['_id'] = db_device['_id']
            ComponentDomain.benchmark(device)
            external_synthetic_id_fields = pick(
                device, *DeviceDomain.external_synthetic_ids)
            # If the db_device was a placeholder
            # We want to override it with the new device
            if db_device.get('placeholder', False):
                # Eve do not generate defaults from sub-resources
                # And we really need the placeholder default set, specially when
                # discovering a device
                device['placeholder'] = False
                # We create hid when we validate (wrong thing) so we need to manually set it here as we won't
                # validate in this db operation
                device['hid'] = DeviceDomain.hid(device['manufacturer'],
                                                 device['serialNumber'],
                                                 device['model'])
                DeviceDomain.update_one_raw(db_device['_id'], {'$set': device})
            elif not is_empty(external_synthetic_id_fields):
                # External Synthetic identifiers are not intrinsically inherent
                # of devices, and thus can be added later in other Snapshots
                # Note that the device / post and _get_existing_device() have already validated those ids
                DeviceDomain.update_one_raw(
                    db_device['_id'], {'$set': external_synthetic_id_fields})
        except DeviceNotFound:
            raise e
    else:
        log.append(db_device)
    device.clear()
    device.update(db_device)
    device['new'] = new  # Note that the device is 'cleared' before
    return db_device
Exemple #5
0
def transfer_property(receives: list):
    for receive in receives:
        if receive['automaticallyAllocate']:
            allocate_type = DeviceEventDomain.new_type('Allocate')
            a = execute_post_internal(
                Naming.resource(allocate_type), {
                    '@type': allocate_type,
                    'to': receive['receiver'],
                    'devices': receive['devices']
                })
            receive['_created'] = receive['_updated'] = a[
                '_created'] + datetime.timedelta(milliseconds=1)
Exemple #6
0
 def register(self, event_log: list):
     with suppress(NoDevicesToProcess):
         register = {
             '@type': DeviceEventDomain.new_type('Register'),
             'device': self.device,
             'components': self.components
         }
         self.set_created_conditionally(register)
         event_log.append(execute_post_internal(Naming.resource(register['@type']), register))
     for device in [self.device] + self.components:
         if 'hid' not in device and 'pid' not in device:
             self._append_unsecured(device, 'model')
         elif 'pid' in device:
             self._append_unsecured(device, 'pid')
Exemple #7
0
 def register(self, event_log: list):
     with suppress(NoDevicesToProcess):
         register = {
             '@type': DeviceEventDomain.new_type('Register'),
             'device': self.device,
             'components': self.components
         }
         self.set_created_conditionally(register)
         event_log.append(
             execute_post_internal(Naming.resource(register['@type']),
                                   register))
     for device in [self.device] + self.components:
         if 'hid' not in device and 'pid' not in device:
             self._append_unsecured(device, 'model')
         elif 'pid' in device:
             self._append_unsecured(device, 'pid')
Exemple #8
0
    def process(self) -> list:
        """
        Executes all events stored.

        First execute the inserts so the stored devices can get the _id and then executes the rest of events.
        :return: A list of the executed events
        """
        log = []  # log done events
        for event_name, common_reference_dict in self.events.items():
            for reference, unique in common_reference_dict.items():
                device = self.references[reference]
                log.append(execute_post_internal(Naming.resource(event_name), {
                    '@type': event_name,
                    'device': device['_id'],
                    'components': [str(x['_id']) for x in unique]
                }))
        return log
Exemple #9
0
def _add_or_get_inactive_account_id(event, field_name):
    """
    We need to execute after insert and insert_resource.
    """
    if field_name in event and type(event[field_name]) is dict:
        try:
            # We look for just accounts that share our database
            _id = AccountDomain.get_one(
                {
                    "email": event[field_name]["email"]
                    # 'databases': {'$in': AccountDomain.actual['databases']} todo review this
                }
            )["_id"]
        except UserNotFound:
            event[field_name]["databases"] = [AccountDomain.get_requested_database()]
            event[field_name]["active"] = False
            event[field_name]["@type"] = "Account"
            _id = execute_post_internal("accounts", event[field_name], True)["_id"]
        event[field_name] = _id
    def process(self) -> list:
        """
        Executes all events stored.

        First execute the inserts so the stored devices can get the _id and then executes the rest of events.
        :return: A list of the executed events
        """
        log = []  # log done events
        for event_name, common_reference_dict in list(self.events.items()):
            for reference, unique in list(common_reference_dict.items()):
                device = self.references[reference]
                log.append(
                    execute_post_internal(
                        Naming.resource(event_name), {
                            '@type': event_name,
                            'device': device['_id'],
                            'components': [str(x['_id']) for x in unique]
                        }))
        return log
Exemple #11
0
def _add_or_get_inactive_account_id(event, field_name):
    """
    We need to execute after insert and insert_resource.
    """
    if field_name in event and type(event[field_name]) is dict:
        try:
            # We look for just accounts that share our database
            _id = AccountDomain.get_one({
                'email': event[field_name]['email']
                # 'databases': {'$in': AccountDomain.actual['databases']} todo review this
            })['_id']
        except UserNotFound:
            event[field_name]['databases'] = [
                AccountDomain.get_requested_database()
            ]
            event[field_name]['active'] = False
            event[field_name]['@type'] = 'Account'
            _id = execute_post_internal('accounts', event[field_name],
                                        True)['_id']
        event[field_name] = _id
Exemple #12
0
 def exec_hard_drive_events(self, event_log, events):
     for i, event in events:
         event['device'] = self.components[i]['_id']
         self.set_created_conditionally(event)
         event_log.append(execute_post_internal(Naming.resource(event['@type']), event))
         event.update(event_log[-1])