Open exec websocket in node.js

Hi! im trying to connect to a exec websocket for a container with node.js, however iam having some issues.

  • LXD Version: 5.1
    (also tried on 5.0)
    The code that iam using is:
const https = require('https');
const fs = require('fs');
const WebSocket = require('ws');

const options = {
    method: 'POST',
    host: 'localhost',
    port: 8443,
    path: '/1.0/instances/settled-hamster/exec',
    cert: fs.readFileSync('./lxd-webui.crt'),
    key: fs.readFileSync('./lxd-webui.key'),
    rejectUnauthorized: false
}

const body = JSON.stringify({
  "command":["/bin/bash"],
  "environment":{"MY_KEY":"my_value"},
  "interactive":true,
  "wait-for-websocket":true
})

const req = https.request(options, res => {
  res.on('data', d => {
    const output = JSON.parse(d);
    
    const wsoptions = {
      cert: options.cert,
      key: options.key,
      rejectUnauthorized: false 
    }

    const ws = new WebSocket('wss://' +
      options.host + ':' + options.port + output.operation +
      '/websocket?secret=' + output.metadata.metadata.fds['0'],
      wsoptions
    );
        
    ws.on('open', () => {
      console.log('connection opened');
      ws.send('printenv \r', { binary: true }, () => {
        setTimeout(() => ws.send('exit \r', { binary: true }), 100);
        setTimeout(() => process.exit(0), 200);
      });
    });

    ws.on('error', error => console.log(error));

    ws.on('message', data => {
      const buf = Buffer.from(data);
      console.log(buf.toString());
    });
  });
});
req.write(body);
req.end();

req.on('error', (e) => {
  console.error(e);
});

if i run this js files i get:

robert@DESKTOP-LEOJGHG:~/panel$ sudo node console.js 
connection opened

And process exits

Iam able to however access exec from the cli:

robert@DESKTOP-LEOJGHG:~/panel$ sudo lxc exec settled-hamster bash
root@settled-hamster:~# 

Solved this issue on my own, the problem was that i had to connect to the control websocket too (didnt need to do that some time ago). I think its because of a change in lxd.

Yes this was enforced in recent versions so we can more reliable detect when a client disconnects.

This came up recently in this thread: