Esempio n. 1
0
 def do_logical_devices(self, line):
     """List logical devices in Voltha"""
     stub = self.get_stub()
     res = stub.ListLogicalDevices(Empty())
     omit_fields = {
         'desc.mfr_desc',
         'desc.hw_desc',
         'desc.sw_desc',
         'desc.dp_desc',
         'desc.serial_number',
         'switch_features.capabilities'
     }
     print_pb_list_as_table('Logical devices:', res.items, omit_fields,
                            self.poutput)
Esempio n. 2
0
    def test_delete_success(self):
        from google.protobuf.empty_pb2 import Empty

        client = _Client()
        api = client.table_admin_client = self._make_table_admin_client()
        api.delete_backup.return_value = Empty()
        instance = _Instance(self.INSTANCE_NAME, client=client)
        backup = self._make_one(self.BACKUP_ID,
                                instance,
                                cluster_id=self.CLUSTER_ID)

        backup.delete()

        api.delete_backup.assert_called_once_with(self.BACKUP_NAME)
Esempio n. 3
0
    def test_delete_success(self):
        from google.protobuf.empty_pb2 import Empty

        client = _Client(self.PROJECT)
        api = client.instance_admin_api = _FauxInstanceAdminAPI(
            _delete_instance_response=Empty())
        instance = self._make_one(self.INSTANCE_ID, client, self.CONFIG_NAME)

        instance.delete()

        name, metadata = api._deleted_instance
        self.assertEqual(name, self.INSTANCE_NAME)
        self.assertEqual(metadata,
                         [("google-cloud-resource-prefix", instance.name)])
Esempio n. 4
0
    def get_claw_aio(self, pin: str) -> float:
        """
        获取手爪参数

        :param pin: 'force':手爪力,'weight':手爪重量
        :return: 根据参数,获取手爪力或者重量

        示例:

        >>> claw_force = self.get_claw_aio("force")
        >>> claw_weight = self.get_claw_aio("weight")
        """
        self._sync()
        pin = pin.lower()
        if pin == 'force':
            res = self.rcs.GetClawHoldOn(Empty())
            return res.hold_on
        elif pin == 'weight':
            res = self.rcs.GetClawWeight(Empty())
            return res.weight
        else:  # pin == 'amplitude':
            res = self.rcs.GetClawAmplitude(Empty())
            return res.amplitude
Esempio n. 5
0
def test_SubmitOrder(
        trading,
        tradingdata,
        walletClientWalletKeypair  # noqa: F811
):
    (walletclient, _, _, pubKey) = walletClientWalletKeypair  # noqa: F811

    # Get a market
    req = vac.api.trading.MarketByIDRequest(market_id="076BB86A5AA41E3E")
    market = tradingdata.MarketByID(req).market

    # Prepare the SubmitOrder
    now = int(tradingdata.GetVegaTime(Empty()).timestamp)
    request = vac.api.trading.PrepareSubmitOrderRequest(
        submission=vac.vega.OrderSubmission(
            expires_at=now + 120000000000,
            market_id=market.id,
            party_id=pubKey,
            price=10,
            side=vac.vega.Side.SIDE_BUY,
            size=1,
            time_in_force=vac.vega.Order.TimeInForce.TIME_IN_FORCE_GTT,
            type=vac.vega.Order.Type.TYPE_LIMIT,
            reference=str(uuid.uuid4()),
        ))
    # Either: Prepare the SubmitOrder using the Vega node
    # blob = trading.PrepareSubmitOrder(request, contact_node=True).blob
    # Or: Prepare the SubmitOrder ourselves
    blob = trading.PrepareSubmitOrder(request, contact_node=False).blob

    # Sign the tx
    r = walletclient.signtx(
        base64.b64encode(blob).decode("ascii"), pubKey, False)
    check_response(r)
    signedTx = r.json()["signedTx"]

    # Submit the signed transaction
    # assert blob == base64.b64decode(signedTx["data"])
    request = vac.api.trading.SubmitTransactionRequest(
        tx=vac.vega.SignedBundle(
            tx=base64.b64decode(signedTx["tx"]),
            sig=vac.vega.Signature(
                sig=base64.b64decode(signedTx["sig"]["sig"]),
                algo=signedTx["sig"]["algo"],
                version=signedTx["sig"]["version"],
            ),
        ))
    response = trading.SubmitTransaction(request)
    assert response.success
Esempio n. 6
0
    def set_config(self, camera_config, ctx):
        if camera_config.HasField("sampling"):
            if camera_config.sampling.HasField("frequency"):
                self.driver.set_sampling_rate(
                    camera_config.sampling.frequency.value)
            if camera_config.sampling.HasField("delay"):
                self.driver.set_delay(camera_config.sampling.delay.value)

        if camera_config.HasField("image"):
            if camera_config.image.HasField("resolution"):
                self.driver.set_resolution(camera_config.image.resolution)
            if camera_config.image.HasField("format"):
                self.driver.set_image_format(camera_config.image.format)
            if camera_config.image.HasField("color_space"):
                self.driver.set_color_space(
                    camera_config.image.color_space.value)
            if camera_config.image.HasField("region"):
                self.driver.set_region_of_interest(camera_config.image.region)

        if camera_config.HasField("camera"):
            if camera_config.camera.HasField("brightness"):
                self.driver.set_brightness(camera_config.camera.brightness)
            if camera_config.camera.HasField("exposure"):
                self.driver.set_exposure(camera_config.camera.exposure)
            if camera_config.camera.HasField("focus"):
                self.driver.set_focus(camera_config.camera.focus)
            if camera_config.camera.HasField("gain"):
                self.driver.set_gain(camera_config.camera.gain)
            if camera_config.camera.HasField("gamma"):
                self.driver.set_gamma(camera_config.camera.gamma)
            if camera_config.camera.HasField("hue"):
                self.driver.set_hue(camera_config.camera.hue)
            if camera_config.camera.HasField("iris"):
                self.driver.set_iris(camera_config.camera.iris)
            if camera_config.camera.HasField("saturation"):
                self.driver.set_saturation(camera_config.camera.saturation)
            if camera_config.camera.HasField("sharpness"):
                self.driver.set_sharpness(camera_config.camera.sharpness)
            if camera_config.camera.HasField("shutter"):
                self.driver.set_shutter(camera_config.camera.shutter)
            if camera_config.camera.HasField("white_balance_bu"):
                self.driver.set_white_balance_bu(
                    camera_config.camera.white_balance_bu)
            if camera_config.camera.HasField("white_balance_rv"):
                self.driver.set_white_balance_rv(
                    camera_config.camera.white_balance_rv)
            if camera_config.camera.HasField("zoom"):
                self.driver.set_zoom(camera_config.camera.zoom)
        return Empty()
    def test_drop_success(self):
        from google.protobuf.empty_pb2 import Empty
        client = _Client()
        api = client.database_admin_api = _FauxDatabaseAdminAPI(
            _drop_database_response=Empty())
        instance = _Instance(self.INSTANCE_NAME, client=client)
        pool = _Pool()
        database = self._makeOne(self.DATABASE_ID, instance, pool=pool)

        database.drop()

        name, options = api._dropped_database
        self.assertEqual(name, self.DATABASE_NAME)
        self.assertEqual(options.kwargs['metadata'],
                         [('google-cloud-resource-prefix', database.name)])
Esempio n. 8
0
def run():

    channel = grpc.insecure_channel('localhost:50055')

    # Test fetch the schema
    stub = schema_pb2.SchemaServiceStub(channel)
    res = stub.GetSchema(Empty())
    print '\nSchema:\n'
    for key in res.protos:
        print '%s %s file begins %s\n' % (30 * '~', key, (35 - len(key)) * '~')
        print res.protos[key]
        print '%s %s file ends %s' % (30 * '~', key, (37 - len(key)) * '~')
    for key in res.descriptors:
        print '%s -> descriptor of %d bytes' % (key, len(res.descriptors[key]))

    # Ping health state as an example
    stub = voltha_pb2.HealthServiceStub(channel)
    res = stub.GetHealthStatus(Empty())
    print '\nHealth state:', res.state

    # Try another API
    stub = voltha_pb2.ExampleServiceStub(channel)
    res = stub.ListAddresses(Empty())
    print '\nExample objects returned:\n', res.addresses
Esempio n. 9
0
    def __init__(self,
                 stub: FmuServiceStub,
                 model_description,
                 integrator=None):
        self.stub = stub
        self.model_description = model_description

        if integrator is None:
            self.fmu_id = self.stub.CreateInstanceFromCS(Empty()).value
        else:
            self.fmu_id = self.stub.CreateInstanceFromME(integrator).value

        self.model_variables = dict()
        for v in self.model_description.model_variables:
            self.model_variables[v.value_reference] = v
Esempio n. 10
0
    def get_copy_of_latest_data(
            self) -> (PayoffTable, List[List[int]], List[List[int]]):
        request = Empty()
        response: P2SROStatusResponse = self._stub.GetCopyOfLatestData(request)
        payoff_table = PayoffTable.from_json_string(
            json_string=response.payoff_table_json)

        active_policies_per_player = []
        fixed_policies_per_player = []
        for active_list, fixed_list in zip(response.active_policies,
                                           response.fixed_policies):
            active_policies_per_player.append(active_list.policies)
            fixed_policies_per_player.append(fixed_list.policies)

        return payoff_table, active_policies_per_player, fixed_policies_per_player
Esempio n. 11
0
    def test_delete_success(self):
        from google.protobuf.empty_pb2 import Empty

        client = _Client()
        api = client.database_admin_api = self._make_database_admin_api()
        api.delete_backup.return_value = Empty()
        instance = _Instance(self.INSTANCE_NAME, client=client)
        backup = self._make_one(self.BACKUP_ID, instance)

        backup.delete()

        api.delete_backup.assert_called_once_with(
            name=self.BACKUP_NAME,
            metadata=[("google-cloud-resource-prefix", backup.name)],
        )
Esempio n. 12
0
def remove_item(
    state: ShoppingCartState, item: RemoveLineItem, ctx: EventSourcedCommandContext
):
    cart = state.cart
    if item.product_id not in cart:
        ctx.fail(
            "Cannot remove item {} because it is not in the cart.".format(
                item.product_id
            )
        )
    else:
        item_removed_event = ItemRemoved()
        item_removed_event.productId = item.product_id
        ctx.emit(item_removed_event)
    return Empty()
def test_get_all_appointments_responder(clear_state, internal_api,
                                        generate_dummy_tracker, stub):
    # Data is pulled straight from the database, so we need to feed some
    tracker = generate_dummy_tracker()
    uuid = uuid4().hex
    internal_api.watcher.db_manager.store_responder_tracker(
        uuid, tracker.to_dict())

    response = stub.get_all_appointments(Empty())
    appointments = dict(response.appointments)

    assert len(appointments.get("watcher_appointments")) == 0 and len(
        appointments.get("responder_trackers")) == 1
    assert dict(
        appointments.get("responder_trackers")[uuid]) == tracker.to_dict()
Esempio n. 14
0
    def UpdateLogicalDeviceFlowGroupTable(self, request, context):
        log.info('grpc-request', request=request)

        try:
            instance_id = self.dispatcher.instance_id_by_logical_device_id(
                request.id)
        except KeyError:
            context.set_details('Logical device \'{}\' not found'.format(
                request.id))
            context.set_code(StatusCode.NOT_FOUND)
            return Empty()

        return self.dispatcher.dispatch(instance_id, VolthaLocalServiceStub,
                                        'UpdateLogicalDeviceFlowGroupTable',
                                        request, context)
Esempio n. 15
0
 def list_logical_devices(self):
     """
     Return the list of logical devices.
     :return: list of logical devices as exposed by VOLTHA
     :except: ConnectionException if VOLTHA is unreachable, otherwise VolthaException if any other RpcError
     """
     try:
         devs = self._get_stub().ListLogicalDevices(Empty(),
                                                    timeout=self._timeout)
         return devs.items
     except grpc.RpcError as e:
         self._manage_std_conn_error(e)
         raise VolthaException(
             "Failed to retrieve logical devices from VOLTHA (%s, %s)" %
             (e.code(), e.details()))
Esempio n. 16
0
 def setAppConfigVal(self, request, context):
     """Set an app config value."""
     self._log_request(request, context)
     # get the app config setting
     for val_type in ("strVal", "intVal", "boolVal"):
         if request.HasField(val_type):
             key, val = request.key, getattr(request, val_type)
             _logger.debug("- Setting app config: %s = %s (%s)", key,
                           str(val),
                           type(val).__name__)
             if isinstance(val, str):
                 val = val.replace( "{{TEMP_DIR}}", self._temp_dir.name ) \
                          .replace( "{{FIXTURES_DIR}}", _FIXTURES_DIR )
             self._webapp.config[key] = val
             return Empty()
     raise RuntimeError("Can't find app config key.")
Esempio n. 17
0
    def AcknowledgeCbsdUpdate(self, request: AcknowledgeCbsdUpdateRequest, context) -> Empty:
        """
        Mark CBSD in the Database as not updated

        Parameters:
            request: a AcknowledgeCbsdUpdateRequest gRPC Message
            context: gRPC context

        Returns:
            Empty: an empty gRPC message
        """
        db_id = request.id
        logger.info(f"Acknowledging CBSD update {db_id}")
        updated = self._update_cbsd(db_id, {'should_deregister': False})
        if not updated:
            context.set_code(grpc.StatusCode.NOT_FOUND)
        return Empty()
Esempio n. 18
0
async def main():
    async with purerpc.insecure_channel("localhost", 50051) as channel:
        stub = ChallengeStub(channel)

        challenge = await stub.create(ChallengeRequest(name='Mr. Easy'))
        print(challenge.id, challenge.name)

        async def challenge_requests(name):
            for i in range(2):
                yield ChallengeRequest(name=f'({i} {name}')

        async for challenge in stub.bulk_create(
                challenge_requests('Mr. Bulk Easy')):
            print(challenge.id, challenge.name)

        async for challenge in stub.list(Empty()):
            print(challenge.id, challenge.name)
Esempio n. 19
0
 def setVehOrdNotesDir(self, request, context):
     """Set the vehicle/ordnance notes directory."""
     self._log_request(request, context)
     dtype = request.dirType
     # set the vehicle/ordnance notes directory
     if dtype == SetVehOrdNotesDirRequest.DirType.NONE:  #pylint: disable=no-member
         dname = None
     elif dtype == SetVehOrdNotesDirRequest.DirType.REAL:  #pylint: disable=no-member
         dname = _ORIG_CHAPTER_H_NOTES_DIR
     elif dtype == SetVehOrdNotesDirRequest.DirType.TEST:  #pylint: disable=no-member
         dname = os.path.join(_FIXTURES_DIR, "vo-notes")
     else:
         raise RuntimeError(
             "Invalid vehicle/ordnance notes dir.type: {}".format(dtype))
     _logger.debug("- Setting vehicle/ordnance notes: %s", dname)
     self._webapp.config["CHAPTER_H_NOTES_DIR"] = dname
     return Empty()
Esempio n. 20
0
def test_get_all_appointments_responder(internal_api, stub,
                                        generate_dummy_tracker, monkeypatch):
    #  Mock data being only present in the Watcher
    local_trackers = {uuid4().hex: generate_dummy_tracker().to_dict()}
    monkeypatch.setattr(internal_api.watcher, "get_all_watcher_appointments",
                        lambda: {})
    monkeypatch.setattr(internal_api.watcher, "get_all_responder_trackers",
                        lambda: local_trackers)

    # Get the response and cast it to dict
    response = stub.get_all_appointments(Empty())
    assert isinstance(response, GetAllAppointmentsResponse)
    appointments = json_format.MessageToDict(response.appointments)

    assert len(appointments.get("watcher_appointments")) == 0
    for uuid, tracker in local_trackers.items():
        assert dict(appointments.get("responder_trackers")[uuid]) == tracker
Esempio n. 21
0
def test_get_tower_info(internal_api, stub, monkeypatch):
    monkeypatch.setattr(internal_api.watcher.gatekeeper, "registered_users",
                        {"uid1": {}})
    monkeypatch.setattr(
        internal_api.watcher,
        "appointments",
        {
            "uid1": {
                "locator": "locator1",
                "user_id": "user_id1"
            },
            "uid2": {
                "locator": "locator2",
                "user_id": "user_id2"
            },
        },
    )
    monkeypatch.setattr(
        internal_api.watcher.responder,
        "trackers",
        {
            "uid1": {
                "penalty_txid": "txid1",
                "locator": "locator1",
                "user_id": "user_id1"
            },
            "uid2": {
                "penalty_txid": "txid2",
                "locator": "locator2",
                "user_id": "user_id2"
            },
            "uid3": {
                "penalty_txid": "txid3",
                "locator": "locator2",
                "user_id": "user_id3"
            },
        },
    )

    response = stub.get_tower_info(Empty())
    assert isinstance(response, GetTowerInfoResponse)
    assert response.tower_id == Cryptographer.get_compressed_pk(
        internal_api.watcher.signing_key.public_key)
    assert response.n_registered_users == 1
    assert response.n_watcher_appointments == 2
    assert response.n_responder_trackers == 3
Esempio n. 22
0
    def StoreAvailableFrequencies(self, request: StoreAvailableFrequenciesRequest, context) -> Empty:
        """
        Store available frequencies in the database

        Parameters:
            request: StoreAvailableFrequencies gRPC Message
            context: gRPC context

        Returns:
            Empty: an empty gRPC message
        """
        db_id = request.id
        logger.info(f"Storing available frequencies for {db_id}")
        updated = self._update_cbsd(db_id, {"available_frequencies": list(request.available_frequencies)})
        if not updated:
            context.set_code(grpc.StatusCode.NOT_FOUND)
        return Empty()
Esempio n. 23
0
def test_get_users(internal_api, stub, monkeypatch):
    # Mock user data (doesn't matter it's not properly formatted for the sake of the test)
    mock_users = ["user1", "user2", "user3"]
    monkeypatch.setattr(
        internal_api.watcher,
        "get_registered_user_ids",
        lambda: {
            "user1": dict(),
            "user2": dict(),
            "user3": dict()
        },
    )

    # Check we receive the same list of users
    response = stub.get_users(Empty())
    assert isinstance(response, GetUsersResponse)
    assert response.user_ids == mock_users
Esempio n. 24
0
    def _setup_joints(self):
        joint_stub = joint_pb2_grpc.JointServiceStub(self._grpc_channel)

        joint_ids = joint_stub.GetAllJointsId(Empty())
        self._joint_uid_to_name = dict(zip(joint_ids.uids, joint_ids.names))
        self._joint_name_to_uid = dict(zip(joint_ids.names, joint_ids.uids))

        req = joint_pb2.JointsStateRequest(
            ids=[joint_pb2.JointId(uid=uid) for uid in joint_ids.uids],
            requested_fields=[joint_pb2.JointField.ALL],
        )
        joints_state = joint_stub.GetJointsState(req)

        for joint_id, joint_state in zip(joints_state.ids,
                                         joints_state.states):
            joint = Joint(joint_state)
            self._joints.append(joint)
Esempio n. 25
0
 def do_logical_devices(self, line):
     """List logical devices in Voltha"""
     stub = self.get_stub()
     res = stub.ListLogicalDevices(Empty())
     omit_fields = {
         'desc.mfr_desc',
         'desc.hw_desc',
         'desc.sw_desc',
         'desc.dp_desc',
         'desc.serial_number',
         'switch_features.capabilities'
     }
     presfns = {
         'datapath_id': lambda x: "{0:0{1}x}".format(int(x), 16)
     }
     print_pb_list_as_table('Logical devices:', res.items, omit_fields,
                            self.poutput, presfns=presfns)
Esempio n. 26
0
 def _get_xpon_object_grpc(self, stub, obj_type, device_id=None):
     if obj_type["type"] == "channel_groups":
         res = stub.GetAllChannelgroupConfig(Empty())
     elif obj_type["type"] == "channel_partitions":
         res = stub.GetAllChannelpartitionConfig(Empty())
     elif obj_type["type"] == "channel_pairs":
         res = stub.GetAllChannelpairConfig(Empty())
     elif obj_type["type"] == "channel_terminations":
         res = stub.GetAllChannelterminationConfig(
             voltha_pb2.ID(id=device_id))
     elif obj_type["type"] == "v_ont_anis":
         res = stub.GetAllVOntaniConfig(Empty())
     elif obj_type["type"] == "ont_anis":
         res = stub.GetAllOntaniConfig(Empty())
     elif obj_type["type"] == "v_enets":
         res = stub.GetAllVEnetConfig(Empty())
     elif obj_type["type"] == "gemports":
         res = stub.GetAllGemportsConfigData(Empty())
     elif obj_type["type"] == "tconts":
         res = stub.GetAllTcontsConfigData(Empty())
     elif obj_type["type"] == "traffic_descriptor_profiles":
         res = stub.GetAllTrafficDescriptorProfileData(Empty())
     return res
Esempio n. 27
0
    def create_response(self, response_data: ErrorResponseData, protocol: ProtocolType, context: Context):
        headers = {"x-request-id": context.request_id}
        if protocol == ProtocolType.MSGPACK:
            content_type = "application/x-msgpack"
            content = msgpack.dumps(response_data)
            headers = {}
        elif protocol == ProtocolType.JSON:
            content_type = "application/json"
            content = json.dumps(response_data)
            headers = {}
        elif protocol == ProtocolType.PROTOBUF:
            content_type = "application/protobuf"
            content = Empty().SerializeToString()
            headers.update({"ERROR_CODE": response_data["error"], "ERROR_MESSAGE": response_data["message"]})
        else:
            raise ValueError(f"Unknown protocol: {protocol}")

        return Response(content, content_type=content_type, headers=headers)
Esempio n. 28
0
    def get_onus(self, olt_id):
        """ Query VOLTHA to get a list of ONUs attached to a particular OLT """

        onus = []

        stub = self.get_stub()
        devices = stub.ListDevices(Empty())
        for device in devices.items:
            if device.parent_id != olt_id:
                continue
            if device.parent_port_no is None:
                continue

            onus.append({"id": olt_id,
                         "onu_device_id": device.id,
                         "intf_id": str(device.parent_port_no & 0x0F)})

        return onus
Esempio n. 29
0
    def get_manager_stats(self, infinite_retry_on_error: bool = True):
        while True:
            try:
                request = Empty()
                response: ManagerStats = self._stub.GetManagerStats(request)
                break
            except grpc.RpcError as err:
                if infinite_retry_on_error:
                    logger.warning(
                        f"grpc.RPCError raised while getting manager stats:\n{err}\n"
                        f"(retrying in {_INFINITE_RETRY_INTERVAL_SECONDS} seconds)"
                    )
                    time.sleep(_INFINITE_RETRY_INTERVAL_SECONDS)
                else:
                    raise

        stats_dict = json.loads(response.manager_stats_json)
        return stats_dict
Esempio n. 30
0
    def get_list_of_logical_devices_from_voltha(self):

        while True:
            log.info('Retrieve devices from voltha')
            try:
                stub = voltha_pb2.VolthaLocalServiceStub(self.channel)
                devices = stub.ListLogicalDevices(Empty()).items
                for device in devices:
                    log.info("Devices {} -> {}".format(device.id,
                                                       device.datapath_id))
                returnValue(devices)

            except Exception as e:
                log.error('Failure to retrieve devices from '
                          'voltha: {}'.format(repr(e)))

            log.info('reconnect', after_delay=self.voltha_retry_interval)
            yield asleep(self.voltha_retry_interval)