Last active
April 16, 2020 22:12
-
-
Save jwreagor/979f3436244d8c22b21ccc5a925a9ca5 to your computer and use it in GitHub Desktop.
Kubernetes Watcher written in Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
// You use the `ResourceVersion` when making the initial query. So keep track | |
// of that upon successful reads and when you need to recreate the watcher from | |
// the last known point, pass in the `ResourceVersion` in the query. | |
const fs = require('fs') | |
const http = require('http') | |
const K8S_HOST = process.env['K8S_HOST'] || '10.100.0.1' | |
const K8S_SECRET = process.env['K8S_SECRET'] || | |
fs.readFileSync('/var/run/secrets/kubernetes.io/serviceaccount/token', 'utf-8') | |
var req = http.request({ | |
protocol: 'http:', | |
host: K8S_HOST, | |
port: 8080, | |
method: 'GET', | |
path: '/api/v1/namespaces?watch=true', | |
headers: { | |
Authorization: 'Bearer ' + K8S_SECRET | |
} | |
}, (res) => { | |
console.log('Watching namespace events...') | |
res.setEncoding('utf8') | |
res.on('data', (chunk) => { | |
const rawEvents = chunk.split('\n') | |
rawEvents.forEach(function (rawEvent) { | |
if (rawEvent.length > 0) { | |
const event = JSON.parse(rawEvent) | |
console.log(' %s was %s', event.object.metadata.name, event.type.charAt(0) + event.type.substring(1).toLowerCase()) | |
} | |
}) | |
}) | |
res.on('end', () => { | |
console.log(' Event stream closed...') | |
}) | |
}) | |
req.on('error', (err) => { | |
console.log('Problem with request: %s', err.message) | |
}); | |
req.end() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment