forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
patch.go
182 lines (151 loc) · 5.18 KB
/
patch.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
package config
import (
"errors"
"fmt"
"io"
"strings"
"github.com/evanphx/json-patch"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/strategicpatch"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/resource"
kprinters "k8s.io/kubernetes/pkg/printers"
configapi "github.com/openshift/origin/pkg/cmd/server/api"
configapiinstall "github.com/openshift/origin/pkg/cmd/server/api/install"
"github.com/openshift/origin/pkg/cmd/util/clientcmd"
)
const PatchRecommendedName = "patch"
var patchTypes = map[string]types.PatchType{"json": types.JSONPatchType, "merge": types.MergePatchType, "strategic": types.StrategicMergePatchType}
// PatchOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of
// referencing the cmd.Flags()
type PatchOptions struct {
Filename string
Patch string
PatchType types.PatchType
Builder *resource.Builder
Printer kprinters.ResourcePrinter
Out io.Writer
}
var (
patch_long = templates.LongDesc(`Patch the master-config.yaml or node-config.yaml`)
patch_example = templates.Examples(`
# Set the auditConfig.enabled value to true
%[1]s openshift.local.config/master/master-config.yaml --patch='{"auditConfig": {"enabled": true}}'`)
)
func NewCmdPatch(name, fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
o := &PatchOptions{Out: out}
cmd := &cobra.Command{
Use: name + " FILENAME -p PATCH",
Short: "Update field(s) of a resource using a patch.",
Long: patch_long,
Example: patch_example,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(o.Complete(f, cmd, args))
cmdutil.CheckErr(o.Validate())
cmdutil.CheckErr(o.RunPatch())
},
}
cmd.Flags().StringVarP(&o.Patch, "patch", "p", "", "The patch to be applied to the resource JSON file.")
cmd.MarkFlagRequired("patch")
cmd.Flags().String("type", "strategic", fmt.Sprintf("The type of patch being provided; one of %v", sets.StringKeySet(patchTypes).List()))
return cmd
}
func (o *PatchOptions) Complete(f *clientcmd.Factory, cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("exactly one FILENAME is allowed: %v", args)
}
o.Filename = args[0]
patchTypeString := strings.ToLower(cmdutil.GetFlagString(cmd, "type"))
ok := false
o.PatchType, ok = patchTypes[patchTypeString]
if !ok {
return cmdutil.UsageError(cmd, fmt.Sprintf("--type must be one of %v, not %q", sets.StringKeySet(patchTypes).List(), patchTypeString))
}
o.Builder = resource.NewBuilder(configapiinstall.NewRESTMapper(), f.CategoryExpander(), configapi.Scheme, resource.DisabledClientForMapping{}, configapi.Codecs.LegacyCodec())
var err error
mapper, typer := f.Object()
decoders := []runtime.Decoder{f.Decoder(true), unstructured.UnstructuredJSONScheme}
o.Printer, err = kprinters.GetStandardPrinter(
&kprinters.OutputOptions{
FmtType: "yaml",
AllowMissingKeys: false,
},
false, mapper, typer, nil, decoders, kprinters.PrintOptions{})
if err != nil {
return err
}
return nil
}
func (o *PatchOptions) Validate() error {
if len(o.Patch) == 0 {
return errors.New("must specify -p to patch")
}
if len(o.Filename) == 0 {
return errors.New("filename is required")
}
return nil
}
func (o *PatchOptions) RunPatch() error {
patchBytes, err := yaml.ToJSON([]byte(o.Patch))
if err != nil {
return fmt.Errorf("unable to parse %q: %v", o.Patch, err)
}
r := o.Builder.
FilenameParam(false, &resource.FilenameOptions{Recursive: false, Filenames: []string{o.Filename}}).
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
infos, err := r.Infos()
if err != nil {
return err
}
if len(infos) > 1 {
return fmt.Errorf("multiple resources provided")
}
info := infos[0]
originalObjJS, err := runtime.Encode(configapi.Codecs.LegacyCodec(info.Mapping.GroupVersionKind.GroupVersion()), info.VersionedObject.(runtime.Object))
if err != nil {
return err
}
patchedObj, err := configapi.Scheme.DeepCopy(info.VersionedObject)
if err != nil {
return err
}
originalPatchedObjJS, err := getPatchedJS(o.PatchType, originalObjJS, patchBytes, patchedObj.(runtime.Object))
if err != nil {
return err
}
rawExtension := &runtime.Unknown{
Raw: originalPatchedObjJS,
}
if err := o.Printer.PrintObj(rawExtension, o.Out); err != nil {
return err
}
return nil
}
func getPatchedJS(patchType types.PatchType, originalJS, patchJS []byte, obj runtime.Object) ([]byte, error) {
switch patchType {
case types.JSONPatchType:
patchObj, err := jsonpatch.DecodePatch(patchJS)
if err != nil {
return nil, err
}
return patchObj.Apply(originalJS)
case types.MergePatchType:
return jsonpatch.MergePatch(originalJS, patchJS)
case types.StrategicMergePatchType:
return strategicpatch.StrategicMergePatch(originalJS, patchJS, obj)
default:
// only here as a safety net - go-restful filters content-type
return nil, fmt.Errorf("unknown Content-Type header for patch: %v", patchType)
}
}