Skip to content

Instantly share code, notes, and snippets.

@mrtc0
Last active June 22, 2017 15:31
Show Gist options
  • Save mrtc0/69eddfdeeaf85fea3775b1e35ebe53ee to your computer and use it in GitHub Desktop.
Save mrtc0/69eddfdeeaf85fea3775b1e35ebe53ee to your computer and use it in GitHub Desktop.
package main
import (
"github.com/lxc/lxd/client"
"github.com/lxc/lxd/shared/api"
"os"
"syscall"
"fmt"
"io/ioutil"
"github.com/lxc/lxd/shared/termios"
)
func main() {
stdout := captureStdout(e)
fmt.Printf("%s", stdout)
}
func captureStdout(f func() error) []byte {
oldStdout := os.Stdout
oldStderr := os.Stderr
r, w, _ := os.Pipe()
os.Stdout = w
os.Stderr = w
f()
w.Close()
out, _ := ioutil.ReadAll(r)
os.Stdout = oldStdout
os.Stderr = oldStderr
return out
}
func e() error{
c, err := lxd.ConnectLXDUnix("", nil)
if err != nil {
return err
}
// Setup the exec request
req := api.ContainerExecPost{
Command: []string{"bash", "-c", "sleep 10; id; wei"},
WaitForWS: true,
Interactive: false,
Width: 80,
Height: 15,
}
// Setup the exec arguments (fds)
args := lxd.ContainerExecArgs{
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
}
// Setup the terminal (set to raw mode)
if req.Interactive {
cfd := int(syscall.Stdin)
oldttystate, err := termios.MakeRaw(cfd)
if err != nil {
return err
}
defer termios.Restore(cfd, oldttystate)
}
// Get the current state
op, err := c.ExecContainer("container1", req, &args)
if err != nil {
return err
}
// Wait for it to complete
err = op.Wait()
if err != nil {
return err
}
return nil
}
package main
import (
"github.com/lxc/lxd"
"os"
"fmt"
"io/ioutil"
)
func main() {
stdout := captureStdout(e)
fmt.Printf("%s", stdout)
}
func captureStdout(f func() error) []byte {
oldStdout := os.Stdout
oldStderr := os.Stderr
r, w, _ := os.Pipe()
os.Stdout = w
os.Stderr = w
f()
w.Close()
out, _ := ioutil.ReadAll(r)
os.Stdout = oldStdout
os.Stderr = oldStderr
return out
}
func e() error{
c, err := lxd.NewClient(&lxd.DefaultConfig, "local")
if err != nil {
return err
}
_, err = c.Exec("container1", []string{"bash", "-c", "sleep 5; id; wei"}, map[string]string{}, os.Stdin, os.Stdout, os.Stderr, nil, 1, 1)
if err != nil {
return err
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment