node.jsexecchild-processlxclxd

Problem with node.js child_process exec for lxc/lxd launch/delete commands


I am using node.js to execute lxc/lxd commands on the server. Many commands for getting information about containers work as expected. For example:

app.get('/checkVirtual', (req, res) => {
    exec('lxc list -c "n" --format="csv"', (error, stdout, stderr) => {
        if (error) {
            //console.log(`error: ${error.message}`);
            return;
        }
        if (stderr) {
            //console.log(`stderr: ${stderr}`);
            return;
        }
        //console.log(`stdout: ${stdout}`);
        res.send(stdout)
    });
})

Postman demonstration

Problems appear when doing lxc/lxd launch/delete commands. An example of executing a command in bash:

enter image description here

Code to execute command in node.js:

app.get('/createMachine', (req, res) => {
    exec('lxc launch ubuntu: virtual4', (error, stdout, stderr) => {
        if (error) {
            console.log(`error: ${error.message}`);
            return;
        }
        if (stderr) {
            console.log(`stderr: ${stderr}`);
            return;
        }
        console.log(`stdout: ${stdout}`);
        res.send(stdout)
    });
})

When executing a request, there will first be a long wait (which is usually longer than the execution of the command), after which the response will come:

enter image description here

An interesting detail: if you try to create a new container with a name that is already taken, the result will not change: Waiting -> 504. Although there should be an error output.

enter image description here


Solution

  • I solved this problem by creating a run.sh file:

    #!/bin/bash
    echo "starting"
    lxc launch testimage test &
    wait
    

    chmod +x run.sh

    and exec('run.sh')