1
0
mirror of https://github.com/ko-build/ko.git synced 2024-12-12 08:54:09 +02:00
ko-build/pkg/commands/run.go
jonjohnsonjr 3c6a907da9
Add additional output formats (tarball and layout) (#134)
* Create a MultiPublisher

MultiPublisher mimics io.MultiWriter in that it will publish an image to
multiple publish.Interface implementations.

* Add publish.{Tarball,Layout}Publisher

This adds support for publishing in the tarball format and to an OCI
image layout.

The tarball format isn't great, yet. It only supports writing once
instead of appending.

* Consolidate options

These were spread all over the place for no reasons. Now all the
publisher related options are grouped together.

* Add options for tarball/layout

Adds --oci-layout-path, --tarball, and --push flags.

--push=false will disable the default behavior of publishing to a
registry.

* go mod vendor

* Add Close method to publish.Interface

This allows us to defer writing to the tarball until we've collected all
the images that have been published.

* Fix tests
2020-02-19 09:30:01 -08:00

153 lines
4.5 KiB
Go

// Copyright 2018 Google LLC All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package commands
import (
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/google/ko/pkg/commands/options"
"github.com/spf13/cobra"
)
// addRun augments our CLI surface with run.
func addRun(topLevel *cobra.Command) {
po := &options.PublishOptions{}
bo := &options.BuildOptions{}
run := &cobra.Command{
Use: "run IMPORTPATH",
Short: "A variant of `kubectl run` that containerizes IMPORTPATH first.",
Long: `This sub-command combines "ko publish" and "kubectl run" to support containerizing and running Go binaries on Kubernetes in a single command.`,
Example: `
# Publish the image and run it on Kubernetes as:
# ${KO_DOCKER_REPO}/<package name>-<hash of import path>
# When KO_DOCKER_REPO is ko.local, it is the same as if
# --local and --preserve-import-paths were passed.
ko run github.com/foo/bar/cmd/baz
# This supports relative import paths as well.
ko run ./cmd/baz
# You can also supply args and flags to the command.
ko run ./cmd/baz -- -v arg1 arg2 --yes`,
Run: func(cmd *cobra.Command, args []string) {
// Args after -- are for kubectl, so only consider importPaths before it.
importPaths := args
dashes := cmd.Flags().ArgsLenAtDash()
if dashes != -1 {
importPaths = args[:cmd.Flags().ArgsLenAtDash()]
}
if len(importPaths) == 0 {
log.Fatalf("ko run: no importpaths listed")
}
kubectlArgs := []string{}
dashes = unparsedDashes()
if dashes != -1 {
kubectlArgs = os.Args[dashes:]
}
builder, err := makeBuilder(bo)
if err != nil {
log.Fatalf("error creating builder: %v", err)
}
publisher, err := makePublisher(po)
if err != nil {
log.Fatalf("error creating publisher: %v", err)
}
defer publisher.Close()
if len(os.Args) < 3 {
log.Fatalf("usage: %s run <package>", os.Args[0])
}
ip := os.Args[2]
if strings.HasPrefix(ip, "-") {
log.Fatalf("expected first arg to be positional, got %q", ip)
}
ctx := createCancellableContext()
imgs, err := publishImages(ctx, importPaths, publisher, builder)
if err != nil {
log.Fatalf("failed to publish images: %v", err)
}
// Usually only one, but this is the simple way to access the
// reference since the import path may have been qualified.
for k, ref := range imgs {
log.Printf("Running %q", k)
pod := filepath.Base(ref.Context().String())
// These are better defaults:
defaults := []string{
"--generator=run-pod/v1", // create a pod instead of deployment
"--attach", // stream logs back
"--rm", // clean up after ourselves
"--restart=Never", // we just want to run once
"--log-flush-frequency=1s", // flush logs more often
}
// Replaced "<package>" with "--image=<published image>".
argv := []string{"--image", ref.String()}
// Add our default kubectl flags.
// TODO: Add some way to override these.
argv = append(argv, defaults...)
// If present, adds -- arg1 arg2...
argv = append(argv, kubectlArgs...)
// "run <package> <defaults> --image <ref> <kubectlArgs>"
argv = append([]string{"run", pod}, argv...)
log.Printf("$ kubectl %s", strings.Join(argv, " "))
kubectlCmd := exec.Command("kubectl", argv...)
// Pass through our environment
kubectlCmd.Env = os.Environ()
// Pass through our std*
kubectlCmd.Stderr = os.Stderr
kubectlCmd.Stdout = os.Stdout
kubectlCmd.Stdin = os.Stdin
// Run it.
if err := kubectlCmd.Run(); err != nil {
log.Fatalf("error executing \"kubectl run\": %v", err)
}
}
},
// We ignore unknown flags to avoid importing everything Go exposes
// from our commands.
FParseErrWhitelist: cobra.FParseErrWhitelist{
UnknownFlags: true,
},
}
options.AddPublishArg(run, po)
options.AddBuildOptions(run, bo)
topLevel.AddCommand(run)
}
func unparsedDashes() int {
for i, s := range os.Args {
if s == "--" {
return i
}
}
return -1
}