|
| 1 | +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0. |
| 3 | + |
| 4 | +import os |
| 5 | +from typing import Optional |
| 6 | + |
| 7 | +from awscrt.io import ( |
| 8 | + ClientBootstrap, |
| 9 | + DefaultHostResolver, |
| 10 | + EventLoopGroup, |
| 11 | + SocketDomain, |
| 12 | + SocketOptions, |
| 13 | +) |
| 14 | +from awsiot.eventstreamrpc import ( |
| 15 | + Connection, |
| 16 | + LifecycleHandler, |
| 17 | + MessageAmendment, |
| 18 | +) |
| 19 | +from awsiot.greengrasscoreipc.client import GreengrassCoreIPCClient |
| 20 | + |
| 21 | + |
| 22 | +def connect(*, |
| 23 | + ipc_socket: str=None, |
| 24 | + authtoken: str=None, |
| 25 | + lifecycle_handler: Optional[LifecycleHandler]=None, |
| 26 | + timeout=10.0) -> GreengrassCoreIPCClient: |
| 27 | + """ |
| 28 | + Creates an IPC client and connects to the GreengrassCoreIPC service. |
| 29 | +
|
| 30 | + Args: |
| 31 | + ipc_socket: Path to the Unix domain socket of Greengrass Nucleus, defaults to |
| 32 | + environment variable AWS_GG_NUCLEUS_DOMAIN_SOCKET_FILEPATH_FOR_COMPONENT |
| 33 | + authtoken: Authentication token, defaults to environment variable SVCUID |
| 34 | + lifecycle_handler: Handler for events over the course of this |
| 35 | + network connection. See :class:`LifecycleHandler` for more info. |
| 36 | + Handler methods will only be invoked if the connect attempt |
| 37 | + succeeds. |
| 38 | + timeout: The number of seconds to wait for establishing the connection. |
| 39 | +
|
| 40 | + Returns: |
| 41 | + Client for the GreengrassCoreIPC service. |
| 42 | + """ |
| 43 | + |
| 44 | + if not ipc_socket: |
| 45 | + ipc_socket = os.environ["AWS_GG_NUCLEUS_DOMAIN_SOCKET_FILEPATH_FOR_COMPONENT"] |
| 46 | + if not authtoken: |
| 47 | + authtoken = os.environ["SVCUID"] |
| 48 | + if not lifecycle_handler: |
| 49 | + lifecycle_handler = LifecycleHandler() |
| 50 | + |
| 51 | + elg = EventLoopGroup(num_threads=1) |
| 52 | + resolver = DefaultHostResolver(elg) |
| 53 | + bootstrap = ClientBootstrap(elg, resolver) |
| 54 | + socket_options = SocketOptions() |
| 55 | + socket_options.domain = SocketDomain.Local |
| 56 | + amender = MessageAmendment.create_static_authtoken_amender(authtoken) |
| 57 | + |
| 58 | + connection = Connection( |
| 59 | + host_name=ipc_socket, |
| 60 | + port=0, # dummy port number, not needed for Unix domain sockets |
| 61 | + bootstrap=bootstrap, |
| 62 | + socket_options=socket_options, |
| 63 | + connect_message_amender=amender, |
| 64 | + ) |
| 65 | + connect_future = connection.connect(lifecycle_handler) |
| 66 | + connect_future.result(timeout) |
| 67 | + |
| 68 | + return GreengrassCoreIPCClient(connection) |
0 commit comments