Пример #1
0
async def read_device(device_id: str) -> List[Dict[str, Any]]:
    """Generate the readings response data for the specified device.

    Args:
        device_id: The ID of the device to get readings for.

    Returns:
        A list of dictionary representations of device reading response(s).
    """
    logger.info('issuing command', command='READ DEVICE', device_id=device_id)

    p = await cache.get_plugin(device_id)
    if p is None:
        raise errors.NotFound(f'plugin not found for device {device_id}', )

    readings = []
    try:
        with p as client:
            for reading in client.read(device_id=device_id):
                readings.append(reading_to_dict(reading))

    except Exception as e:
        raise errors.ServerError(
            'error while issuing gRPC request: read device', ) from e

    logger.debug('got readings', count=len(readings), command='READ DEVICE')
    return readings
Пример #2
0
async def transaction(transaction_id: str) -> Dict[str, Any]:
    """Generate the transaction response data.

    Args:
        transaction_id: The ID of the transaction to get the status of.

    Returns:
         A dictionary representation of the transaction status response.
    """
    logger.info('issuing command', command='TRANSACTION')

    txn = await cache.get_transaction(transaction_id)
    if not txn:
        raise errors.NotFound(f'transaction not found: {transaction_id}', )

    plugin_id = txn.get('plugin')
    device = txn.get('device')

    if not plugin_id:
        raise errors.ServerError(
            f'malformed cached transaction ({transaction_id}): "plugin" not defined'
        )

    p = plugin.manager.get(plugin_id)
    if not p:
        raise errors.NotFound(
            f'plugin not found for transaction: {plugin_id}', )

    try:
        logger.debug(
            'getting transaction info',
            command='TRANSACTION',
            device=device,
            plugin=plugin_id,
            txn_id=transaction_id,
        )
        with p as client:
            response = client.transaction(transaction_id)
    except Exception as e:
        raise errors.ServerError(
            'error while issuing gRPC request: transaction', ) from e

    status = synse_grpc.utils.to_dict(response)
    status['device'] = device
    utils.normalize_write_ctx(status)

    return status
Пример #3
0
    def test_make_response(self):

        ex = errors.NotFound('context error message')
        resp = ex.make_response()

        assert isinstance(resp, dict)
        assert resp == {
            'http_code': 404,
            'description': 'resource not found',
            'timestamp': '2019-04-22T13:30:00Z',
            'context': 'context error message',
        }
Пример #4
0
async def info(device_id: str) -> Dict[str, Any]:
    """Generate the device info response data.

    Args:
        device_id: The ID of the device to get information for.

    Returns:
        A dictionary representation of the device info response.
    """
    logger.info('issuing command', command='INFO', device_id=device_id)

    device = await cache.get_device(device_id)
    if device is None:
        raise errors.NotFound(f'device not found: {device_id}')

    tags = [utils.tag_string(t) for t in device.tags]
    device_info = utils.to_dict(device)
    device_info['tags'] = tags
    return device_info
Пример #5
0
async def plugin(plugin_id: str) -> Dict[str, Any]:
    """Generate the plugin response data.

    Args:
        plugin_id: The ID of the plugin to get information for.

    Returns:
        A dictionary representation of the plugin response.
    """
    logger.info('issuing command', command='PLUGIN', plugin_id=plugin_id)

    # If there are no plugins registered, re-registering to ensure
    # the most up-to-date plugin state.
    if not manager.has_plugins():
        manager.refresh()

    p = manager.get(plugin_id)
    if p is None:
        raise errors.NotFound(f'plugin not found: {plugin_id}')

    try:
        with p as client:
            health = client.health()
    except Exception as e:
        raise errors.ServerError(
            'error while issuing gRPC request: plugin health'
        ) from e

    response = {
        **p.metadata,
        'active': p.active,
        'network': {
            'address': p.address,
            'protocol': p.protocol,
        },
        'version': p.version,
        'health': utils.to_dict(health),
    }

    return response
Пример #6
0
async def write_sync(device_id: str,
                     payload: Union[Dict, List[Dict]]) -> List[Dict[str, Any]]:
    """Generate the synchronous write response data.

    Args:
        device_id: The ID of the device to write to.
        payload: The data to write to the device.

    Returns:
        A list of dictionary representations of synchronous write response(s).
    """
    logger.info(
        'issuing command',
        command='WRITE SYNC',
        device_id=device_id,
        payload=payload,
    )

    plugin = await cache.get_plugin(device_id)
    if plugin is None:
        raise errors.NotFound(f'plugin not found for device {device_id}', )

    response = []
    try:
        with plugin as client:
            for status in client.write_sync(device_id=device_id, data=payload):
                # Add the transaction to the cache
                await cache.add_transaction(status.id, device_id, plugin.id)
                s = grpc_utils.to_dict(status)
                s['device'] = device_id
                utils.normalize_write_ctx(s)
                response.append(s)
    except Exception as e:
        raise errors.ServerError(
            'error while issuing gRPC request: sync write', ) from e

    return response