|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +# |
| 4 | +# Copyright 2020 Confluent Inc. |
| 5 | +# |
| 6 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +# you may not use this file except in compliance with the License. |
| 8 | +# You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, software |
| 13 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +# See the License for the specific language governing permissions and |
| 16 | +# limitations under the License. |
| 17 | +# |
| 18 | + |
| 19 | +# |
| 20 | +# This uses OAuth client credentials grant: |
| 21 | +# https://www.oauth.com/oauth2-servers/access-tokens/client-credentials/ |
| 22 | +# where client_id and client_secret are passed as HTTP Authorization header |
| 23 | +# |
| 24 | + |
| 25 | +import logging |
| 26 | +import functools |
| 27 | +import argparse |
| 28 | +import time |
| 29 | +from confluent_kafka import SerializingProducer |
| 30 | +from confluent_kafka.serialization import StringSerializer |
| 31 | +import requests |
| 32 | + |
| 33 | + |
| 34 | +def _get_token(args, config): |
| 35 | + """Note here value of config comes from sasl.oauthbearer.config below. |
| 36 | + It is not used in this example but you can put arbitrary values to |
| 37 | + configure how you can get the token (e.g. which token URL to use) |
| 38 | + """ |
| 39 | + payload = { |
| 40 | + 'grant_type': 'client_credentials', |
| 41 | + 'scope': ' '.join(args.scopes) |
| 42 | + } |
| 43 | + resp = requests.post(args.token_url, |
| 44 | + auth=(args.client_id, args.client_secret), |
| 45 | + data=payload) |
| 46 | + token = resp.json() |
| 47 | + return token['access_token'], time.time() + float(token['expires_in']) |
| 48 | + |
| 49 | + |
| 50 | +def producer_config(args): |
| 51 | + logger = logging.getLogger(__name__) |
| 52 | + return { |
| 53 | + 'bootstrap.servers': args.bootstrap_servers, |
| 54 | + 'key.serializer': StringSerializer('utf_8'), |
| 55 | + 'value.serializer': StringSerializer('utf_8'), |
| 56 | + 'security.protocol': 'sasl_plaintext', |
| 57 | + 'sasl.mechanisms': 'OAUTHBEARER', |
| 58 | + # sasl.oauthbearer.config can be used to pass argument to your oauth_cb |
| 59 | + # It is not used in this example since we are passing all the arguments |
| 60 | + # from command line |
| 61 | + # 'sasl.oauthbearer.config': 'not-used', |
| 62 | + 'oauth_cb': functools.partial(_get_token, args), |
| 63 | + 'logger': logger, |
| 64 | + } |
| 65 | + |
| 66 | + |
| 67 | +def delivery_report(err, msg): |
| 68 | + """ |
| 69 | + Reports the failure or success of a message delivery. |
| 70 | +
|
| 71 | + Args: |
| 72 | + err (KafkaError): The error that occurred on None on success. |
| 73 | +
|
| 74 | + msg (Message): The message that was produced or failed. |
| 75 | +
|
| 76 | + Note: |
| 77 | + In the delivery report callback the Message.key() and Message.value() |
| 78 | + will be the binary format as encoded by any configured Serializers and |
| 79 | + not the same object that was passed to produce(). |
| 80 | + If you wish to pass the original object(s) for key and value to delivery |
| 81 | + report callback we recommend a bound callback or lambda where you pass |
| 82 | + the objects along. |
| 83 | +
|
| 84 | + """ |
| 85 | + if err is not None: |
| 86 | + print('Delivery failed for User record {}: {}'.format(msg.key(), err)) |
| 87 | + return |
| 88 | + print('User record {} successfully produced to {} [{}] at offset {}'.format( |
| 89 | + msg.key(), msg.topic(), msg.partition(), msg.offset())) |
| 90 | + |
| 91 | + |
| 92 | +def main(args): |
| 93 | + topic = args.topic |
| 94 | + delimiter = args.delimiter |
| 95 | + |
| 96 | + producer_conf = producer_config(args) |
| 97 | + |
| 98 | + producer = SerializingProducer(producer_conf) |
| 99 | + |
| 100 | + print('Producing records to topic {}. ^C to exit.'.format(topic)) |
| 101 | + while True: |
| 102 | + # Serve on_delivery callbacks from previous calls to produce() |
| 103 | + producer.poll(0.0) |
| 104 | + try: |
| 105 | + msg_data = input(">") |
| 106 | + msg = msg_data.split(delimiter) |
| 107 | + if len(msg) == 2: |
| 108 | + producer.produce(topic=topic, key=msg[0], value=msg[1], |
| 109 | + on_delivery=delivery_report) |
| 110 | + else: |
| 111 | + producer.produce(topic=topic, value=msg[0], |
| 112 | + on_delivery=delivery_report) |
| 113 | + except KeyboardInterrupt: |
| 114 | + break |
| 115 | + |
| 116 | + print('\nFlushing {} records...'.format(len(producer))) |
| 117 | + producer.flush() |
| 118 | + |
| 119 | + |
| 120 | +if __name__ == '__main__': |
| 121 | + parser = argparse.ArgumentParser(description="SerializingProducer OAUTH Example" |
| 122 | + " with client credentials grant") |
| 123 | + parser.add_argument('-b', dest="bootstrap_servers", required=True, |
| 124 | + help="Bootstrap broker(s) (host[:port])") |
| 125 | + parser.add_argument('-t', dest="topic", default="example_producer_oauth", |
| 126 | + help="Topic name") |
| 127 | + parser.add_argument('-d', dest="delimiter", default="|", |
| 128 | + help="Key-Value delimiter. Defaults to '|'"), |
| 129 | + parser.add_argument('--client', dest="client_id", required=True, |
| 130 | + help="Client ID for client credentials flow") |
| 131 | + parser.add_argument('--secret', dest="client_secret", required=True, |
| 132 | + help="Client secret for client credentials flow.") |
| 133 | + parser.add_argument('--token-url', dest="token_url", required=True, |
| 134 | + help="Token URL.") |
| 135 | + parser.add_argument('--scopes', dest="scopes", required=True, nargs='+', |
| 136 | + help="Scopes requested from OAuth server.") |
| 137 | + |
| 138 | + main(parser.parse_args()) |
0 commit comments