Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions cmd/coreos-assembler.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (
var buildCommands = []string{"init", "fetch", "build", "run", "prune", "clean", "list"}
var advancedBuildCommands = []string{"buildfetch", "buildupload", "oc-adm-release", "push-container", "upload-oscontainer"}
var buildextendCommands = []string{"aliyun", "aws", "azure", "digitalocean", "exoscale", "gcp", "ibmcloud", "kubevirt", "live", "metal", "metal4k", "nutanix", "openstack", "qemu", "secex", "virtualbox", "vmware", "vultr"}
var utilityCommands = []string{"aws-replicate", "compress", "generate-hashlist", "koji-upload", "kola", "remote-build-container", "remote-prune", "sign", "tag"}
var utilityCommands = []string{"aws-replicate", "compress", "generate-hashlist", "koji-upload", "kola", "remote-build-container", "remote-prune", "remote-session", "sign", "tag"}
var otherCommands = []string{"shell", "meta"}

func init() {
Expand Down Expand Up @@ -63,17 +63,29 @@ func run(argv []string) error {
argv = argv[1:]
}

if cmd == "" {
if cmd == "" || cmd == "--help" {
printUsage()
os.Exit(1)
}

// if the COREOS_ASSEMBLER_REMOTE_SESSION environment variable is
// set then we "intercept" the command here and redirect it to
// `cosa remote-session exec`, which will execute the commands
// via `podman --remote` on a remote machine.
Comment on lines +71 to +74
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One thing I'm hazy on is how this works with the "context directory"; e.g. is the cosa init and the git clone expected to happen remotely? Or is it local, and then podman syncs it?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it should be able to work either way. You can cosa init locally and sync it over first or you can set up the remote session and cosa init on the remote.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds cool and magical; not a blocker for merge but would be nice add this new flow in the docs!

Or, another approach may be to land the fedora-coreos-pipeline changes, and then at least just link to that code. (I tend to learn a lot by reading about how APIs/CLIs are used in the real world and not just docs)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm working on the pipeline changes and I'll post them up shortly (testing them now). Trying to work out all the kinks first.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

session, ok := os.LookupEnv("COREOS_ASSEMBLER_REMOTE_SESSION")
if ok && session != "" && cmd != "remote-session" {
argv = append([]string{"exec", "--", cmd}, argv...)
cmd = "remote-session"
}

// Manual argument parsing here for now; once we get to "phase 1"
// of the Go conversion we can vendor cobra (and other libraries)
// at the toplevel.
switch cmd {
case "clean":
return runClean(argv)
case "remote-session":
return runRemoteSession(argv)
}

target := fmt.Sprintf("/usr/lib/coreos-assembler/cmd-%s", cmd)
Expand Down
260 changes: 260 additions & 0 deletions cmd/remote-session.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,260 @@
package main

import (
"fmt"
"github.com/spf13/cobra"
"io/ioutil"
"os"
"os/exec"
"strings"
)

type RemoteSessionOptions struct {
CreateImage string
CreateExpiration string
SyncQuiet bool
}

var (
remoteSessionOpts RemoteSessionOptions

cmdRemoteSession = &cobra.Command{
Use: "remote-session",
Short: "cosa remote-session [command]",
Long: "Initiate and use remote sessions for COSA execution.",
}

cmdRemoteSessionCreate = &cobra.Command{
Use: "create",
Short: "Create a remote session",
Long: "Create a remote session. This command will print an ID to " +
"STDOUT that should be set in COREOS_ASSEMBLER_REMOTE_SESSION " +
"environment variable for later commands to use.",
Args: cobra.ExactArgs(0),
PreRunE: preRunCheckEnv,
RunE: runCreate,
}

cmdRemoteSessionDestroy = &cobra.Command{
Use: "destroy",
Short: "Destroy a remote session",
Long: "Destroy a remote session. After running this command the " +
"COREOS_ASSEMBLER_REMOTE_SESSION should be unset.",
Args: cobra.ExactArgs(0),
PreRunE: preRunCheckEnv,
RunE: runDestroy,
}

cmdRemoteSessionExec = &cobra.Command{
Use: "exec",
Short: "Execute a cosa command in the remote session",
Long: "Execute a cosa command in the remote session.",
Args: cobra.MinimumNArgs(1),
PreRunE: preRunCheckEnv,
RunE: runExec,
}

cmdRemoteSessionPS = &cobra.Command{
Use: "ps",
Short: "Check if the remote session is running",
Long: "Check if the remote session is running.",
Args: cobra.ExactArgs(0),
PreRunE: preRunCheckEnv,
RunE: runPS,
}

cmdRemoteSessionSync = &cobra.Command{
Use: "sync",
Short: "sync files/directories to/from the remote",
Long: "sync files/directories to/from the remote. The symantics here " +
"are similar to rsync or scp. Provide `:from to` or `from :to`. " +
"The argument with the leading ':' will represent the remote.",
Args: cobra.MinimumNArgs(2),
PreRunE: preRunCheckEnv,
RunE: runSync,
}
)

// Function to determine if stdin is a terminal or not.
func isatty() bool {
cmd := exec.Command("tty")
cmd.Stdin = os.Stdin
cmd.Stdout = ioutil.Discard
cmd.Stderr = ioutil.Discard
err := cmd.Run()
return err == nil
}

// Function to check if a given environment variable exists
// and is non-empty.
func envVarIsSet(v string) bool {
val, ok := os.LookupEnv(v)
if !ok || val == "" {
return false
} else {
return true
}
}

// Function to return an error object with appropriate text for an
// environment variable error based on the given inputs.
func envVarError(v string, required bool) error {
if required {
return fmt.Errorf("The env var %s must be defined and non-empty", v)
} else {
return fmt.Errorf("The env var %s must not be defined", v)
}
}

// Function to check requisite environment variables. This is run
// before each subcommand to perform the checks.
func preRunCheckEnv(c *cobra.Command, args []string) error {
// We need to make sure that the CONTAINER_HOST env var
// is set for all commands. This is used for `podman --remote`.
// We could also check `CONTAINER_SSHKEY` key here but it's not
// strictly required (user could be using ssh-agent).
if !envVarIsSet("CONTAINER_HOST") {
return envVarError("CONTAINER_HOST", true)
}
// We need to check COREOS_ASSEMBLER_REMOTE_SESSION. For create
// we need to make sure it's not set. For all other commands we
// need to make sure it is set.
remoteSessionVarIsSet := envVarIsSet("COREOS_ASSEMBLER_REMOTE_SESSION")
if c.Use == "create" && remoteSessionVarIsSet {
return envVarError("COREOS_ASSEMBLER_REMOTE_SESSION", false)
} else if c.Use != "create" && !remoteSessionVarIsSet {
return envVarError("COREOS_ASSEMBLER_REMOTE_SESSION", true)
}
return nil
}

// Creates a "remote session" on the remote. This just creates a
// container on the remote and prints to STDOUT the container ID.
// The user is then expected to store this ID in the
// COREOS_ASSEMBLER_REMOTE_SESSION environment variable.
func runCreate(c *cobra.Command, args []string) error {
podmanargs := []string{"--remote", "run", "--rm", "-d", "--privileged",
"--security-opt=label=disable", "--volume=/srv/",
"--uidmap=1000:0:1", "--uidmap=0:1:1000", "--uidmap=1001:1001:64536",
"--device=/dev/kvm", "--device=/dev/fuse", "--tmpfs=/tmp",
"--entrypoint=/usr/bin/dumb-init", remoteSessionOpts.CreateImage,
"sleep", remoteSessionOpts.CreateExpiration}
cmd := exec.Command("podman", podmanargs...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}

// Destroys the "remote session". In reality it just deletes
// the container referenced by $COREOS_ASSEMBLER_REMOTE_SESSION.
func runDestroy(c *cobra.Command, args []string) error {
session := os.Getenv("COREOS_ASSEMBLER_REMOTE_SESSION")
podmanargs := []string{"--remote", "rm", "-f", session}
cmd := exec.Command("podman", podmanargs...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}

// Executes a command in the "remote session". Mostly just a
// `podman --remote exec`.
func runExec(c *cobra.Command, args []string) error {
podmanargs := []string{"--remote", "exec", "-i"}
if isatty() {
podmanargs = append(podmanargs, "-t")
}
session := os.Getenv("COREOS_ASSEMBLER_REMOTE_SESSION")
podmanargs = append(podmanargs, session, "cosa")
podmanargs = append(podmanargs, args...)
cmd := exec.Command("podman", podmanargs...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
if exitError, ok := err.(*exec.ExitError); ok {
// If the command failed let's exit with the same exitcode
// as the remotely executed process.
os.Exit(exitError.ExitCode())
} else {
return err
}
}
return nil
}

// Executes a `podman --remote ps -a --filter id=<container>`
// to show the status of the remote running cosa container.
func runPS(c *cobra.Command, args []string) error {
session := os.Getenv("COREOS_ASSEMBLER_REMOTE_SESSION")
podmanargs := []string{"--remote", "ps", "-a",
fmt.Sprintf("--filter=id=%s", session)}
cmd := exec.Command("podman", podmanargs...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}

// runSync provides an rsync-like interface that allows
// files to be copied to/from the remote. It uses
// `podman --remote exec` as the transport for rsync (see [1])
//
// One of the arguments here must be prepended with a `:`. This
// argument will represent the path on the remote. This function
// will substitute `:` with `$COREOS_ASSEMBLER_REMOTE_SESSION:`.
// That environment var just contains the container ID on the remote.
//
// [1] https://github.com/moby/moby/issues/13660
func runSync(c *cobra.Command, args []string) error {
// check arguments. Need one with pre-pended ':'
found := 0
for index, arg := range args {
if strings.HasPrefix(arg, ":") {
args[index] = fmt.Sprintf("%s%s",
os.Getenv("COREOS_ASSEMBLER_REMOTE_SESSION"), arg)
found++
}
}
if found != 1 {
return fmt.Errorf("Must pass in a single arg with `:` prepended")
}
// build command and execute
rsyncargs := []string{"-ah", "--mkpath", "--blocking-io",
"--compress", "--rsh", "podman --remote exec -i"}
if !remoteSessionOpts.SyncQuiet {
rsyncargs = append(rsyncargs, "-v")
}
rsyncargs = append(rsyncargs, args...)
cmd := exec.Command("rsync", rsyncargs...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}

func init() {
cmdRemoteSession.AddCommand(cmdRemoteSessionCreate)
cmdRemoteSession.AddCommand(cmdRemoteSessionDestroy)
cmdRemoteSession.AddCommand(cmdRemoteSessionExec)
cmdRemoteSession.AddCommand(cmdRemoteSessionPS)
cmdRemoteSession.AddCommand(cmdRemoteSessionSync)

// cmdRemoteSessionCreate options
cmdRemoteSessionCreate.Flags().StringVarP(
&remoteSessionOpts.CreateImage, "image", "",
"quay.io/coreos-assembler/coreos-assembler:latest",
"The COSA container image to use on the remote")
cmdRemoteSessionCreate.Flags().StringVarP(
&remoteSessionOpts.CreateExpiration, "expiration", "", "infinity",
"The amount of time before the remote-session auto-exits")

// cmdRemoteSessionSync options
cmdRemoteSessionSync.Flags().BoolVarP(
&remoteSessionOpts.SyncQuiet, "quiet", "", false,
"Make the sync output less verbose")
}

// execute the cmdRemoteSession cobra command
func runRemoteSession(argv []string) error {
cmdRemoteSession.SetArgs(argv)
return cmdRemoteSession.Execute()
}
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
module github.com/coreos/coreos-assembler

go 1.15

require github.com/spf13/cobra v1.5.0
10 changes: 10 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.5.0 h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU=
github.com/spf13/cobra v1.5.0/go.mod h1:dWXEIy2H428czQCjInthrTRUg7yKbok+2Qi/yBIJoUM=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading