Пример #1
0
async def get_registered_device(
    device_id: DeviceID,
    repo: DeviceRepository = Depends(get_repository(DeviceRepository)),
) -> Device:
    try:
        return await repo.get(device_id)
    except DeviceDoesNotExist:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="device not found"
        )
Пример #2
0
async def execute_command_on_device(
        execute_params: ExecuteShellOnDeviceRequest,
        broker_repo: DeviceBrokerRepo = Depends(
            get_repository(DeviceBrokerRepo)),
        device: Device = Depends(get_registered_device),
) -> None:
    command = ExecuteOnDeviceCommand(
        device_id=device.id,
        correlation_id=uuid.uuid4(),
        command_attributes=execute_params.dict(),
    )
    await broker_repo.send_command(command)
Пример #3
0
async def device_ws_endpoint(  # noqa: WPS231
    websocket: websockets.WebSocket,
    token: str = Depends(get_bearer_token),
    auth_service: DevicesAuthService = Depends(get_service(DevicesAuthService)),
    broker_repo: DeviceBrokerRepo = Depends(get_repository(DeviceBrokerRepo)),
    clients_manager: DevicesSocketManager = Depends(get_device_clients_manager),
    socket_repo: DevicesSocketRepo = Depends(get_repository(DevicesSocketRepo)),
) -> None:
    try:
        device = await auth_service.get_device_from_token(token)
    except RuntimeError as error:
        logger.debug(f"device token decode error:{error}")
        raise websockets.WebSocketDisconnect(code=status.WS_1008_POLICY_VIOLATION)

    await clients_manager.connect(device.id, websocket)
    await socket_repo.set_connected(device.id)

    while True:
        try:  # noqa: WPS229
            payload = await websocket.receive_text()
            logger.debug(f"received response from device:{device.id}\n{payload}")
            response = DeviceAgentResponse.parse_raw(payload)
        except ValueError as validation_error:
            logger.error(f"ws payload validation error {validation_error}")
        except websockets.WebSocketDisconnect as disconnect_error:
            logger.info(f"device:{device.id} disconnected, reason {disconnect_error}")
            await clients_manager.disconnect(device.id)
            await socket_repo.set_disconnected(device.id)
            break
        else:
            if response.is_success:
                await _publish_event(broker_repo, device, response)
            else:
                logger.error(
                    f"received error from device:{device.id}\n{response.error}"
                )
async def get_device_hardware(
    device: Device = Depends(get_registered_device),
    broker_repo: DeviceBrokerRepo = Depends(get_repository(DeviceBrokerRepo)),
) -> GetDeviceHardwareResponse:
    hardware = device.get_hardware()  # type:ignore

    if hardware:
        return GetDeviceHardwareResponse.parse_obj(hardware)

    command = SyncDeviceHardwareCommand(device_id=device.id,
                                        correlation_id=uuid.uuid4())
    await broker_repo.send_command(command)
    try:
        event = await broker_repo.get(device.id,
                                      command.correlation_id)  # type: ignore
    except RuntimeError:
        raise HTTPException(status_code=status.HTTP_504_GATEWAY_TIMEOUT,
                            detail="device unavailable")
    return GetDeviceHardwareResponse(**event["event_attributes"])
Пример #5
0
async def get_device_system(
    device: Device = Depends(get_registered_device),
    broker_repo: DeviceBrokerRepo = Depends(get_repository(DeviceBrokerRepo)),
) -> GetDeviceSystemResponse:
    system = device.get_system()  # type: ignore

    if system:
        return GetDeviceSystemResponse(system_attributes=system)

    command = SyncDeviceSystemCommand(device_id=device.id, correlation_id=uuid.uuid4())
    await broker_repo.send_command(command)

    try:
        event = await broker_repo.get(device.id, command.correlation_id)  # type: ignore
    except RuntimeError:
        raise HTTPException(
            status_code=status.HTTP_504_GATEWAY_TIMEOUT, detail="device unavailable"
        )
    return GetDeviceSystemResponse(system_attributes=event["event_attributes"])
Пример #6
0
async def get_device_software(
    device: Device = Depends(get_registered_device),
    broker_repo: DeviceBrokerRepo = Depends(get_repository(DeviceBrokerRepo)),
) -> GetListDeviceSoftware:
    software = device.get_software()  # type: ignore

    if software:
        return GetListDeviceSoftware.parse_obj(software)

    command = SyncDeviceSoftwareCommand(device_id=device.id,
                                        correlation_id=uuid.uuid4())
    await broker_repo.send_command(command)

    try:
        event = await broker_repo.get(device.id,
                                      command.correlation_id)  # type: ignore
    except RuntimeError:
        raise HTTPException(status_code=status.HTTP_504_GATEWAY_TIMEOUT,
                            detail="device unavailable")
    else:
        return GetListDeviceSoftware(
            __root__=event["event_attributes"]["installed_programs"])
Пример #7
0
def _get_users_service(
    users_repository: UserRepository = Depends(get_repository(UserRepository)),
) -> UserService:
    return UserService(users_repo=users_repository)
Пример #8
0
async def shutdown_device(
    device: Device = Depends(get_registered_device),
    broker_repo: DeviceBrokerRepo = Depends(get_repository(DeviceBrokerRepo)),
) -> None:
    command = ShutdownDeviceCommand(device_id=device.id, correlation_id=uuid.uuid4())
    await broker_repo.send_command(command)