def main(argv):
    """Sends usage reports to Google Service Control for all users."""

    if len(argv) != 2:
        print('Usage: python -m impl.step_6_report_usage.report <service_name>')
        return

    service_name = argv[1]

    service = build('servicecontrol', 'v1')

    database = JsonDatabase()

    for customer_id, customer in database.items():
        for product_id, product in customer['products'].items():
            if 'consumer_id' not in product:
                continue
            end_time = datetime.datetime.utcnow().strftime(TIME_FORMAT)
            start_time = None
            if 'last_report_time' in product:
                start_time = product['last_report_time']
            else:
                start_time = product['start_time']
            metric_plan_name = product['plan_id'].replace('-', '_')
            operation = {
                'operationId': str(uuid.uuid4()),
                'operationName': 'Codelab Usage Report',
                'consumerId': product['consumer_id'],
                'startTime': start_time,
                'endTime': end_time,
                'metricValueSets': [{
                    'metricName': '%s/%s_requests' % (service_name,
                                                      metric_plan_name),
                    'metricValues': [{
                        'int64Value': _get_usage_for_product(),
                    }],
                }],
            }
            check = service.services().check(
                serviceName=service_name, body={
                    'operation': operation
                }).execute()

            if 'checkErrors' in check:
                print('Errors for user %s with product %s:' % (customer_id,
                                                               product_id))
                print(check['checkErrors'])
                ### TODO: Temporarily turn off service for the user. ###
                continue
            service.services().report(
                serviceName=service_name, body={
                    'operations': [operation]
                }).execute()
            product['last_report_time'] = end_time
            database.write(customer_id, customer)
def main(argv):
    """Main entrypoint to the integration with the Procurement Service."""

    if len(argv) < 2:
        print 'Usage: python -m impl.step_5_entitlement_cancel.app <project_id>'
        return

    project_id = argv[1]

    credentials = _get_credentials()

    # Construct a service for the Partner Procurement API.
    database = JsonDatabase()
    procurement = Procurement(credentials, database, project_id)

    # Get the subscription object in order to perform actions on it.
    subscriber = pubsub_v1.SubscriberClient(credentials=credentials)
    subscription_path = subscriber.subscription_path(project_id,
                                                     PUBSUB_SUBSCRIPTION)

    def callback(message):
        """Callback for handling Cloud Pub/Sub messages."""
        payload = json.loads(message.data)

        print 'Received message:'
        pprint.pprint(payload)
        print

        ack = False
        if 'entitlement' in payload:
            ack = procurement.handle_entitlement_message(
                payload['entitlement'], payload['eventType'])
        elif 'account' in payload:
            ack = procurement.handle_account_message(payload['account'])
        else:
            # If there's no account or entitlement, then just ack and ignore the
            # message. This should never happen.
            ack = True

        if ack:
            message.ack()

    subscription = subscriber.subscribe(subscription_path, callback=callback)

    print 'Listening for messages on {}'.format(subscription_path)
    print 'Exit with Ctrl-\\'

    while True:
        try:
            subscription.result()
        except Exception as exception:
            print(
                'Listening for messages on {} threw an Exception: {}.'.format(
                    subscription_path, exception))
Esempio n. 3
0
def main(argv):
    """Main entrypoint to the integration with the Procurement Service."""

    if len(argv) != 1:
        print('Usage: python3 -m impl.step_2_account.app')
        return

    # Construct a service for the Partner Procurement API.
    database = JsonDatabase()
    procurement = Procurement(database)

    # Get the subscription object in order to perform actions on it.
    subscriber = pubsub_v1.SubscriberClient()
    subscription_path = subscriber.subscription_path(PROJECT_ID,
                                                     PUBSUB_SUBSCRIPTION)

    def callback(message):
        """Callback for handling Cloud Pub/Sub messages."""
        payload = json.loads(message.data)

        print('Received message:')
        pprint.pprint(payload)
        print()

        ack = False
        if 'entitlement' in payload:
            ack = procurement.handle_entitlement_message()
        elif 'account' in payload:
            ack = procurement.handle_account_message(payload['account'])
        else:
            # If there's no account or entitlement, then just ack and ignore the
            # message. This should never happen.
            ack = True

        if ack:
            message.ack()

    subscription = subscriber.subscribe(subscription_path, callback=callback)

    print('Listening for messages on {}'.format(subscription_path))
    print('Exit with Ctrl-\\')

    while True:
        try:
            subscription.result()
        except Exception as exception:
            print(
                'Listening for messages on {} threw an Exception: {}.'.format(
                    subscription_path, exception))