This repository has been archived by the owner on Mar 14, 2022. It is now read-only.
forked from istio/istio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd.go
269 lines (236 loc) · 7.46 KB
/
cmd.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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
// Copyright 2017 Istio Authors.
//
// 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 convert
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"github.com/ghodss/yaml"
multierror "github.com/hashicorp/go-multierror"
"github.com/spf13/cobra"
"k8s.io/api/extensions/v1beta1"
"istio.io/istio/istioctl/pkg/convert"
"istio.io/istio/pilot/pkg/config/kube/crd"
"istio.io/istio/pilot/pkg/model"
"istio.io/istio/pkg/log"
)
var (
inFilenames []string
outFilename string
)
// Command for converting v1alpha1 configs to v1alpha3
func Command() *cobra.Command {
cmd := &cobra.Command{
Use: "convert-networking-config",
Short: "Convert networking configs from v1alpha1 to v1alpha3",
Long: "Converts sets of v1alpha1 configs to v1alpha3 equivalents on a best effort basis. " +
"The output should be considered a starting point for your v1alpha3 configs and probably " +
"require some minor modification. " +
"Warnings will (hopefully) be generated where configs cannot be converted perfectly, " +
"or in certain edge cases. " +
"The input must be the set of configs that would be in place in an environment at a given " +
"time. " +
"This allows the command to attempt to create and merge output configs intelligently." +
"Output configs are given the namespace and domain of the first input config " +
"so it is recommended that input configs be part of the same namespace and domain.",
Example: "istioctl experimental convert-networking-config -f v1alpha1/default-route.yaml -f v1alpha1/header-delay.yaml",
RunE: func(c *cobra.Command, args []string) error {
if len(inFilenames) == 0 {
return fmt.Errorf("no input files provided")
}
readers := make([]io.Reader, 0)
if len(inFilenames) == 1 && inFilenames[0] == "-" {
readers = append(readers, os.Stdin)
} else {
for _, filename := range inFilenames {
file, err := os.Open(filename)
if err != nil {
return err
}
defer func() {
if err := file.Close(); err != nil {
log.Errorf("Did not close input %s successfully: %v",
filename, err)
}
}()
readers = append(readers, file)
}
}
writer := os.Stdout
if outFilename != "-" {
file, err := os.Create(outFilename)
if err != nil {
return err
}
defer func() {
if err := file.Close(); err != nil {
log.Errorf("Did not close output successfully: %v", err)
}
}()
writer = file
}
return convertConfigs(readers, writer)
},
}
cmd.PersistentFlags().StringSliceVarP(&inFilenames, "filenames", "f",
nil, "Input filenames")
cmd.PersistentFlags().StringVarP(&outFilename, "output", "o",
"-", "Output filename")
return cmd
}
func convertConfigs(readers []io.Reader, writer io.Writer) error {
configDescriptor := model.ConfigDescriptor{
model.RouteRule,
model.VirtualService,
model.Gateway,
model.EgressRule,
model.ServiceEntry,
model.DestinationPolicy,
model.DestinationRule,
model.HTTPAPISpec,
model.HTTPAPISpecBinding,
model.QuotaSpec,
model.QuotaSpecBinding,
}
configs, ingresses, err := readConfigs(readers)
if err != nil {
return err
}
if err = validateConfigs(configs); err != nil {
return err
}
out := make([]model.Config, 0)
out = append(out, convert.DestinationPolicies(configs)...)
out = append(out, convert.RouteRules(configs)...)
out = append(out, convert.EgressRules(configs)...)
convertedIngresses, err := convert.IstioIngresses(ingresses, "")
if err == nil {
out = append(out, convertedIngresses...)
} else {
return multierror.Prefix(err, "Ingress rules invalid")
}
out = append(out, convert.RouteRuleRouteLabels(out, configs)...)
writeYAMLOutput(configDescriptor, out, writer)
// sanity check that the outputs are valid
if err := validateConfigs(out); err != nil {
return multierror.Prefix(err, "output config(s) are invalid:")
}
return nil
}
func readConfigs(readers []io.Reader) ([]model.Config, []*v1beta1.Ingress, error) {
out := make([]model.Config, 0)
outIngresses := make([]*v1beta1.Ingress, 0)
for _, reader := range readers {
data, err := ioutil.ReadAll(reader)
if err != nil {
return nil, nil, err
}
configs, kinds, err := crd.ParseInputs(string(data))
if err != nil {
return nil, nil, err
}
recognized := 0
for _, nonIstio := range kinds {
if nonIstio.Kind == "Ingress" &&
nonIstio.APIVersion == "extensions/v1beta1" {
ingress, err := parseIngress(nonIstio)
if err != nil {
log.Errorf("Could not decode ingress %v: %v", nonIstio.Name, err)
continue
}
outIngresses = append(outIngresses, ingress)
recognized++
}
}
if len(kinds) > recognized {
// If convert-networking-config was asked to convert non-network things,
// like Deployments and Services, return a brief informative error
kindsFound := make(map[string]bool)
for _, kind := range kinds {
kindsFound[kind.Kind] = true
}
var msg error
for kind := range kindsFound {
msg = multierror.Append(msg, fmt.Errorf("unsupported kind: %v", kind))
}
return nil, nil, msg
}
out = append(out, configs...)
}
return out, outIngresses, nil
}
func writeYAMLOutput(descriptor model.ConfigDescriptor, configs []model.Config, writer io.Writer) {
for i, config := range configs {
schema, exists := descriptor.GetByType(config.Type)
if !exists {
log.Errorf("Unknown kind %q for %v", crd.ResourceName(config.Type), config.Name)
continue
}
obj, err := crd.ConvertConfig(schema, config)
if err != nil {
log.Errorf("Could not decode %v: %v", config.Name, err)
continue
}
bytes, err := yaml.Marshal(obj)
if err != nil {
log.Errorf("Could not convert %v to YAML: %v", config, err)
continue
}
writer.Write(bytes) // nolint: errcheck
if i+1 < len(configs) {
writer.Write([]byte("---\n")) // nolint: errcheck
}
}
}
func validateConfigs(configs []model.Config) error {
var errs error
for _, config := range configs {
var err error
switch config.Type {
case model.RouteRule.Type:
err = model.ValidateRouteRule(config.Spec)
case model.VirtualService.Type:
err = model.ValidateVirtualService(config.Spec)
case model.Gateway.Type:
err = model.ValidateGateway(config.Spec)
case model.EgressRule.Type:
err = model.ValidateEgressRule(config.Spec)
case model.ServiceEntry.Type:
err = model.ValidateServiceEntry(config.Spec)
case model.DestinationPolicy.Type:
err = model.ValidateDestinationPolicy(config.Spec)
case model.DestinationRule.Type:
err = model.ValidateDestinationRule(config.Spec)
}
if err != nil {
errs = multierror.Append(err, errs)
}
}
return errs
}
func parseIngress(unparsed crd.IstioKind) (*v1beta1.Ingress, error) {
// To convert unparsed to a v1beta1.Ingress Marshal into JSON and Unmarshal back
b, err := json.Marshal(unparsed)
if err != nil {
return nil, multierror.Prefix(err, "can't reserialize Ingress")
}
out := &v1beta1.Ingress{}
err = json.Unmarshal(b, out)
if err != nil {
return nil, multierror.Prefix(err, "can't deserialize as Ingress")
}
return out, nil
}