npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

kube-js

v0.1.2

Published

Simplified, lightweight Kubernetes API client with some useful extensions.

Downloads

6

Readme

kube-js

Build Status

Simplified, lightweight Kubernetes API client with some useful extensions for Nod.js.

Installation

Install via npm:

$ npm i kube-js --save

Examples

kube-js provides access to all the Kubernetes objects and includes some niceties for writing simpler code.

Basics

kube-js maps the URI paths in the Kubernetes API to sequences of objects chained together via properties and ending in a function. For example, to GET the ReplicationController named 'http-rc' in the Namespace 'my-project':

const Api = require('kube-js');
const core = new Api.Core({
  url: 'http://my-k8s-api-server.com',
  version: 'v1',  // Defaults to 'v1'
  namespace: 'my-project' // Defaults to 'default'
});

function print(err, result) {
  console.log(JSON.stringify(err || result, null, 2));
}

core.namespaces.replicationcontrollers('http-rc').get(print);

kube-js supports the Extensions API group. For example, GET the Deployment named http-deployment:

const ext = new Api.Extensions({
  url: 'http://my-k8s-api-server.com',
  version: 'v1beta1',  // Defaults to 'v1beta1'
  namespace: 'my-project' // Defaults to 'default'
});

ext.namespaces.deployments('http-deployment').get(print);

kube-js provides a helper to get in-cluster config and accessing the API from a Pod:

const Api = require('kube-js');
const core = new Api.Core(Api.config.getInCluster());

and a helper to get the current-context config from ~/.kube/config:

const Api = require('kube-js');
const core = new Api.Core(Api.config.fromKubeconfig());

Creating and updating

kube-js objects expose .post, .patch, and .put methods. Create the ReplicationController from the example above:

const manifestObject = require('./rc.json');
core.namespaces.replicationcontrollers.post({ body: manifestObject }, print);

or update the number of replicas:

const patch = { spec: { replicas: 10 } };
core.namespaces.replicationcontrollers('http-rc').patch({
  body: patch
}, print);

Using the correct API group and version

kube-js client includes functionality to help determine the correct Kubernetes API group and version to use based on manifests:

const Api = require('kube-js');
const api = new Api.Api({
  url: 'http://my-k8s-api-server.com',
  namespace: 'my-project'
});

const manifest0 = {
  kind: 'Deployment',
  apiVersion: 'extensions/v1beta1'
  ...
};
const manifest1 = {
  kind: 'ReplicationController',
  apiVersion: 'v1'
  ...
};

api.group(manifest0).ns.kind(manifest0).post({ body: manifest0 }, print);
api.group(manifest1).ns.kind(manifest1).post({ body: manifest1 }, print);

Object name aliases

kube-js supports the same aliases as kubectl (e.g., ns for namespaces) and the singular versions of the resource name (e.g., namespace for namespaces). We can shorten the example above:

core.ns.rc('http-rc').get(print);

Switching namespaces

You can call the namespace object to specify the namespace:

core.ns('other-project').rc('http-rc').get(print);

Query parameters

You can optionally specify query string object qs to GET endpoints. kube-js passes qs directly to request. For example to filter based on label selector:

core.ns.rc.get({ qs: { labelSelector: 'service=http' } }, print);

Label selector filtering

kube-js has a shortcut, matchLabels, for filtering on label selector equality:

core.ns.rc.matchLabels({ service: 'http' }).get(print);

and a more general match method based on Kubernetes Match Expressions:

core.ns.rc.match([{
  key: 'service',
  operator: 'In',
  values: ['http']
}, {
  key: 'deploy',
  operator: 'NotIn',
  values: ['production', 'staging']
}]).get(print);

ThirdPartyResources

You can extend the Kubernetes API using a ThirdPartyResource and kube-js:

const newResoure = {
  apiVersion: 'extensions/v1beta1',
  kind: 'ThirdPartyResource',
  metadata: {
    name: 'new-resource.kubernetes-client.io'
  },
  description: 'Example resource',
  versions: [{
    name: 'v1'
  }]
};

ext.thirdpartyresources.post({ body: newResource }, print);

and then extend an ThirdPartyResource API client with your new resources:

const thirdPartyResources = new Api.ThirdPartyResources({
  url: 'http://my-k8s-api-server.com',
  group: 'kubernetes-client.io',
  resources: ['customresources']  // Notice pluralization!
});

// Access `customresources` as if they were a regular Kubernetes object
thirdPartyResources.ns.customresources.get(print);
thirdPartyResources.addResource('newresources');  // Notice pluralization!
// Now access `newresources`
thirdPartyResources.ns.newresources.get(print);

ReplicationController Pods

kube-js provides a shortcut for listing all Pods matching a ReplicationController selector:

core.ns.rc.po.get(print);

kube-js deletes all the Pods associated with a ReplicationController when it deletes the ReplicationController. You can preserve the Pods:

core.ns.rc.delete({ name: 'http-rc', preservePods: true });

Watching and streaming

If you don't pass a callback to get, node-kubernetes returns a stream. This is useful for watching:

const JSONStream = require('json-stream');
const jsonStream = new JSONStream();

const stream = core.ns.po.get({ qs: { watch: true } });
stream.pipe(jsonStream);
jsonStream.on('data', object => {
  console.log('Pod:', JSON.stringify(object, null, 2));
});

You can access logs in a similar fashion:

const stream = core.ns.po.log({ name: 'http-123', qs: { follow: true } });
stream.on('data', chunk => {
  process.stdout.write(chunk.toString());
});

Note: the kube-apiserver will close watch connections eventually according to the [--min-request-timeout](http://kubernetes.io/docs/admin/kube-apiserver/ command line argument. kube-js does not attempt to reconnect when the kube-apiserver closes a connection.

Authenticating

kube-js supports Kubernetes apiserver authentication.

Basic authentication (with optional certificate authority):

const core = new Api.Core({
  url: 'https://my-k8s-api-server.com',
  ca: fs.readFileSync('cluster-ca.pem'),
  auth: {
    user: 'user',
    pass: 'pass'
  }
});

or without a certificate authority:

const core = new Api.Core({
  url: 'https://my-k8s-api-server.com',
  insecureSkipTlsVerify: true,
  auth: {
    user: 'user',
    pass: 'pass'
  }
});

token authentication:

const core = new Api.Core({
  url: 'https://my-k8s-api-server.com',
  auth: {
    bearer: 'token'
  }
});

and client certificate authentication:

const core = new Api.Core({
  url: 'https://my-k8s-api-server.com',
  ca: fs.readFileSync('cluster-ca.pem'),
  cert: fs.readFileSync('my-user-cert.pem'),
  key: fs.readFileSync('my-user-key.pem')
});

Passing options to request

kube-js uses request. You can specify request options for kube-js to pass to request:

const core = new Api.Core({
  url: 'https://my-k8s-api-server.com',
  request: {
    timeout: 3000
  }
});

Testing

kube-js includes unit tests and integration tests. Minikube is a tool that makes it easy to run integration tests locally.

Run the unit tests:

$ npm test

The integration tests use a running Kubernetes server. You specify the Kubernetes server context via the CONTEXT environment variable. For example, run the integration tests with the minikube context:

$ CONTEXT=minikube npm run test-integration

More Documentation

License

MIT