Skip to content

Instantly share code, notes, and snippets.

@vincent99
Last active August 14, 2019 01:16
Show Gist options
  • Save vincent99/491afed2306ba448dd89 to your computer and use it in GitHub Desktop.
Save vincent99/491afed2306ba448dd89 to your computer and use it in GitHub Desktop.
Simple example of subscribing to Rancher change events
/*
Setup:
npm install ws
Usage:
Create an API key in Rancher and start up with:
node socket.js address.of.rancher:8080 access_key secret_key project_id
*/
var WebSocket = require('ws');
var host = process.argv[2];
var accessKey = process.argv[3];
var secretKey = process.argv[4];
var projectId = process.argv[5];
var url = 'ws://'+accessKey+':'+secretKey+'@'+host+'/v1/projects/'+projectId+'/subscribe?eventNames=resource.change';
var socket = new WebSocket(url);
socket.on('open', function() {
console.log('Socket opened');
});
socket.on('message', function(messageStr) {
var message = JSON.parse(messageStr);
if ( message.name === 'ping' )
{
console.log('ping');
}
else if ( message.name === 'resource.change' && message.data )
{
var resource = message.data.resource;
var info = 'name='+resource.name + ', state='+resource.state;
if ( resource.transitioning !== 'no' )
{
info += ', transitioning='+resource.transitioning + ', message='+resource.transitioningMessage
}
console.log(message.resourceType, message.resourceId, 'changed:', info);
}
});
socket.on('close', function() {
console.log('Socket closed');
});
@alfrye
Copy link

alfrye commented Dec 6, 2018

I am using rancher 2.11 and after I get a few pings back from rancher the websocket closes with error code 1006. Any ideas?

I accessing the websocket from a node.js server

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment