2015-09-04 23:33:11 +00:00
|
|
|
/*
|
2016-06-03 00:25:58 +00:00
|
|
|
Copyright 2015 The Kubernetes Authors.
|
2015-09-04 23:33:11 +00:00
|
|
|
|
|
|
|
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 cmd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"os"
|
2016-04-18 09:49:43 +00:00
|
|
|
"path/filepath"
|
2016-05-13 17:08:44 +00:00
|
|
|
"reflect"
|
2015-12-21 05:37:49 +00:00
|
|
|
gruntime "runtime"
|
2015-09-04 23:33:11 +00:00
|
|
|
"strings"
|
|
|
|
|
2017-01-13 17:48:50 +00:00
|
|
|
"k8s.io/apimachinery/pkg/api/errors"
|
2017-01-11 14:09:48 +00:00
|
|
|
"k8s.io/apimachinery/pkg/api/meta"
|
|
|
|
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
|
|
|
"k8s.io/apimachinery/pkg/runtime"
|
|
|
|
"k8s.io/apimachinery/pkg/runtime/schema"
|
2017-01-16 20:13:59 +00:00
|
|
|
"k8s.io/apimachinery/pkg/types"
|
2017-02-03 19:49:37 +00:00
|
|
|
"k8s.io/apimachinery/pkg/util/mergepatch"
|
2017-01-24 14:35:22 +00:00
|
|
|
"k8s.io/apimachinery/pkg/util/strategicpatch"
|
2017-01-11 14:09:48 +00:00
|
|
|
"k8s.io/apimachinery/pkg/util/validation/field"
|
|
|
|
"k8s.io/apimachinery/pkg/util/yaml"
|
2015-09-04 23:33:11 +00:00
|
|
|
"k8s.io/kubernetes/pkg/api"
|
|
|
|
"k8s.io/kubernetes/pkg/kubectl"
|
2016-10-07 22:24:42 +00:00
|
|
|
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
|
2015-09-04 23:33:11 +00:00
|
|
|
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
|
|
|
|
"k8s.io/kubernetes/pkg/kubectl/cmd/util/editor"
|
|
|
|
"k8s.io/kubernetes/pkg/kubectl/resource"
|
2017-02-19 22:56:11 +00:00
|
|
|
"k8s.io/kubernetes/pkg/printers"
|
2016-03-09 12:44:24 +00:00
|
|
|
"k8s.io/kubernetes/pkg/util/crlf"
|
2017-01-25 01:00:32 +00:00
|
|
|
"k8s.io/kubernetes/pkg/util/i18n"
|
2015-09-04 23:33:11 +00:00
|
|
|
|
2017-02-13 00:31:06 +00:00
|
|
|
jsonpatch "github.com/evanphx/json-patch"
|
2015-09-04 23:33:11 +00:00
|
|
|
"github.com/golang/glog"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
)
|
|
|
|
|
2016-05-20 17:49:56 +00:00
|
|
|
var (
|
2016-10-07 22:24:42 +00:00
|
|
|
editLong = templates.LongDesc(`
|
2016-05-20 17:49:56 +00:00
|
|
|
Edit a resource from the default editor.
|
2015-09-04 23:33:11 +00:00
|
|
|
|
2016-05-20 17:49:56 +00:00
|
|
|
The edit command allows you to directly edit any API resource you can retrieve via the
|
|
|
|
command line tools. It will open the editor defined by your KUBE_EDITOR, or EDITOR
|
|
|
|
environment variables, or fall back to 'vi' for Linux or 'notepad' for Windows.
|
|
|
|
You can edit multiple objects, although changes are applied one at a time. The command
|
|
|
|
accepts filenames as well as command line arguments, although the files you point to must
|
|
|
|
be previously saved versions of resources.
|
2015-09-04 23:33:11 +00:00
|
|
|
|
2017-02-13 00:31:06 +00:00
|
|
|
Editing is done with the API version used to fetch the resource.
|
|
|
|
To edit using a specific API version, fully-qualify the resource, version, and group.
|
2017-02-19 22:56:11 +00:00
|
|
|
|
2017-02-13 00:31:06 +00:00
|
|
|
The default format is YAML. To edit in JSON, specify "-o json".
|
2017-02-19 22:56:11 +00:00
|
|
|
|
2017-02-13 00:31:06 +00:00
|
|
|
The flag --windows-line-endings can be used to force Windows line endings,
|
2016-05-20 17:49:56 +00:00
|
|
|
otherwise the default for your operating system will be used.
|
2015-09-04 23:33:11 +00:00
|
|
|
|
2016-05-20 17:49:56 +00:00
|
|
|
In the event an error occurs while updating, a temporary file will be created on disk
|
|
|
|
that contains your unapplied changes. The most common error when updating a resource
|
|
|
|
is another editor changing the resource on the server. When this occurs, you will have
|
|
|
|
to apply your changes to the newer version of the resource, or update your temporary
|
|
|
|
saved copy to include the latest resource version.`)
|
2015-09-04 23:33:11 +00:00
|
|
|
|
2016-10-07 22:24:42 +00:00
|
|
|
editExample = templates.Examples(`
|
|
|
|
# Edit the service named 'docker-registry':
|
|
|
|
kubectl edit svc/docker-registry
|
2015-09-04 23:33:11 +00:00
|
|
|
|
2016-10-07 22:24:42 +00:00
|
|
|
# Use an alternative editor
|
|
|
|
KUBE_EDITOR="nano" kubectl edit svc/docker-registry
|
2015-09-04 23:33:11 +00:00
|
|
|
|
2017-02-13 00:31:06 +00:00
|
|
|
# Edit the job 'myjob' in JSON using the v1 API format:
|
2017-02-27 17:47:26 +00:00
|
|
|
kubectl edit job.v1.batch/myjob -o json
|
|
|
|
|
|
|
|
# Edit the deployment 'mydeployment' in YAML and save the modified config in its annotation:
|
|
|
|
kubectl edit deployment/mydeployment -o yaml --save-config`)
|
2015-09-04 23:33:11 +00:00
|
|
|
)
|
|
|
|
|
2016-10-13 00:18:39 +00:00
|
|
|
func NewCmdEdit(f cmdutil.Factory, out, errOut io.Writer) *cobra.Command {
|
2016-08-17 18:28:07 +00:00
|
|
|
options := &resource.FilenameOptions{}
|
2016-03-28 19:44:21 +00:00
|
|
|
|
2016-04-03 06:48:24 +00:00
|
|
|
// retrieve a list of handled resources from printer as valid args
|
|
|
|
validArgs, argAliases := []string{}, []string{}
|
2017-02-19 22:56:11 +00:00
|
|
|
p, err := f.Printer(nil, printers.PrintOptions{
|
2016-06-23 14:49:31 +00:00
|
|
|
ColumnLabels: []string{},
|
|
|
|
})
|
2016-04-03 06:48:24 +00:00
|
|
|
cmdutil.CheckErr(err)
|
|
|
|
if p != nil {
|
|
|
|
validArgs = p.HandledResources()
|
|
|
|
argAliases = kubectl.ResourceAliases(validArgs)
|
|
|
|
}
|
|
|
|
|
2015-09-04 23:33:11 +00:00
|
|
|
cmd := &cobra.Command{
|
|
|
|
Use: "edit (RESOURCE/NAME | -f FILENAME)",
|
2017-01-25 01:00:32 +00:00
|
|
|
Short: i18n.T("Edit a resource on the server"),
|
2015-09-04 23:33:11 +00:00
|
|
|
Long: editLong,
|
|
|
|
Example: fmt.Sprintf(editExample),
|
|
|
|
Run: func(cmd *cobra.Command, args []string) {
|
2016-03-28 19:44:21 +00:00
|
|
|
err := RunEdit(f, out, errOut, cmd, args, options)
|
2015-09-04 23:33:11 +00:00
|
|
|
cmdutil.CheckErr(err)
|
|
|
|
},
|
2016-04-03 06:48:24 +00:00
|
|
|
ValidArgs: validArgs,
|
|
|
|
ArgAliases: argAliases,
|
2015-09-04 23:33:11 +00:00
|
|
|
}
|
2016-08-17 18:28:07 +00:00
|
|
|
usage := "to use to edit the resource"
|
|
|
|
cmdutil.AddFilenameOptionFlags(cmd, options, usage)
|
2016-06-15 11:35:56 +00:00
|
|
|
cmdutil.AddValidateFlags(cmd)
|
2015-09-04 23:33:11 +00:00
|
|
|
cmd.Flags().StringP("output", "o", "yaml", "Output format. One of: yaml|json.")
|
2017-02-13 00:31:06 +00:00
|
|
|
|
2015-12-21 05:37:49 +00:00
|
|
|
cmd.Flags().Bool("windows-line-endings", gruntime.GOOS == "windows", "Use Windows line-endings (default Unix line-endings)")
|
2015-11-04 21:47:08 +00:00
|
|
|
cmdutil.AddApplyAnnotationFlags(cmd)
|
2016-01-22 18:33:23 +00:00
|
|
|
cmdutil.AddRecordFlag(cmd)
|
2016-03-10 01:27:19 +00:00
|
|
|
cmdutil.AddInclude3rdPartyFlags(cmd)
|
2017-01-25 14:12:32 +00:00
|
|
|
return cmd
|
2015-09-04 23:33:11 +00:00
|
|
|
}
|
|
|
|
|
2016-10-13 00:18:39 +00:00
|
|
|
func RunEdit(f cmdutil.Factory, out, errOut io.Writer, cmd *cobra.Command, args []string, options *resource.FilenameOptions) error {
|
2016-09-21 23:41:07 +00:00
|
|
|
return runEdit(f, out, errOut, cmd, args, options, NormalEditMode)
|
|
|
|
}
|
|
|
|
|
2017-02-13 00:31:06 +00:00
|
|
|
// runEdit performs an interactive edit on the resources specified by filename or resource builder args.
|
|
|
|
// in NormalEditMode, all resources are edited as a single list.
|
|
|
|
// in CreateEditMode, resources are edited one-by-one.
|
|
|
|
// TODO: refactor runEdit and editFn into smaller simpler chunks
|
2016-09-21 23:41:07 +00:00
|
|
|
func runEdit(f cmdutil.Factory, out, errOut io.Writer, cmd *cobra.Command, args []string, options *resource.FilenameOptions, editMode EditMode) error {
|
2016-10-06 23:23:54 +00:00
|
|
|
o, err := getPrinter(cmd)
|
2015-09-04 23:33:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-02-12 20:06:17 +00:00
|
|
|
mapper, originalResult, updatedResultsGetter, cmdNamespace, err := getMapperAndResult(f, args, options, editMode)
|
2016-10-14 21:54:57 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2015-09-04 23:33:11 +00:00
|
|
|
|
2015-12-21 05:37:49 +00:00
|
|
|
encoder := f.JSONEncoder()
|
2015-10-20 22:22:54 +00:00
|
|
|
|
2016-02-02 12:30:12 +00:00
|
|
|
var (
|
|
|
|
windowsLineEndings = cmdutil.GetFlagBool(cmd, "windows-line-endings")
|
|
|
|
edit = editor.NewDefaultEditor(f.EditorEnvs())
|
|
|
|
)
|
|
|
|
|
2017-02-13 00:31:06 +00:00
|
|
|
// editFn is invoked for each edit session (once with a list for normal edit, once for each individual resource in a edit-on-create invocation)
|
2017-02-12 20:06:17 +00:00
|
|
|
editFn := func(infos []*resource.Info) error {
|
2016-11-14 22:12:24 +00:00
|
|
|
var (
|
|
|
|
results = editResults{}
|
|
|
|
original = []byte{}
|
|
|
|
edited = []byte{}
|
|
|
|
file string
|
|
|
|
)
|
|
|
|
|
|
|
|
containsError := false
|
2017-02-13 00:31:06 +00:00
|
|
|
|
|
|
|
// loop until we succeed or cancel editing
|
2016-11-14 22:12:24 +00:00
|
|
|
for {
|
2017-02-13 00:31:06 +00:00
|
|
|
// get the object we're going to serialize as input to the editor
|
|
|
|
var originalObj runtime.Object
|
|
|
|
switch len(infos) {
|
|
|
|
case 1:
|
|
|
|
originalObj = infos[0].Object
|
|
|
|
default:
|
|
|
|
l := &unstructured.UnstructuredList{
|
|
|
|
Object: map[string]interface{}{
|
|
|
|
"kind": "List",
|
|
|
|
"apiVersion": "v1",
|
|
|
|
"metadata": map[string]interface{}{},
|
|
|
|
},
|
|
|
|
}
|
|
|
|
for _, info := range infos {
|
|
|
|
l.Items = append(l.Items, info.Object.(*unstructured.Unstructured))
|
|
|
|
}
|
|
|
|
originalObj = l
|
2016-11-14 22:12:24 +00:00
|
|
|
}
|
2015-09-04 23:33:11 +00:00
|
|
|
|
2016-11-14 22:12:24 +00:00
|
|
|
// generate the file to edit
|
|
|
|
buf := &bytes.Buffer{}
|
|
|
|
var w io.Writer = buf
|
|
|
|
if windowsLineEndings {
|
|
|
|
w = crlf.NewCRLFWriter(w)
|
|
|
|
}
|
2015-09-04 23:33:11 +00:00
|
|
|
|
2016-11-14 22:12:24 +00:00
|
|
|
if o.addHeader {
|
|
|
|
results.header.writeTo(w)
|
|
|
|
}
|
2015-09-04 23:33:11 +00:00
|
|
|
|
2016-11-14 22:12:24 +00:00
|
|
|
if !containsError {
|
2017-02-13 00:31:06 +00:00
|
|
|
if err := o.printer.PrintObj(originalObj, w); err != nil {
|
2016-11-14 22:12:24 +00:00
|
|
|
return preservedFile(err, results.file, errOut)
|
|
|
|
}
|
|
|
|
original = buf.Bytes()
|
|
|
|
} else {
|
|
|
|
// In case of an error, preserve the edited file.
|
|
|
|
// Remove the comments (header) from it since we already
|
|
|
|
// have included the latest header in the buffer above.
|
|
|
|
buf.Write(manualStrip(edited))
|
|
|
|
}
|
2016-05-13 17:08:44 +00:00
|
|
|
|
2016-11-14 22:12:24 +00:00
|
|
|
// launch the editor
|
|
|
|
editedDiff := edited
|
|
|
|
edited, file, err = edit.LaunchTempFile(fmt.Sprintf("%s-edit-", filepath.Base(os.Args[0])), o.ext, buf)
|
|
|
|
if err != nil {
|
2016-05-18 07:29:55 +00:00
|
|
|
return preservedFile(err, results.file, errOut)
|
|
|
|
}
|
2017-02-12 20:06:17 +00:00
|
|
|
// If we're retrying the loop because of an error, and no change was made in the file, short-circuit
|
|
|
|
if containsError && bytes.Equal(stripComments(editedDiff), stripComments(edited)) {
|
|
|
|
return preservedFile(fmt.Errorf("%s", "Edit cancelled, no valid changes were saved."), file, errOut)
|
2016-11-14 22:12:24 +00:00
|
|
|
}
|
|
|
|
// cleanup any file from the previous pass
|
|
|
|
if len(results.file) > 0 {
|
|
|
|
os.Remove(results.file)
|
2016-05-18 07:29:55 +00:00
|
|
|
}
|
2016-11-14 22:12:24 +00:00
|
|
|
glog.V(4).Infof("User edited:\n%s", string(edited))
|
2016-09-21 23:41:07 +00:00
|
|
|
|
2016-11-14 22:12:24 +00:00
|
|
|
// Apply validation
|
|
|
|
schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"), cmdutil.GetFlagString(cmd, "schema-cache-dir"))
|
|
|
|
if err != nil {
|
|
|
|
return preservedFile(err, file, errOut)
|
|
|
|
}
|
|
|
|
err = schema.ValidateBytes(stripComments(edited))
|
|
|
|
if err != nil {
|
|
|
|
results = editResults{
|
|
|
|
file: file,
|
|
|
|
}
|
|
|
|
containsError = true
|
2017-02-03 18:51:36 +00:00
|
|
|
fmt.Fprintln(errOut, results.addError(errors.NewInvalid(api.Kind(""), "", field.ErrorList{field.Invalid(nil, "The edited file failed validation", fmt.Sprintf("%v", err))}), infos[0]))
|
2016-11-14 22:12:24 +00:00
|
|
|
continue
|
|
|
|
}
|
2016-05-18 07:29:55 +00:00
|
|
|
|
2016-11-14 22:12:24 +00:00
|
|
|
// Compare content without comments
|
|
|
|
if bytes.Equal(stripComments(original), stripComments(edited)) {
|
|
|
|
os.Remove(file)
|
|
|
|
fmt.Fprintln(errOut, "Edit cancelled, no changes made.")
|
|
|
|
return nil
|
2015-11-04 21:47:08 +00:00
|
|
|
}
|
2016-05-18 07:29:55 +00:00
|
|
|
|
2016-11-14 22:12:24 +00:00
|
|
|
lines, err := hasLines(bytes.NewBuffer(edited))
|
|
|
|
if err != nil {
|
|
|
|
return preservedFile(err, file, errOut)
|
|
|
|
}
|
|
|
|
if !lines {
|
|
|
|
os.Remove(file)
|
|
|
|
fmt.Fprintln(errOut, "Edit cancelled, saved file was empty.")
|
|
|
|
return nil
|
|
|
|
}
|
2016-05-18 07:29:55 +00:00
|
|
|
|
2016-11-14 22:12:24 +00:00
|
|
|
results = editResults{
|
|
|
|
file: file,
|
|
|
|
}
|
2016-05-18 07:29:55 +00:00
|
|
|
|
2016-11-14 22:12:24 +00:00
|
|
|
// parse the edited file
|
2017-02-13 00:31:06 +00:00
|
|
|
updatedInfos, err := updatedResultsGetter(edited).Infos()
|
|
|
|
if err != nil {
|
2016-11-14 22:12:24 +00:00
|
|
|
// syntax error
|
|
|
|
containsError = true
|
|
|
|
results.header.reasons = append(results.header.reasons, editReason{head: fmt.Sprintf("The edited file had a syntax error: %v", err)})
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
// not a syntax error as it turns out...
|
|
|
|
containsError = false
|
2017-02-13 00:31:06 +00:00
|
|
|
updatedVisitor := resource.InfoListVisitor(updatedInfos)
|
2015-09-10 21:32:57 +00:00
|
|
|
|
2016-11-14 22:12:24 +00:00
|
|
|
// need to make sure the original namespace wasn't changed while editing
|
2017-02-13 00:31:06 +00:00
|
|
|
if err := updatedVisitor.Visit(resource.RequireNamespace(cmdNamespace)); err != nil {
|
2016-11-14 22:12:24 +00:00
|
|
|
return preservedFile(err, file, errOut)
|
|
|
|
}
|
2015-09-04 23:33:11 +00:00
|
|
|
|
2016-11-14 22:12:24 +00:00
|
|
|
// iterate through all items to apply annotations
|
2017-02-13 00:31:06 +00:00
|
|
|
if err := visitAnnotation(cmd, f, updatedVisitor, encoder); err != nil {
|
2016-11-14 22:12:24 +00:00
|
|
|
return preservedFile(err, file, errOut)
|
|
|
|
}
|
2015-09-04 23:33:11 +00:00
|
|
|
|
2016-11-14 22:12:24 +00:00
|
|
|
switch editMode {
|
|
|
|
case NormalEditMode:
|
2017-02-13 00:31:06 +00:00
|
|
|
err = visitToPatch(infos, updatedVisitor, mapper, encoder, out, errOut, &results, file)
|
2016-11-14 22:12:24 +00:00
|
|
|
case EditBeforeCreateMode:
|
2017-02-13 00:31:06 +00:00
|
|
|
err = visitToCreate(updatedVisitor, mapper, out, errOut, &results, file)
|
2016-11-14 22:12:24 +00:00
|
|
|
default:
|
2017-02-13 00:31:06 +00:00
|
|
|
err = fmt.Errorf("Unsupported edit mode %q", editMode)
|
2016-11-14 22:12:24 +00:00
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return preservedFile(err, results.file, errOut)
|
|
|
|
}
|
2016-11-03 10:25:58 +00:00
|
|
|
|
2016-11-14 22:12:24 +00:00
|
|
|
// Handle all possible errors
|
|
|
|
//
|
|
|
|
// 1. retryable: propose kubectl replace -f
|
|
|
|
// 2. notfound: indicate the location of the saved configuration of the deleted resource
|
|
|
|
// 3. invalid: retry those on the spot by looping ie. reloading the editor
|
|
|
|
if results.retryable > 0 {
|
|
|
|
fmt.Fprintf(errOut, "You can run `%s replace -f %s` to try this update again.\n", filepath.Base(os.Args[0]), file)
|
|
|
|
return cmdutil.ErrExit
|
|
|
|
}
|
|
|
|
if results.notfound > 0 {
|
|
|
|
fmt.Fprintf(errOut, "The edits you made on deleted resources have been saved to %q\n", file)
|
|
|
|
return cmdutil.ErrExit
|
|
|
|
}
|
2016-05-13 17:08:44 +00:00
|
|
|
|
2016-11-14 22:12:24 +00:00
|
|
|
if len(results.edit) == 0 {
|
|
|
|
if results.notfound == 0 {
|
|
|
|
os.Remove(file)
|
|
|
|
} else {
|
|
|
|
fmt.Fprintf(out, "The edits you made on deleted resources have been saved to %q\n", file)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2016-11-03 10:25:58 +00:00
|
|
|
|
2016-11-14 22:12:24 +00:00
|
|
|
if len(results.header.reasons) > 0 {
|
|
|
|
containsError = true
|
2016-09-23 18:12:24 +00:00
|
|
|
}
|
2015-09-04 23:33:11 +00:00
|
|
|
}
|
2016-11-14 22:12:24 +00:00
|
|
|
}
|
2016-11-03 10:25:58 +00:00
|
|
|
|
2016-11-14 22:12:24 +00:00
|
|
|
switch editMode {
|
|
|
|
// If doing normal edit we cannot use Visit because we need to edit a list for convenience. Ref: #20519
|
|
|
|
case NormalEditMode:
|
2017-02-12 20:06:17 +00:00
|
|
|
infos, err := originalResult.Infos()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return editFn(infos)
|
2016-11-14 22:12:24 +00:00
|
|
|
// If doing an edit before created, we don't want a list and instead want the normal behavior as kubectl create.
|
|
|
|
case EditBeforeCreateMode:
|
2017-02-12 20:06:17 +00:00
|
|
|
return originalResult.Visit(func(info *resource.Info, err error) error {
|
|
|
|
return editFn([]*resource.Info{info})
|
|
|
|
})
|
2016-11-14 22:12:24 +00:00
|
|
|
default:
|
2017-02-13 00:31:06 +00:00
|
|
|
return fmt.Errorf("Unsupported edit mode %q", editMode)
|
2016-11-03 10:25:58 +00:00
|
|
|
}
|
2015-09-04 23:33:11 +00:00
|
|
|
}
|
|
|
|
|
2016-10-06 23:23:54 +00:00
|
|
|
func getPrinter(cmd *cobra.Command) (*editPrinterOptions, error) {
|
|
|
|
switch format := cmdutil.GetFlagString(cmd, "output"); format {
|
|
|
|
case "json":
|
|
|
|
return &editPrinterOptions{
|
2017-02-19 22:56:11 +00:00
|
|
|
printer: &printers.JSONPrinter{},
|
2016-10-06 23:23:54 +00:00
|
|
|
ext: ".json",
|
|
|
|
addHeader: false,
|
|
|
|
}, nil
|
2016-09-21 23:41:07 +00:00
|
|
|
// If flag -o is not specified, use yaml as default
|
|
|
|
case "yaml", "":
|
2016-10-06 23:23:54 +00:00
|
|
|
return &editPrinterOptions{
|
2017-02-19 22:56:11 +00:00
|
|
|
printer: &printers.YAMLPrinter{},
|
2016-10-06 23:23:54 +00:00
|
|
|
ext: ".yaml",
|
|
|
|
addHeader: true,
|
|
|
|
}, nil
|
|
|
|
default:
|
|
|
|
return nil, cmdutil.UsageError(cmd, "The flag 'output' must be one of yaml|json")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-02-12 20:06:17 +00:00
|
|
|
type resultGetter func([]byte) *resource.Result
|
|
|
|
|
2017-02-13 00:31:06 +00:00
|
|
|
// getMapperAndResult obtains the initial set of resources to edit, and returns:
|
|
|
|
// * mapper: restmapper used for printing objects
|
|
|
|
// * result: initial set of resources to edit. contains latest versions from the server when in normal editing mode
|
|
|
|
// * resultGetter: function that returns a set of resources parsed from user input. used to get resources from edited file.
|
|
|
|
// * cmdNamespace: namespace the edit was invoked with. used to verify namespaces don't change during editing.
|
|
|
|
// * error: any error that occurs fetching initial resources or building results.
|
2017-02-12 20:06:17 +00:00
|
|
|
func getMapperAndResult(f cmdutil.Factory, args []string, options *resource.FilenameOptions, editMode EditMode) (meta.RESTMapper, *resource.Result, resultGetter, string, error) {
|
2017-02-13 00:31:06 +00:00
|
|
|
if editMode != NormalEditMode && editMode != EditBeforeCreateMode {
|
|
|
|
return nil, nil, nil, "", fmt.Errorf("Unsupported edit mode %q", editMode)
|
|
|
|
}
|
|
|
|
|
2016-10-06 23:23:54 +00:00
|
|
|
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, nil, "", err
|
|
|
|
}
|
2017-02-13 00:31:06 +00:00
|
|
|
mapper, typer, err := f.UnstructuredObject()
|
2016-09-21 23:41:07 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, nil, "", err
|
|
|
|
}
|
2017-02-12 20:06:17 +00:00
|
|
|
|
2017-03-24 12:02:10 +00:00
|
|
|
b := resource.NewBuilder(mapper, f.CategoryExpander(), typer, resource.ClientMapperFunc(f.UnstructuredClientForMapping), unstructured.UnstructuredJSONScheme)
|
2017-02-13 00:31:06 +00:00
|
|
|
if editMode == NormalEditMode {
|
|
|
|
// if in normal mode, also read from args, and fetch latest from the server
|
|
|
|
b = b.ResourceTypeOrNameArgs(true, args...).Latest()
|
2016-09-21 23:41:07 +00:00
|
|
|
}
|
2017-02-12 20:06:17 +00:00
|
|
|
|
|
|
|
originalResult := b.NamespaceParam(cmdNamespace).DefaultNamespace().
|
2016-10-06 23:23:54 +00:00
|
|
|
FilenameParam(enforceNamespace, options).
|
|
|
|
ContinueOnError().
|
|
|
|
Flatten().
|
|
|
|
Do()
|
2017-02-12 20:06:17 +00:00
|
|
|
err = originalResult.Err()
|
2016-10-06 23:23:54 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, nil, "", err
|
|
|
|
}
|
2017-02-12 20:06:17 +00:00
|
|
|
|
|
|
|
updatedResultGetter := func(data []byte) *resource.Result {
|
2017-02-13 00:31:06 +00:00
|
|
|
// resource builder to read objects from edited data
|
2017-03-24 12:02:10 +00:00
|
|
|
return resource.NewBuilder(mapper, f.CategoryExpander(), typer, resource.ClientMapperFunc(f.UnstructuredClientForMapping), unstructured.UnstructuredJSONScheme).
|
2017-02-13 00:31:06 +00:00
|
|
|
Stream(bytes.NewReader(data), "edited-file").
|
|
|
|
ContinueOnError().
|
|
|
|
Flatten().
|
|
|
|
Do()
|
2017-02-12 20:06:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return mapper, originalResult, updatedResultGetter, cmdNamespace, err
|
2016-10-06 23:23:54 +00:00
|
|
|
}
|
|
|
|
|
2016-11-21 02:55:31 +00:00
|
|
|
func visitToPatch(
|
2017-02-13 00:31:06 +00:00
|
|
|
originalInfos []*resource.Info,
|
2017-02-12 20:06:17 +00:00
|
|
|
patchVisitor resource.Visitor,
|
2016-11-21 02:55:31 +00:00
|
|
|
mapper meta.RESTMapper,
|
|
|
|
encoder runtime.Encoder,
|
|
|
|
out, errOut io.Writer,
|
|
|
|
results *editResults,
|
|
|
|
file string,
|
|
|
|
) error {
|
2016-11-23 05:06:36 +00:00
|
|
|
err := patchVisitor.Visit(func(info *resource.Info, incomingErr error) error {
|
2017-02-13 00:31:06 +00:00
|
|
|
editObjUID, err := meta.NewAccessor().UID(info.Object)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-10-06 23:23:54 +00:00
|
|
|
|
2017-02-13 00:31:06 +00:00
|
|
|
var originalInfo *resource.Info
|
|
|
|
for _, i := range originalInfos {
|
|
|
|
originalObjUID, err := meta.NewAccessor().UID(i.Object)
|
2016-10-06 23:23:54 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2017-02-13 00:31:06 +00:00
|
|
|
if editObjUID == originalObjUID {
|
|
|
|
originalInfo = i
|
|
|
|
break
|
2016-10-06 23:23:54 +00:00
|
|
|
}
|
2017-02-13 00:31:06 +00:00
|
|
|
}
|
|
|
|
if originalInfo == nil {
|
|
|
|
return fmt.Errorf("no original object found for %#v", info.Object)
|
2016-10-06 23:23:54 +00:00
|
|
|
}
|
|
|
|
|
2017-02-13 00:31:06 +00:00
|
|
|
originalSerialization, err := runtime.Encode(encoder, originalInfo.Object)
|
2016-10-06 23:23:54 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
editedSerialization, err := runtime.Encode(encoder, info.Object)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// compute the patch on a per-item basis
|
|
|
|
// use strategic merge to create a patch
|
|
|
|
originalJS, err := yaml.ToJSON(originalSerialization)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
editedJS, err := yaml.ToJSON(editedSerialization)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if reflect.DeepEqual(originalJS, editedJS) {
|
|
|
|
// no edit, so just skip it.
|
|
|
|
cmdutil.PrintSuccess(mapper, false, out, info.Mapping.Resource, info.Name, false, "skipped")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-02-13 00:31:06 +00:00
|
|
|
preconditions := []mergepatch.PreconditionFunc{
|
|
|
|
mergepatch.RequireKeyUnchanged("apiVersion"),
|
|
|
|
mergepatch.RequireKeyUnchanged("kind"),
|
|
|
|
mergepatch.RequireMetadataKeyUnchanged("name"),
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create the versioned struct from the type defined in the mapping
|
|
|
|
// (which is the API version we'll be submitting the patch to)
|
|
|
|
versionedObject, err := api.Scheme.New(info.Mapping.GroupVersionKind)
|
|
|
|
var patchType types.PatchType
|
|
|
|
var patch []byte
|
|
|
|
switch {
|
|
|
|
case runtime.IsNotRegisteredError(err):
|
|
|
|
// fall back to generic JSON merge patch
|
|
|
|
patchType = types.MergePatchType
|
|
|
|
patch, err = jsonpatch.CreateMergePatch(originalJS, editedJS)
|
|
|
|
if err != nil {
|
|
|
|
glog.V(4).Infof("Unable to calculate diff, no merge is possible: %v", err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
for _, precondition := range preconditions {
|
|
|
|
if !precondition(patch) {
|
|
|
|
glog.V(4).Infof("Unable to calculate diff, no merge is possible: %v", err)
|
|
|
|
return fmt.Errorf("%s", "At least one of apiVersion, kind and name was changed")
|
|
|
|
}
|
2016-10-06 23:23:54 +00:00
|
|
|
}
|
2017-02-13 00:31:06 +00:00
|
|
|
case err != nil:
|
2016-10-06 23:23:54 +00:00
|
|
|
return err
|
2017-02-13 00:31:06 +00:00
|
|
|
default:
|
|
|
|
patchType = types.StrategicMergePatchType
|
|
|
|
patch, err = strategicpatch.CreateTwoWayMergePatch(originalJS, editedJS, versionedObject, preconditions...)
|
|
|
|
if err != nil {
|
|
|
|
glog.V(4).Infof("Unable to calculate diff, no merge is possible: %v", err)
|
|
|
|
if mergepatch.IsPreconditionFailed(err) {
|
|
|
|
return fmt.Errorf("%s", "At least one of apiVersion, kind and name was changed")
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
2016-10-06 23:23:54 +00:00
|
|
|
}
|
|
|
|
|
2017-02-13 00:31:06 +00:00
|
|
|
patched, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, patchType, patch)
|
2016-10-06 23:23:54 +00:00
|
|
|
if err != nil {
|
2017-02-03 18:51:36 +00:00
|
|
|
fmt.Fprintln(errOut, results.addError(err, info))
|
2016-11-23 05:02:30 +00:00
|
|
|
return nil
|
2016-10-06 23:23:54 +00:00
|
|
|
}
|
|
|
|
info.Refresh(patched, true)
|
|
|
|
cmdutil.PrintSuccess(mapper, false, out, info.Mapping.Resource, info.Name, false, "edited")
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-02-13 00:31:06 +00:00
|
|
|
func visitToCreate(createVisitor resource.Visitor, mapper meta.RESTMapper, out, errOut io.Writer, results *editResults, file string) error {
|
2016-09-21 23:41:07 +00:00
|
|
|
err := createVisitor.Visit(func(info *resource.Info, incomingErr error) error {
|
|
|
|
if err := createAndRefresh(info); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
cmdutil.PrintSuccess(mapper, false, out, info.Mapping.Resource, info.Name, false, "created")
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-02-13 00:31:06 +00:00
|
|
|
func visitAnnotation(cmd *cobra.Command, f cmdutil.Factory, annotationVisitor resource.Visitor, encoder runtime.Encoder) error {
|
2016-10-06 23:23:54 +00:00
|
|
|
// iterate through all items to apply annotations
|
|
|
|
err := annotationVisitor.Visit(func(info *resource.Info, incomingErr error) error {
|
2017-02-27 17:47:26 +00:00
|
|
|
// If the flag is true, create or update the annotation. Otherwise, NOP
|
|
|
|
if cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag) {
|
|
|
|
if err := kubectl.CreateOrUpdateAnnotation(true, info, encoder); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-10-06 23:23:54 +00:00
|
|
|
}
|
|
|
|
if cmdutil.ShouldRecord(cmd, info) {
|
2017-02-25 15:40:50 +00:00
|
|
|
if err := cmdutil.RecordChangeCause(info.Object, f.Command(cmd, false)); err != nil {
|
2016-10-06 23:23:54 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
2017-02-13 00:31:06 +00:00
|
|
|
return err
|
2016-10-06 23:23:54 +00:00
|
|
|
}
|
|
|
|
|
2016-09-21 23:41:07 +00:00
|
|
|
type EditMode string
|
|
|
|
|
|
|
|
const (
|
|
|
|
NormalEditMode EditMode = "normal_mode"
|
|
|
|
EditBeforeCreateMode EditMode = "edit_before_create_mode"
|
|
|
|
)
|
|
|
|
|
2015-09-04 23:33:11 +00:00
|
|
|
// editReason preserves a message about the reason this file must be edited again
|
|
|
|
type editReason struct {
|
|
|
|
head string
|
|
|
|
other []string
|
|
|
|
}
|
|
|
|
|
|
|
|
// editHeader includes a list of reasons the edit must be retried
|
|
|
|
type editHeader struct {
|
|
|
|
reasons []editReason
|
|
|
|
}
|
|
|
|
|
|
|
|
// writeTo outputs the current header information into a stream
|
|
|
|
func (h *editHeader) writeTo(w io.Writer) error {
|
|
|
|
fmt.Fprint(w, `# Please edit the object below. Lines beginning with a '#' will be ignored,
|
|
|
|
# and an empty file will abort the edit. If an error occurs while saving this file will be
|
|
|
|
# reopened with the relevant failures.
|
|
|
|
#
|
|
|
|
`)
|
|
|
|
for _, r := range h.reasons {
|
|
|
|
if len(r.other) > 0 {
|
|
|
|
fmt.Fprintf(w, "# %s:\n", r.head)
|
|
|
|
} else {
|
|
|
|
fmt.Fprintf(w, "# %s\n", r.head)
|
|
|
|
}
|
|
|
|
for _, o := range r.other {
|
|
|
|
fmt.Fprintf(w, "# * %s\n", o)
|
|
|
|
}
|
|
|
|
fmt.Fprintln(w, "#")
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-02-02 12:30:12 +00:00
|
|
|
func (h *editHeader) flush() {
|
|
|
|
h.reasons = []editReason{}
|
|
|
|
}
|
|
|
|
|
2016-10-06 23:23:54 +00:00
|
|
|
type editPrinterOptions struct {
|
2017-02-19 22:56:11 +00:00
|
|
|
printer printers.ResourcePrinter
|
2016-10-06 23:23:54 +00:00
|
|
|
ext string
|
|
|
|
addHeader bool
|
|
|
|
}
|
|
|
|
|
2015-09-04 23:33:11 +00:00
|
|
|
// editResults capture the result of an update
|
|
|
|
type editResults struct {
|
|
|
|
header editHeader
|
|
|
|
retryable int
|
|
|
|
notfound int
|
|
|
|
edit []*resource.Info
|
|
|
|
file string
|
|
|
|
|
2016-11-21 02:55:31 +00:00
|
|
|
version schema.GroupVersion
|
2015-09-04 23:33:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *editResults) addError(err error, info *resource.Info) string {
|
|
|
|
switch {
|
|
|
|
case errors.IsInvalid(err):
|
|
|
|
r.edit = append(r.edit, info)
|
|
|
|
reason := editReason{
|
2016-02-02 12:30:12 +00:00
|
|
|
head: fmt.Sprintf("%s %q was not valid", info.Mapping.Resource, info.Name),
|
2015-09-04 23:33:11 +00:00
|
|
|
}
|
2015-11-30 22:43:52 +00:00
|
|
|
if err, ok := err.(errors.APIStatus); ok {
|
2015-09-04 23:33:11 +00:00
|
|
|
if details := err.Status().Details; details != nil {
|
|
|
|
for _, cause := range details.Causes {
|
2016-02-02 12:30:12 +00:00
|
|
|
reason.other = append(reason.other, fmt.Sprintf("%s: %s", cause.Field, cause.Message))
|
2015-09-04 23:33:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
r.header.reasons = append(r.header.reasons, reason)
|
2016-03-07 12:20:27 +00:00
|
|
|
return fmt.Sprintf("error: %s %q is invalid", info.Mapping.Resource, info.Name)
|
2015-09-04 23:33:11 +00:00
|
|
|
case errors.IsNotFound(err):
|
|
|
|
r.notfound++
|
2016-03-07 12:20:27 +00:00
|
|
|
return fmt.Sprintf("error: %s %q could not be found on the server", info.Mapping.Resource, info.Name)
|
2015-09-04 23:33:11 +00:00
|
|
|
default:
|
|
|
|
r.retryable++
|
2016-03-07 12:20:27 +00:00
|
|
|
return fmt.Sprintf("error: %s %q could not be patched: %v", info.Mapping.Resource, info.Name, err)
|
2015-09-04 23:33:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// preservedFile writes out a message about the provided file if it exists to the
|
|
|
|
// provided output stream when an error happens. Used to notify the user where
|
|
|
|
// their updates were preserved.
|
|
|
|
func preservedFile(err error, path string, out io.Writer) error {
|
|
|
|
if len(path) > 0 {
|
|
|
|
if _, err := os.Stat(path); !os.IsNotExist(err) {
|
|
|
|
fmt.Fprintf(out, "A copy of your changes has been stored to %q\n", path)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// hasLines returns true if any line in the provided stream is non empty - has non-whitespace
|
|
|
|
// characters, or the first non-whitespace character is a '#' indicating a comment. Returns
|
|
|
|
// any errors encountered reading the stream.
|
|
|
|
func hasLines(r io.Reader) (bool, error) {
|
|
|
|
// TODO: if any files we read have > 64KB lines, we'll need to switch to bytes.ReadLine
|
|
|
|
// TODO: probably going to be secrets
|
|
|
|
s := bufio.NewScanner(r)
|
|
|
|
for s.Scan() {
|
|
|
|
if line := strings.TrimSpace(s.Text()); len(line) > 0 && line[0] != '#' {
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if err := s.Err(); err != nil && err != io.EOF {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
return false, nil
|
|
|
|
}
|
2015-10-20 22:22:54 +00:00
|
|
|
|
|
|
|
// stripComments will transform a YAML file into JSON, thus dropping any comments
|
|
|
|
// in it. Note that if the given file has a syntax error, the transformation will
|
|
|
|
// fail and we will manually drop all comments from the file.
|
|
|
|
func stripComments(file []byte) []byte {
|
2016-02-02 12:30:12 +00:00
|
|
|
stripped := file
|
|
|
|
stripped, err := yaml.ToJSON(stripped)
|
2015-10-20 22:22:54 +00:00
|
|
|
if err != nil {
|
|
|
|
stripped = manualStrip(file)
|
|
|
|
}
|
|
|
|
return stripped
|
|
|
|
}
|
|
|
|
|
|
|
|
// manualStrip is used for dropping comments from a YAML file
|
|
|
|
func manualStrip(file []byte) []byte {
|
|
|
|
stripped := []byte{}
|
2016-02-02 12:30:12 +00:00
|
|
|
lines := bytes.Split(file, []byte("\n"))
|
|
|
|
for i, line := range lines {
|
2015-10-20 22:22:54 +00:00
|
|
|
if bytes.HasPrefix(bytes.TrimSpace(line), []byte("#")) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
stripped = append(stripped, line...)
|
2016-02-02 12:30:12 +00:00
|
|
|
if i < len(lines)-1 {
|
|
|
|
stripped = append(stripped, '\n')
|
|
|
|
}
|
2015-10-20 22:22:54 +00:00
|
|
|
}
|
|
|
|
return stripped
|
|
|
|
}
|