OKD Node.js Client
This Node.JS RESTful client API for Kubernetes/OpenShift. This library helps you use JavaScript to write simple programs to automate things like deploy images, listen for cluster events, build/create containers (OpenShift only at the moment), watch push/pull images etc. Or more sophisticated things like send me an email/slack message if a particular pod crash.
Index
- Installing
- Login
- Initialize With Token
- Select Namespace
- Components
- CRUD
- Watch
- Concrete Implementations
- Bot Example
Installing
npm i okd-api
const login okd =
Login into OpenShift
This API exposes two objects login
which handles the login against a OpenShift cluster.
let config = cluster:'https://okd.address.com/' user: 'user' password: '***' strictSSL: true || false
The login function receive an configuration following object:
- cluster Kubernetes server URL.
- user, password Your user and password.
- strictSSL Some implementations like Minishfit use a self-signed SSL certificate which trigger a security warning for https clients, is that your case turn this to false.
The login functions returns an okd
object after it finish the authentication with the server, the okd
object is the one in charge of to talk against the API server.
With Token
If you already have a token (because you previously acquired one through authentication) you can provide the cluster URL and the token.
const cluster = `https://minishfit.vm:8443/` const token = 'v0tDED5vjN7Vv...' let imagestream = is imagestreamall
Namespace
Namespaces is a way to partition resources across your Kubernetes/OpenShift cluster. This mean that to access a particular resource such as BuildConfig you need first need to specify the namespace.
okd /* Now you can use this okd object for resources in the dev-665 namespace*/ okdsvcall /*...*/
If you need to operate across multiple namespaces you just need to instantiate multiple objects.
{ const cluster = `https://my-cluster.com/` const token = 'v0tDED5vjN7Vv...' return } myScriptsmyScriptsmyScripts
Retrieve Token
Once the client login with the server you receive an OAuth token to get this token and other information by calling the config
method.
okd
Components
This are the objects supported at the moment:
-
OpenShift
- ImageStream
- BuildConfig
- Build
- DeploymentConfig
- Router
- Project Requires Admin
-
Kubernetes
- Deployment
- Service
- Pod
- ReplicaSet
- Namespace Require Admin
To access those elements like this:
okdis // OpenShift ImageStream okdbc // OpenShift BuildConfig okdbuild // OpenShift Build okdproject // OpenShift Project okddc // OpenShift DeploymentConfig okdroute // OpenShift Routes okdsvc // OpenShift/Kubernetes services okdpod // OpenShift/Kubernetes pod okddeploy // OpenShift/Kubernetes deployment okdrs // OpenShift/Kubernetes replica sets okdnamespace // OpenShift/Kubernetes Namespaces
CRUD
Each of this objects support a common set of functionalities which are related to the basic HTTP REST verbs. Let's talk in more detail about those functions.
Find All
Returns a promise which resolve in the future with a list of all the objects of a particular type.
// Returns a promise with all imagestreams in the namespace dev-655. okd is all // All Services okd svc all
By Name
You can also find resources by name:
okd is
Returns Imagestream called nodejs-image
.
Remove
To remove a resource from the cluster:
okd is
It returns a promise with the response from the server.
Creating
To create Kubernetes/OpenShift objects you can use the following:
let deploy = okddeploy deploy
Usually you want to describe the configuration of your components and for that reason there is a template system.
Template
Objects in Kubernetes are defined using a templates like this one:
apiVersion: apps/v1beta1kind: Deploymentmetadata: name: <%=name%> labels: app: <%=name%>spec: replicas: 1 selector: matchLabels: app: <%=name%> template: metadata: labels: app: <%=name%> spec: containers: - name: <%=name%> image: <%=image%> command: ['sh', '-c', 'echo Hello Kubernetes! && sleep 3600'] ports: - containerPort: 8080
This is what a Deployment looks like, this API support template parameters that helps you create reusable templates, in this example we can replace the <%=name%>
and <%=image%>
placeholders with actual information like this:
let deploy = okd deploy deploy
This code push to the server a Deployment object with the following shape:
apiVersion: apps/v1beta1kind: Deploymentmetadata: name: my-deployment labels: app: my-deploymentspec: replicas: 1 ... containers: image: nginx ...
Editing template at Runtime
To modify the template at run-time you can do the following:
let deploy = okddeploylet object = deploy_tmpl //pass by reference objectmetadataname = 'deploy-y'deploy // we send the template with the amended field.
Faster Template
Template operations above can be done faster by using this shortcut:
okd okd
from_template will auto-detect the type of template you try to use and if its supported you can perform the actions for example:
let deploy = okd
If deployment.yml
is a valid Deployment template it will return an okd.deploy
object, equivalent to something like this:
let deploy = okddeploy
The difference is that the information about the deployment is encapsulated inside the object, allowing you act over the object.
//['tmpl0.yml','tmpl1.yml', 'tmpl2.yml'... ] let objs = './deploy.yml''pod.yml' 'route.yml' // create all objs //delete all objs
Update
To update a Kubernetes component such as Deployment you can use the put
or update
method, this method fetch a copy of the actual resource from the server and apply a merge, for example:
Let's assume an imaginary object A
is in the cloud:
A a:1 b:2 c:3 d: e: 5
To update the e
property to 1 we can do:
okdAtype
After we execute this command we should get this:
A a:1 b:2 c:3 d: e: 1
In the following example we are going to update a Deployment controller test
to 3 replicas.
Patch
Another way to update Kubernetes object is to use the patch
method, this method requires the json-PATCH protocol, for example:
let update = op:'replace' path:'/spec/template/spec/containers/0/image' value: 'awesome:test-23' let deploy = okddeploy deploy
This will update the deployment object and automatically this change will trigger a re-deployment.
Watch
Kubernetes/OpenShift uses an event system to keep track of changes in the cluster, we can listen to this changes individually using the watch
function.
okdokd_object
-
name The name of the object we want to listen for state change.
-
event =>
A function that receives Kubernetes events.
The event have the form of:
type: "MODIFIED" /* DELETE, ADDED */ object: kind: "Service" apiVersion: "v1" /*...*/
Type define the action and object is basically a Kubernetes/OKD object definition.
Usage Example
okd // Watch for new buildsokdis // Watch for for actions in this podokdpod
Watching All Objects
Or we can watch them all using the watch_all
function, and listen any events in the namespace
for a particular object type.
okdresource
This function receives array of events as parameters. To watch the pods running we can do this:
const login = login //{cluster: '****', user:'user', ...}
We call a watch_all
function a pass a function called watch_test
this function should have the following signature:
{ let type = events0type let phase = events0objectstatusphase let pod_name = events0objectmetadataname // Only show compute pods in OKD ;) if! 'openshift.io/build.name' in annotations console console }
Contrary to the cases above, here should use a callback because we are dealing with a stateful connection which will remain as long as the timeout limit establish by the cluster administrator. The event type is similar to the one we used above.
Concrete Implementations
Some Kubernetes/OKD objects have unique functionalities, in the case of pod for example aside from common functionalities they also implement other functions like logs, exec, etc.
Build Configuration
Trigger A Binary Build
For now the only way to trigger a build in using this API is by uploading a binary.
For example:
{ let tmp_file = name || './okd.tar.gz' let ret = // tar the directory, forget parent return tmp_file} /* tar the workspace folder */let file = okdbc // micro-1 should be an existing BuildConfig
Pods
Pods are the building blocks for Kubernetes applications, they also expose some functionalities that can be useful:
Logs
There is two options to watch pod logs first is getting the whole bulk, by using the pod.logs
method:
okdpod
This will return the logs for the pod my-pod
npm info using npm@6.4.1npm info using node@v10.12.0npm info lifecycle my-app@1.0.0~prestart: my-app@1.0.0npm info lifecycle my-app@1.0.0~start: my-app@1.0.0> my-app@1.0.0 start /opt/app-root/src> node app.js
This method give you a snapshot of the current state but you will miss further updates, to keep streaming logs in real-time you can use the pod.stream_logs
method:
okdpod
This method keeps track of the latest logs update in the pod.
If you are running multiple containers in a single pod then you can target that container using function container
like this:
okd pod
Writing A Bot
Let's build a bot that fetch the logs of any container that is being deploying in our cluster, this can be interesting to follow the stages of an applications from building, testing and execution from one place.
Login
const login = // {cluster: '****', user:'user', ...}
We have done the login and we setup the watch for the namespace testing
next we need to create a function that watch and capture the transition of pods from Pending
to Running
.
{ let pending = {} // Closure that will return { // for more info about event object --> //https://kubernetes.io/docs/reference/federation/v1/definitions/#_v1_event let annotations = events0objectmetadataannotations let labels = events0objectmetadatalabels let phase = events0objectstatusphase let pod_name = events0objectmetadataname // Capture pods transitioning from Pending to Running. // This means being deployed... ifphase === 'Pending' console console pendingpod_name = true // If the pod goes from Pending to Running... // ... We show the logs. ifphase === 'Running' && pendingpod_name console // clear screen... console console // Watch the logs for this pod: pod_name okdpod pendingpod_name = false }}
This function does just that it just listen for pods doing the transitions and then we finally use the pod.stream_logs
to retrieve the logs from the targeted pod. If we run this program we are going to get something like this: