Giter Club home page Giter Club logo

javascript's Introduction

Javascript Kubernetes Client information

Build Status Client Capabilities Client Support Level Build and Deploy Docs

The Javascript clients for Kubernetes is implemented in typescript, but can be called from either Javascript or Typescript. The client is implemented for server-side use with Node.

The request library is currently being swapped to fetch. See the fetch migration docs for more information and progress.

Installation

npm install @kubernetes/client-node

Example code

List all pods

const k8s = require('@kubernetes/client-node');

const kc = new k8s.KubeConfig();
kc.loadFromDefault();

const k8sApi = kc.makeApiClient(k8s.CoreV1Api);

const main = async () => {
    try {
        const podsRes = await k8sApi.listNamespacedPod('default');
        console.log(podsRes.body);
    } catch (err) {
        console.error(err);
    }
};

main();

Create a new namespace

const k8s = require('@kubernetes/client-node');

const kc = new k8s.KubeConfig();
kc.loadFromDefault();

const k8sApi = kc.makeApiClient(k8s.CoreV1Api);

const namespace = {
    metadata: {
        name: 'test',
    },
};

const main = async () => {
    try {
        const createNamespaceRes = await k8sApi.createNamespace(namespace);
        console.log('New namespace created: ', createNamespaceRes.body);

        const readNamespaceRes = await k8sApi.readNamespace(namespace.metadata.name);
        console.log('Namespace: ', readNamespaceRes.body);

        await k8sApi.deleteNamespace(namespace.metadata.name, {});
    } catch (err) {
        console.error(err);
    }
};

main();

Create a cluster configuration programatically

const k8s = require('@kubernetes/client-node');

const cluster = {
    name: 'my-server',
    server: 'http://server.com',
};

const user = {
    name: 'my-user',
    password: 'some-password',
};

const context = {
    name: 'my-context',
    user: user.name,
    cluster: cluster.name,
};

const kc = new k8s.KubeConfig();
kc.loadFromOptions({
    clusters: [cluster],
    users: [user],
    contexts: [context],
    currentContext: context.name,
});
const k8sApi = kc.makeApiClient(k8s.CoreV1Api);
...

Additional Examples and Documentation

There are several more JS and TS examples in the examples directory.

Documentation for the library is split into two resources:

  1. The Kubernetes API Reference is the source-of-truth for all Kubernetes client libraries, including this one. We suggest starting here!
  2. The Typedoc autogenerated docs can be viewed online and can also be built locally (see below)

Compatibility

Prior to the 0.13.0 release, release versions did not track Kubernetes versions. Starting with the 0.13.0 release, we will increment the minor version whenever we update the minor Kubernetes API version (e.g. 1.19.x) that this library is generated from.

Generally speaking newer clients will work with older Kubernetes, but compatability isn't 100% guaranteed.

client version older versions 1.20 1.21 1.22 1.23 1.24 1.25 1.26 1.27 1.28
0.14.x - x x x x x x x x
0.15.x - + x x x x x x x
0.16.x - + + x x x x x x
0.17.x - - + + + x x x x
0.18.x - - - + + + x x x
0.19.x - - - - - - + + x
0.20.x - - - - - - - + +

Key:

  • Exactly the same features / API objects in both javascript-client and the Kubernetes version.
  • + javascript-client has features or api objects that may not be present in the Kubernetes cluster, but everything they have in common will work.
  • - The Kubernetes cluster has features the javascript-client library can't use (additional API objects, etc).
  • x The Kubernetes cluster has no guarantees to support the API client of this version, as it only promises n-2 version support. It is not tested, and operations using API versions that have been deprecated and removed in later server versions won't function correctly.

Known Issues

  • Multiple kubeconfigs are not completely supported. Credentials are cached based on the kubeconfig username and these can collide across configs. Here is the related issue.
  • The client wasn't generated for Kubernetes 1.23 due to limited time from the maintainer(s)

Development

All dependencies of this project are expressed in its package.json file. Before you start developing, ensure that you have NPM installed, then run:

npm install

(re) Generating code

npm run generate

Documentation

Documentation is generated via typedoc:

npm run docs

To view the generated documentation, open docs/index.html

Formatting

Run npm run format or install an editor plugin like https://github.com/prettier/prettier-vscode and https://marketplace.visualstudio.com/items?itemName=EditorConfig.EditorConfig

Linting

Run npm run lint or install an editor plugin like https://github.com/Microsoft/vscode-typescript-tslint-plugin

Testing

Tests are written using the Chai library. See config_test.ts for an example.

To run tests, execute the following:

npm test

Contributing

Please see CONTRIBUTING.md for instructions on how to contribute.

javascript's People

Contributors

ananya2001-an avatar bbatha avatar brendanburns avatar brendandburns avatar burn2delete avatar davidisa avatar dependabot[bot] avatar dominykas avatar drubin avatar edvald avatar ericpromislow avatar hardillb avatar k8s-ci-robot avatar macrozone avatar mansona avatar mattxwang avatar mbohlool avatar mclarke47 avatar mstruebing avatar ndeloof avatar nicklason avatar nikhita avatar rluvaton avatar schrodit avatar sheldonkwok avatar spiffxp avatar stefancenusa avatar tattdcodemonkey avatar tux-rampage avatar uesyn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

javascript's Issues

How to Watch with KubeConfig configured from cluster

When creating applications which needs to Watch the kubernetes api, there is no way of creating a new KubeConfig object created by credentials provided by kubernetes (or openshift).

Basically the Config::fromCluster() is what we need, but then available on the KubeConfig class like

const kc = new k8s.KubeConfig();
kc.fromCluster();  // <-- this is missing and so required!

Or am I doing something completely wrong here?
It's just that the application which needs to query the kubernetes api, is running in kubernetes itself, so .kube/config files are not working in this usecase.

Package.json missing @types/bluebird

The package.json currently has a dependency on the bluebird module, but doesn't include the typings for it. The means that any Promise<...> objects returned from the Core_V1Api are typed as any.

The fix is to include a dependency on @types/bluebird.

A temporary workaround is for the user to install @types/bluebird.

Rename typescript to javascript through the code

I saw the examples in the main page refer to the package name as typescript and I assume we will have them in other docs/code. This issue is to track the progress of renaming all of them to javascript.

Creating a Pod

Dear team, I looked for a way to create a pod but could not find while searching code.
Is there a doc/manual page?

Needs to be Regenerated

New versions of kubernetes have been released, this requires that the clients be regenerated for v1.10 and v1.11

Recommended tsconfig settings

There are a few tsconfig settings you might consider adopting in this project.

  • esModuleInterop: make TypeScript's ES6 module import/export semantics more in line with standards, and enables other tools to understand the static module graph for things like tree-shaking.
  • allowSyntheticDefaultImports: allow importing a commonjs module as the default export
  • strict: make TypeScript extra pedantic about types. This ensures TypeScript is doing the best job possible enforcing the correctness of your code. It also ensures that generated d.ts files are free of loose definitions, allowing strict consumers to benefit from tighter type definitions.
  • forceConsistentCasingInFileNames: ensure we always warn when casing differs because some file systems (cough NTFS cough) aren't strict about casing by default. This helps ensure Windows contributors don't get failures in CI due to casing issues.
  • importHelpers: keep package size down by pulling out common helpers into external dependencies (these can be bundled into the final artifact by a build tool like rollup if you desire).
  • declarationMap: if you're ok including the original source in the package (IMO very nice for debugging and go-to-definition for inspecting implementation details), declarationMap is needed to make it work.

attach fix for UnhandledPromiseRejectionWarning

For anyone with the the following error:

ode:16396) UnhandledPromiseRejectionWarning: Error: Server responded with a non-101 status: 500 Internal Server Error
Response Headers Follow:
date: Mon, 24 Sep 2018 16:01:57 GMT
content-length: 75
content-type: text/plain; charset=utf-8

    at WebSocketClient.failHandshake (../nodes/node_modules/websocket/lib/WebSocketClient.js:339:32)
    at ClientRequest.<anonymous> (../nodes/node_modules/websocket/lib/WebSocketClient.js:278:18)
    at ClientRequest.emit (events.js:182:13)
    at HTTPParser.parserOnIncomingClient (_http_client.js:555:21)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:109:17)
    at TLSSocket.socketOnData (_http_client.js:441:20)
    at TLSSocket.emit (events.js:182:13)
    at addChunk (_stream_readable.js:283:12)
    at readableAddChunk (_stream_readable.js:264:11)
    at TLSSocket.Readable.push (_stream_readable.js:219:10)
    at TLSWrap.onread (net.js:639:20)
(node:16396) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:16396) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

just simply override the following code in file node_modules/@kubernetes/client-node/dist/attach.js,

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const querystring = require("querystring");
const web_socket_handler_1 = require("./web-socket-handler");
class Attach {
    constructor(config) {
        this.handler = new web_socket_handler_1.WebSocketHandler(config);
    }
    attach(namespace, podName, containerName, stdout, stderr, stdin, tty) {
        return __awaiter(this, void 0, void 0, function* () {
            const query = {
                stdout: stdout != null,
                stderr: stderr != null,
                stdin: stdin != null,
                tty,
                container: containerName,
            };
            const queryStr = querystring.stringify(query);
            const path = `/api/v1/namespaces/${namespace}/pods/${podName}/attach?${queryStr}`;
            const conn = yield this.handler.connect(path, null, (streamNum, buff) => {
                web_socket_handler_1.WebSocketHandler.handleStandardStreams(streamNum, buff, stdout, stderr);
            });
            if (stdin != null) {
                web_socket_handler_1.WebSocketHandler.handleStandardInput(conn, stdin);
            }
            return conn;
        });
    }
}
exports.Attach = Attach;
//# sourceMappingURL=attach.js.map

Hope it works for you too!

Helper function for app client creation

Hello,

I was trying to use the Apps API instead of the Core API and noticed there aren't helpers for creating clients from a config. I ended up writing my own that look almost identical to the config ones provided for Core. Should we add helpers for Apps as well? I can just submit a PR.

Thanks,
Sheldon

Create a SECURITY_CONTACTS file.

As per the email sent to kubernetes-dev[1], please create a SECURITY_CONTACTS
file.

The template for the file can be found in the kubernetes-template repository[2].
A description for the file is in the steering-committee docs[3], you might need
to search that page for "Security Contacts".

Please feel free to ping me on the PR when you make it, otherwise I will see when
you close this issue. :)

Thanks so much, let me know if you have any questions.

(This issue was generated from a tool, apologies for any weirdness.)

[1] https://groups.google.com/forum/#!topic/kubernetes-dev/codeiIoQ6QE
[2] https://github.com/kubernetes/kubernetes-template-project/blob/master/SECURITY_CONTACTS
[3] https://github.com/kubernetes/community/blob/master/committee-steering/governance/sig-governance-template-short.md

Missing Content-Type header on patch operation

Hi,
Everytime I try to patch a node, I hit a HTTP 415
the server responded with the status code 415 but did not return more information.

After some researches, I found that the API wait for Content-Type: application/strategic-merge-patch+json header for PATCH operations.
But this header is not set.

Is there any way I can override headers before sending the request ?

install from git via npm

#65 has instructions for a local install from git, however this is inconvenient for CI/CD processes as we need to download and build a dependency which results in longer build times, and increased complexity.

NPM supports installs from github via npm install kubernetes-client/javascript, however the current directory structure prevents this from working.

To solve these issues:

  • flatten the project structure so package.json is in the root of the repo
  • stick to one project per repo, if there is a jquery client in the future it should have it's own repo

npm pack not packaging the dist directory

I just installed the package and encountered a build error because the modules were not found in index.ts. At face value seems that the problem is that index.ts should be index.d.ts but delving a bit deeper into the problem, it seems that the npm package does not contain the contents of the dist directory generated by an npm build (of the kubernetes-client project).

Prevent watch from exiting

Currently the watch function will exit if the stream is empty, we should have a flag for continuous monitoring. Or is there a better way to be watching for resources?

Error while listing deployments

var kc = new k8s.KubeConfig();
kc.loadFromDefault();

var k8sApi = kc.makeApiClient(k8s.AppsV1beta1Deployment);
//var k8sApi = kc.makeApiClient(k8s.AppsV1beta1DeploymentList);

k8sApi.listNamespacedDeployment.then( (res) => {
    return res.body;
});

i get this error:

"TypeError: apiClient.setDefaultAuthentication is not a function"

Originally posted by @scher200 in #103 (comment)

api does not expose Core_v1Api to typescript

In the following example

import k8s = require('@kubernetes/client-node');
var client: k8s.Core_v1Api;
client = k8s.Config.defaultClient();

typescript produces the following error

error TS2694: Namespace '"<path>/@kubernetes/client-node/index"' has no exported member 'Core_v1Api'.

This could be related to #23 but I also did not see it exported in the distribution. This example is overly simplified to demonstrate the problem.

Long lists of positional arguments on API methods

This appears to be more of an upstream issue with swagger-codegen (ref swagger-api/swagger-codegen#7930) but I wanted to flag it here.

Basically as it stands, adding a new option is likely to break compatibility, and the usability isn't great as it is... To illustrate I just wrote this call: client.listNamespacedPod(namespace, undefined, undefined, undefined, undefined, labelSelector) - who knows what sequence the parameters will be in for the next k8s version :)

I'd at least suggest setting the appropriate configuration flag if the above issue gets resolved.

Consider making refactoring API object model

I propose the following changes to the API object model:

  1. Make non-required fields (and fields that aren't apiVersion or kind) in all API objects optional e.g., containers: V1Container -> containers?: V1Container.
  2. Automatically generate type guards to make it easy to condition on the types of API objects you're interacting with in TypeScript.
  3. Change all API objects in api.ts to be interfaces rather than classes.
  4. Add a utility type that represent the set of top-level API objects (e.g., type CoreTypes = AppsV1beta1Deployment | AppsV1beta1DeploymentList | [...]), so that you can deal with a well-typed collection of objects for some API group.

Justification for (1)

Suppose I manually construct an object so that I can later kubectl it to the server:

        const svc = <k8s.V1Service>{
          "kind": "Service",
          "apiVersion": "v1",
          "metadata": {
            name: name,
          },
          "spec": {}
        };

This will actually not compile because k8s.V1Service requires a status field. This field need not exist for our purposes, though. It is possible to work around this by casting to any first (e.g., const svc = <k8s.V1Service><any>{ [...] }, but this is not a particularly compelling "blessed pattern", because status actually is an optional field.

This approach will make apps using --strictNullCheck a little more verbose, but really not checking null here is just hiding from the real issue, which is that it can very well be null.

Justification for (2)

Using the API objects in api.ts is pretty painful in TypeScript.

Let's say you are writing an app in TypeScript, and have some object const foo: AppsV1beta1Deployment | AppsV1beta2Deployment | ExtensionsV1beta1Deployment;.

If you want to figure out which of these types foo really has at runtime, you would ordinarily do something like:

if (foo instanceof AppsV1beta1Deployment) {` 

But if you have built up an API object using an object literal (as we did in (1)), then that object literal will not be an instanceof any of them, because it will be of type object. This means that you have to write your own type guard that checks kind and apiVersion, but really this should just be exposed by the library itself.

Furthermore, if you did want to use the official constructors in api.ts, you'd need to do something like the below:

const svc = new k8s.V1Service();
svc.metadata = new k8s.V1ObjectMeta();
svc.metadata.name = name;
svc.spec = new k8s.V1ServiceSpec();

Needless to say, this is not ideal.

Justification for (3)

In addition to points (1) and (2), we're not exposing any methods or custom constructors on the API object classes in api.ts, so we're not getting any benefit from them being classes, and there are significant drawbacks.

Using v1beta1 API

Is there a way to get the beta API to use it for making requests? I want to make a createNamespacedDeployment request, but it only exists on Extensions_v1beta1Api.

auth with access token instead of username and password

Hi there,

I'm trying to use this on the OTC (open telecom cloud).

They provide a forked version for kubectl here:
https://github.com/Cusfomer-kubectl/kubernetes

And in the end I have a kube config file that looks like this:

apiVersion: v1
clusters:
- cluster:
    cluster-uuid: 4f65a35c-a9c8-4c98-87a4-xxxxxxxxxxxx
    server: https://cce.eu-de.otc.t-systems.com
  name: fg-dev
contexts:
- context:
    cluster: fg-dev
    user: frederik_berg
  name: fg-dev
current-context: fg-dev
kind: Config
preferences: {}
users:
- name: frederik_berg
  user:
    access-key: <access-key consisting of uppercase alphanum chars>
    region-id: eu-de
    secret-key: <secret-key consisting of mixed case alphanum chars>

the config_types.js looks like it dosn't support this:

function userIterator() {
    return function (elt, i, list) {
        if (!elt.name) {
            throw new Error(`users[${i}].name is missing`);
        }
        let token = null;
        if (elt.user["token"]) {
            token = elt.user["token"];
        }
        if (elt.user["token-file"]) {
            token = fs.readFileSync(elt.user["token-file"]);
        }
        return {
            name: elt.name,
            certData: elt.user["client-certificate-data"],
            certFile: elt.user["client-certificate"],
            keyData: elt.user["client-key-data"],
            keyFile: elt.user["client-key"],
            authProvider: elt.user["auth-provider"],
            token: token,
        };
    };
}

Is there any way I can make this work?

P.S. this is using the newest version available from npm/yarn not from git directly

Add a client for the pod read-log endpoint

Command-line: kubectl log <pod-name>
Documentation: https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.11/#read-log-pod-v1-core

From what I read so far on kubernetes/kubernetes#13885, the /log endpoints only expects binary.k8s.io as protocol. Without it (but still sending the *.channel.k8s.io ones), a 403 Forbidden status code is returned.

I'll try to submit a PR for this in the upcoming days, suggestions are welcome.

Right now I'm trying to fit this into WebSocketHandler, but there is already a binary handler that expects the first byte of the message to be the channel number, which is not the case for the /log endpoint. See https://github.com/kubernetes-client/javascript/blob/master/node-client/src/web-socket-handler.ts#L89-L94

Vulnerable dependency

When running nsp against a project with @kubernetes/client-node 0.2.1 The following vulnerable dependency is highlighted:

> nsp check

(+) 1 vulnerability found
┌────────────┬────────────────────────────────────────────────────────────────────┐
│            │ Sandbox Breakout / Arbitrary Code Execution                        │
├────────────┼────────────────────────────────────────────────────────────────────┤
│ Name       │ static-eval                                                        │
├────────────┼────────────────────────────────────────────────────────────────────┤
│ CVSS       │ 6.2 (Medium)                                                       │
├────────────┼────────────────────────────────────────────────────────────────────┤
│ Installed  │ 0.2.3                                                              │
├────────────┼────────────────────────────────────────────────────────────────────┤
│ Vulnerable │ <=1.1.1                                                            │
├────────────┼────────────────────────────────────────────────────────────────────┤
│ Patched    │ >=2.0.0                                                            │
├────────────┼────────────────────────────────────────────────────────────────────┤
│ Path       │ [email protected] > @kubernetes/[email protected] > [email protected] >  │
│            │ [email protected]                                                  │
├────────────┼────────────────────────────────────────────────────────────────────┤
│ More Info  │ https://nodesecurity.io/advisories/548                             │
└────────────┴────────────────────────────────────────────────────────────────────┘

The static-eval package should be upgraded to version 2.0.0.

createNamespacedDeployment not available

Hi! I'm using 0.2.1 and i've noticed that createNamespacedDeployment is not available on Core_v1Api
It is available only under Apps_v1Api but it is not clear for me how to use it
Can you point me in some direction please?

GKE on Windows: Failed to refresh token

When using Google Kubernetes Engine on Windows, the Kubernetes client
sometimes fails with the following error:

C:\...\node_modules\@kubernetes\client-node\dist\config.js:99
                            throw new Error('Failed to refresh token: ' + result);
                            ^

Error: Failed to refresh token:
    at KubeConfig.applyAuthorizationHeader (C:\...\node_modules\@kubernetes\client-node\dist\config.js:99:35)
    at KubeConfig.applyOptions (C:\...\node_modules\@kubernetes\client-node\dist\config.js:126:14)
    at KubeConfig.applyToRequest (C:\...\node_modules\@kubernetes\client-node\dist\config.js:138:14)
    at Core_v1Api.createNamespace (C:\...\node_modules\@kubernetes\client-node\dist\api.js:27561:38)
    at Object.<anonymous> (C:\...\create-namespace.js:19:5)
    at Module._compile (module.js:643:30)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
    at Function.Module.runMain (module.js:684:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

The content of result.stderr:

'C:\\Users\\cbuchacher\\AppData\\Local\\Google\\Cloud\' is not recognized as an internal or external command,\r\noperable program or batch file.\r\n'

The content of user.authProvider.config['cmd-path']:

C:\Users\cbuchacher\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\gcloud.cmd

Retry for transient faults

Is it supposed to handle transient faults like 504 by retrying, or have users handle?
It seems to me the fix could be as simple as using one of request wrappers like node-request-retry in place of request, for example.
Any thoughts would be appreciated.

Every property in Typescript defined as required

It seems the conversion from Swagger to TypeScript incorrectly makes every parameter on request body types required. In a lot of cases the request parameters contain all of the properties that you'd expect when fetching objects, which ofter you can't use in the request body, so the only feasible workaround is to cast to with <any> or Partial<T>. For example, status is required in the interface for the body for createNamespace, which of course doesn't make sense when creating a namespace.

I'm not sure if this is an upstream issue with swagger-codegen or the configuration, but for the library to work as expected, there probably needs to be a separation between types returned from read/list calls, and the types used for create/patch calls.

Let me know if we can help with this, we're likely to be heavy users of the library so we're happy to contribute, but would probably need some pointers to get started .)

Using with Typescript

I'm trying to use the node client from a Typescript file, but I can get the compiler to be happy when including it. Doing:
import { Config } from '@kubernetes/client-node/dist/src/config';
the compiler complains that it can't find the definition file for bluebird. This is because it's in the devDependencies of the client's package.json, so it doesn't get installed when doing npm install.

What is the recommended way to use the package from Typescript? An example would be appreciated.

insecure-skip-tls-verify is Ignored in Kube Config

When using var k8sApi = k8s.Config.defaultClient(); to get the default client, if the users .kube/config file includes a context with insecure-skip-tls-verify the certificate-authority is not necessarily going to be present. See example below:

- cluster:
    insecure-skip-tls-verify: true
    server: https://127.0.0.1:443
  name: my-cluster

In these cases the call to defaultClient() fails with the following error:

Uncaught Error: clusters[0].cluster.[certificate-authority-data, certificate-authority] is missing

This is trigged by Config Types validation code which tests for a certificate authority even if insecure-skip-tls-verify is set to true. Source

This prevents using this library even if the currently set context does provide a context-authority since all context configurations are validated during the iteration.

I would like to be able to connect to some clusters using the insecure flag.

Exec not working with authentication

Error : UnhandledPromiseRejectionWarning: TypeError: Cannot set property 'Authorization' of undefined

Raised from here (opts.headers does not exists) https://github.com/kubernetes-client/javascript/blob/master/node-client/src/config.ts#L156

When I patch it :

if (token) {
            if(!opts.headers) {
                opts.headers = {};
            }
            opts.headers['Authorization'] = token;
 }

I get : Error: Server responded with a non-101 status: 400 Bad Request at WebSocketClient.failHandshake (audit-id: 8c520bd1-f6b8-4c98-9175-b77e23724fc8)

I'm using GCE with Kubernetes 1.8 with .kube/config's user :

name: kubectl-exec
  user:
    token: e...Q

my script :

import k8s = require('@kubernetes/client-node');
let command = process.argv[2];

let kc = new k8s.KubeConfig();
kc.loadFromFile(process.env['HOME'] + '/.kube/config');

let exec = new k8s.Exec(kc);
exec.exec('default', 'dep-yolo-6476bc5465-9s6bm', 'yolo', command, process.stdout, process.stderr, process.stdin, true /* tty */);

Other commands (list namespaces, get pod ...) are working fine

How to use watch with token and crt

It seems the watch class only accepts a KubeConfig object, the example shows loading from a file.

However within a pod we should be using token and crt. How do we apply these to the Watch object?

Config: read from Buffer or create from Constructor

We have a use-case of loading config params from another Json Object, loaded from persistence layer - as the target cluster is dynamic in our case.

It would be helpful to have Config read from Buffer or by invoking parameterised constructor:

{
  kubernetesPassword: string;
  kubernetesUrl: string;
  kubernetesUserName: string;
  registrySecret: string;
  caCert: string;
  cert: string;
  key: string;
}

loadFromCluster does not exist

71f0ac8


const kc = new k8s.KubeConfig();
kc.loadFromCluster();

const k8sApi = kc.makeApiClient(k8s.Core_v1Api);

k8sApi.listNamespacedPod('default')
    .then((res) => {
	console.log(res.body);
    })
    .catch((err) => {
        console.log(err);
    });

has a call to kc.loadFromCluster() and loadFromCluster is not a method. What should we be using?

Exec with service account token - missing required Host header

When we use service account (e.g. login in cluster mode) and wanna run exec command, it will override websocket headers with Authorization: ...

        this.config.applytoHTTPSOptions(opts);
        const client = new ws.client({ tlsOptions: opts });

How it used:
https://github.com/theturtle32/WebSocket-Node/blob/7a30e3949a2e5b4f7ea701b7959cc8bd030f4c8f/lib/WebSocketClient.js#L236

       for (var key in self.config.tlsOptions) {
           if (self.config.tlsOptions.hasOwnProperty(key)) {
               requestOptions[key] = self.config.tlsOptions[key];
           }
       }

As a result, request options will be:

{ agent: false,
  hostname: '11.22.33.44',
  port: '6443',
  method: 'GET',
  path: '/api/v1/namespaces/monitoring/pods/xxx/exec?stdout=true&stderr=true&stdin=true&tty=true&command=sh&command=xxx&container=yyy',
  headers: 
   [ Authorization: 'Bearer aabbccddee...' ],
  ca: <Buffer ... >,
  cert: null,
  key: null }

And response will be:

Error: Server responded with a non-101 status: 400 Bad Request: missing required Host header

How to reproduce:

Run exec command from in-cluster or use service account in kube config

Update api core to support kubernetes 1.9

For eg : /apis/apps/v1beta1/deployments has moved into core now and the new url is /apis/apps/deployments

Cluster version info :


root@kubemaster:/home/test# kubectl version
Client Version: version.Info{Major:"1", Minor:"9", GitVersion:"v1.9.3", GitCommit:"d2835416544f298c919e2ead3be3d0864b52323b", GitTreeState:"clean", BuildDate:"2018-02-07T12:22:21Z", GoVersion:"go1.9.2", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"9", GitVersion:"v1.9.3", GitCommit:"d2835416544f298c919e2ead3be3d0864b52323b", GitTreeState:"clean", BuildDate:"2018-02-07T11:55:20Z", GoVersion:"go1.9.2", Compiler:"gc", Platform:"linux/amd64"}

Please update the apis

Exec example for copying files to pod

Managed to download file from pod by creating a writestream and using it as stdout

const downloadCommand = ["tar", "czpf", "-", `${remotePath}`];
const localFile = fs.createWriteStream(localPath);
Exec.exec(nameSpace, podName, containerName, downloadCommand, localFile, null, null, false);

But I wouldn't know how to upload a file/folder to the container.

Anyone can help me out?

How to install from git?

I'd like to use latest recent changes (Add a fromCluster option to KubeConfig.)

How to install this package from git?

TS interfaces for kube resources

I think this library could include kube resources definitions. I have one for my own, look something like this:

/**
 * https://kubernetes.io/docs/api-reference/v1.6/#deploymentspec-v1beta1-apps
 */
export interface DeploymentSpec {
  /**
   * Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready)
   */
  minReadySeconds?: number,
  /**
   * Number of desired pods. This is a pointer to distinguish between explicit zero and not specified. Defaults to 1.
   */
  replicas?: number,
  /**
   * The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 2.
   */
  revisionHistoryLimit?: number,
  /**
   * The config this deployment is rolling back to. Will be cleared after rollback is done.
   */
  rollbackTo?: RollbackConfig,
  /**
   * Label selector for pods. Existing ReplicaSets whose pods are selected by this will be the ones affected by this deployment.
   */
  selector?: LabelSelector,
  /**
   * The deployment strategy to use to replace existing pods with new ones.
   */
  strategy?: DeploymentStrategy
  /**
   * Template describes the pods that will be created.
   */
  template: PodTemplateSpec
}

export interface Deployment extends Resource {
  apiVersion: 'extensions/v1beta1'
  kind: 'Deployment',
  spec: DeploymentSpec
}

Though they are manually created, not generated as I assume can be.

I use those interfaces to created helm charts or kube configs (JS results are converted to yalm configs and applied to server). I find using Typescript for making configs much more convenient, flexible and safe than directly writing configs in native YAML format.

how to run the kubernetes client inside the pod?

i am trying to access the pod with the below command, do i have to add something more for access the pod

const k8s = require('@kubernetes/client-node');

var k8sApi = k8s.Config.defaultClient();
k8sApi.listNamespacedPod('default')
    .then((res) => {
        console.log(res.body);
    });

i am new to this, can u give me simple example

Publishes `.ts` files breaks build in all projects using `strict` option

Publishing .ts files will cause builds to fail on all projects that are using TypeScript's strict null checking, even in the with --skipLibCheck, --skipDefaultLibCheck, and the @kubernetes/client-node file placed in the excludes list.

Instead, you probably want to:

  • Apply the following diff to the package.json, so that the dist/index.js is properly targeted and the typings file dist/index.d.ts is included:
    @@ -10,7 +10,8 @@
         "*.ts",
         "*.js"
       ],
    -  "main": "index.js",
    +  "main": "dist/index.js",
    +  "types": "dist/index.d.ts",
       "scripts": {
         "clean": "rm -Rf node_modules/ dist/",
         "build": "tsc",
  • Increment the version to 0.1.4.
  • Run npm publish using npm client > 5. (4 will probably not work; I was able to publish a mirror here using 5.7.2.

npm registry package needs updating

There have been a handful of updates to the client since the last publish from 6c4fc27. Is it possible to publish a new version? I would be happy to tag and publish as well.

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.