Friday, June 17, 2016

Using Python and "requests" to monitor and read the OpenShift API.

As part of an effort to automate what I do with OpenShift, I had to learn how to take advantage of OpenShift's "watch" QueryParameter on some of its API's.

As I typically work with python I quickly learned, that watching streams is not so easy. That said, it can be done.

Below is an example of how I use this method to watch the routes API in openshift, and print out, the events, that happen in the "joe" namespace.
#!/bin/python

import requests
import json

s = requests.Session()

token = "lTBiDnvYlHhuOl3C9Tj_Mb-FvL0hcMMONIua0E0D5CE"
openshift_api="https://master.openshift.example.com:8443"
namespace="joe"

def streaming():
    req = requests.Request("GET",'{0}/oapi/v1/namespaces/{1}/routes?watch=true'.format(openshift_api, namespace),
                           headers={'Authorization': 'Bearer {0}'.format(token)},
                           params="").prepare()

    resp = s.send(req, stream=True, verify=False)
    print resp.status_code

    for line in resp.iter_lines():
        if line:
            yield line


def read_stream():

    for line in streaming():
        event = {}
        try: 
            event = json.loads(line)

            if event['type']:
                print event 
 
        except Exception as e: 
            print e
            continue

read_stream() 

No comments:

Post a Comment

Its the little things (like opening a web browser)

Sometimes as your developing a solution/script for a problem your faced with interesting challenges where the dumbest workaround (opening a ...