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.

import requests
import json

s = requests.Session()

token = "lTBiDnvYlHhuOl3C9Tj_Mb-FvL0hcMMONIua0E0D5CE"

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

    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 = {}
            event = json.loads(line)

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