def _raise_if_not_200(self, status_code, response_body):  # response_body here is str in Py3
     if status_code != self.HTTP_SC_200:
         expected_exception = self._expected_exception_map.get(status_code)
         if expected_exception:
             raise expected_exception
         else:
             raise DiscoveryFailure(response_body)
     return DiscoveryInfo(response_body)
def ggc_discovery(thing_name,
                  discovery_info_provider,
                  retry_count=10,
                  max_groups=1):
    back_off_core = ProgressiveBackOffCore()
    discovered = False
    discovery_info = None

    while retry_count != 0:
        try:
            discovery_info = discovery_info_provider.discover(thing_name)
            group_list = discovery_info.getAllGroups()

            if len(group_list) > max_groups:
                raise DiscoveryFailure("Discovered more groups than expected")

            discovered = True
            break
        except DiscoveryFailure as df:
            logging.error(
                "Discovery failed! Error:{0} type:{1} message:{2}".format(
                    df, str(type(df)), df.message))
            back_off = True
        except DiscoveryInvalidRequestException as e:
            logging.error("Invalid discovery request! Error:{0}".format(e))
            logging.error("Stopping discovery...")
            break
        except BaseException as e:
            logging.error(
                "Error in discovery:{0} type:{1} message:{2} thing_name:{3} "
                "dip:{4}".format(e, str(type(e)), e.message, thing_name,
                                 discovery_info_provider))
            back_off = True

        if back_off:
            retry_count -= 1
            logging.info("{0} retries left\n".format(retry_count))
            logging.debug("Backing off...\n")
            back_off_core.backOff()

    return discovered, discovery_info
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)
            groupList = discoveryInfo.getAllGroups()

            if len(groupList) > 1:
                raise DiscoveryFailure("Discovered more groups than expected")

            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
            connList = coreInfo.connectivityInfoList
            print connList

            for addr in connList:
                hostAddr = addr.host

                if isIpAddress(hostAddr):
                    print('Check: {}'.format(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)