def discover(host, rootCAPath, certificatePath, privateKeyPath, thingName, devicePath):
    # Progressive back off core
    backOffCore = ProgressiveBackOffCore()

    # Discover GGCs
    discoveryInfoProvider = DiscoveryInfoProvider()
    discoveryInfoProvider.configureEndpoint(host)
    discoveryInfoProvider.configureCredentials(rootCAPath, certificatePath, privateKeyPath)
    discoveryInfoProvider.configureTimeout(10)  # 10 sec

    print("Iot end point: {}".format(host))
    print("Iot CA Path: {}".format(rootCAPath))
    print("GGAD cert path: {}".format(certificatePath))
    print("GGAD private key path: {}".format(privateKeyPath))
    print("GGAD thing name : {}".format(thingName))

    retryCount = MAX_DISCOVERY_RETRIES
    discovered = False
    groupCA = None
    coreInfo = None
    while retryCount != 0:
        try:
            discoveryInfo = discoveryInfoProvider.discover(thingName)
            caList = discoveryInfo.getAllCas()
            coreList = discoveryInfo.getAllCores()

            # We only pick the first ca and core info
            groupId, ca = caList[0]
            coreInfo = coreList[0]
            print("Discovered GGC: %s from Group: %s" % (coreInfo.coreThingArn, groupId))

            hostAddr = ""

            # In this example Ip detector lambda is turned on which reports
            # the GGC hostAddr to the CIS (Connectivity Information Service) that stores the
            # connectivity information for the AWS Greengrass core associated with your group.
            # This is the information used by discovery and the list of host addresses
            # could be outdated or wrong and you would normally want to
            # validate it in a better way.
            # For simplicity, we will assume the first host address that looks like an ip
            # is the right one to connect to GGC.
            # Note: this can also be set manually via the update-connectivity-info CLI
            for addr in coreInfo.connectivityInfoList:
                hostAddr = addr.host
                if isIpAddress(hostAddr):
                    print(hostAddr)

            print("Discovered GGC Host Address: " + hostAddr)
            print("Now we persist the connectivity/identity information...")
            groupCA = '{}/{}'.format(devicePath, GROUP_CA_PATH + CA_NAME)
            ggcHostPath = '{}/{}'.format(devicePath, GROUP_CA_PATH + GGC_ADDR_NAME)
            if not os.path.exists('{}/{}'.format(devicePath, GROUP_CA_PATH)):
                os.makedirs('{}/{}'.format(devicePath, GROUP_CA_PATH))
            groupCAFile = open(groupCA, "w")
            groupCAFile.write(ca)
            groupCAFile.close()
            groupHostFile = open(ggcHostPath, "w")
            groupHostFile.write(hostAddr)
            groupHostFile.close()

            discovered = True
            print("Now proceed to the connecting flow...")
            break
        except DiscoveryInvalidRequestException as e:
            print("Invalid discovery request detected!")
            print("Type: " + str(type(e)))
            print("Error message: " + e.message)
            print("Stopping...")
            break
        except BaseException as e:
            print("Error in discovery!")
            print("Type: " + str(type(e)))
            print("Error message: " + e.message)
            retryCount -= 1
            print("\n"+str(retryCount) + "/" + str(MAX_DISCOVERY_RETRIES) + " retries left\n")
            print("Backing off...\n")
            backOffCore.backOff()

        else:
            if not discovered:
                print("Discovery failed after %d retries. Exiting...\n" % (MAX_DISCOVERY_RETRIES))
                sys.exit(-1)
Ejemplo n.º 2
0
# Configure logging
logger = logging.getLogger("AWSIoTPythonSDK.core")
logger.setLevel(logging.INFO)  # set to logging.DEBUG for additional logging
streamHandler = logging.StreamHandler()
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)

# Run Discovery service to check which GGC to connect to, if it hasn't been run already
# Discovery talks with the IoT cloud to get the GGC CA cert and ip address

if not os.path.isfile('./groupCA/root-ca.crt'):
    # Progressive back off core
    backOffCore = ProgressiveBackOffCore()
    # Discover GGCs
    discoveryInfoProvider = DiscoveryInfoProvider()
    discoveryInfoProvider.configureEndpoint(host)
    discoveryInfoProvider.configureCredentials(iotCAPath, certificatePath,
                                               privateKeyPath)
    discoveryInfoProvider.configureTimeout(10)  # 10 sec
    print("Iot end point: " + host)
    print("Iot CA Path: " + iotCAPath)
    print("GGAD cert path: " + certificatePath)
    print("GGAD private key path: " + privateKeyPath)
    print("GGAD thing name : " + clientId)
    retryCount = MAX_DISCOVERY_RETRIES
    discovered = False
    groupCA = None
    coreInfo = None
Ejemplo n.º 3
0
    def discover_ggc(self):
        backOffCore = ProgressiveBackOffCore()
        discoveryInfoProvider = DiscoveryInfoProvider()
        discoveryInfoProvider.configureEndpoint(self.iot_endpoint)
        discoveryInfoProvider.configureCredentials(self.iot_ca_path,
                                                   self.cert_path,
                                                   self.private_key_path)
        print('Endpoint: {}'.format(self.iot_endpoint))
        print('iot_ca_path: {}'.format(self.iot_ca_path))
        print('cert_path: {}'.format(self.cert_path))
        print('private_key_path: {}'.format(self.private_key_path))
        print('device_name: {}'.format(self.device_name))
        discoveryInfoProvider.configureTimeout(10)  # 10 sec
        retryCount = self.max_discovery_retries
        discovered = False
        groupCA = None
        coreInfo = None
        while retryCount != 0:
            try:
                discoveryInfo = discoveryInfoProvider.discover(
                    self.device_name)  # noqa: E501
                caList = discoveryInfo.getAllCas()
                coreList = discoveryInfo.getAllCores()
                groupId, ca = caList[0]
                coreInfo = coreList[0]
                print('Discovered GGC: ' + coreInfo.coreThingArn +
                      ' from Group: ' + groupId)
                host_addr = ''

                for addr in coreInfo.connectivityInfoList:
                    host_addr = addr.host
                    if self.isIpAddress(host_addr):
                        break

                print('Discovered GGC Host Address: ' + host_addr)
                self.ggc_host_addr = host_addr
                print('Now we persist the connectivity/identity information')
                groupCA = os.path.join(self.device_path, self.ca_name)
                ggcHostPath = os.path.join(self.device_path,
                                           self.ggc_addr_name)  # noqa: E501
                groupCAFile = open(groupCA, 'w')
                groupCAFile.write(ca)
                groupCAFile.close()
                groupHostFile = open(ggcHostPath, 'w')
                groupHostFile.write(host_addr)
                groupHostFile.close()

                discovered = True
                print('Now proceed to the connecting flow...')
                break
            except DiscoveryInvalidRequestException as e:
                print('Invalid discovery request detected!')
                print('Type: ' + str(type(e)))
                print('Error message: ' + e.message)
                print('Stopping...')
                break
            except BaseException as e:
                print('Error in discovery!')
                print('Type: ' + str(type(e)))
                print('Error message: ' + e.message)
                retryCount -= 1
                raise
                print('\n' + str(retryCount) + '/' +
                      str(self.max_discovery_retries) + ' retries left\n')
                print('Backing off...\n')
                backOffCore.backOff()

        if not discovered:
            print('Discovery failed after ' + str(self.max_discovery_retries) +
                  ' retries. Exiting...\n')
            sys.exit(-1)