github.com/google/fleetspeak@v0.1.15-0.20240426164851-4f31f62c1aea/fleetspeak_python/fleetspeak/server_connector/testing/loopback.py (about)

     1  # Copyright 2017 Google Inc.
     2  #
     3  # Licensed under the Apache License, Version 2.0 (the "License");
     4  # you may not use this file except in compliance with the License.
     5  # You may obtain a copy of the License at
     6  #
     7  #     https://www.apache.org/licenses/LICENSE-2.0
     8  #
     9  # Unless required by applicable law or agreed to in writing, software
    10  # distributed under the License is distributed on an "AS IS" BASIS,
    11  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  # See the License for the specific language governing permissions and
    13  # limitations under the License.
    14  
    15  """A simple GRPCService based loopback.
    16  
    17  This script uses the GRPCService client library to receive messages from
    18  a fleetspeak server. They are returned to the sending address, again
    19  using the GRPCService client library.
    20  """
    21  
    22  import logging
    23  import threading
    24  import time
    25  
    26  from absl import app
    27  from absl import flags
    28  from fleetspeak.server_connector import connector
    29  
    30  FLAGS = flags.FLAGS
    31  
    32  
    33  def main(argv=None):
    34    del argv  # Unused.
    35  
    36    service_client = connector.InsecureGRPCServiceClient("TestService")
    37    seen = set()
    38    seen_lock = threading.Lock()
    39  
    40    def loop(message, context):
    41      """loop a message back to fleetspeak."""
    42      del context  # Unused
    43  
    44      logging.info("Received message.")
    45      with seen_lock:
    46        if message.message_id in seen:
    47          logging.warning("Ignoring duplicate.")
    48          return
    49        seen.add(message.message_id)
    50  
    51      message.ClearField("source_message_id")
    52      message.ClearField("message_id")
    53      message.destination.service_name = message.source.service_name
    54      message.destination.client_id = message.source.client_id
    55  
    56      service_client.outgoing.InsertMessage(message)
    57      logging.info("Sent message.")
    58  
    59    service_client.Listen(loop)
    60    while True:
    61      time.sleep(600)
    62  
    63  
    64  if __name__ == "__main__":
    65    app.run(main)