| 1 |
/* |
| 2 |
Copyright 2016 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package builder |
| 18 |
|
| 19 |
import ( |
| 20 |
"encoding/json" |
| 21 |
"fmt" |
| 22 |
"net/http" |
| 23 |
"strings" |
| 24 |
|
| 25 |
restful "github.com/emicklei/go-restful/v3" |
| 26 |
|
| 27 |
"k8s.io/kube-openapi/pkg/common" |
| 28 |
"k8s.io/kube-openapi/pkg/common/restfuladapter" |
| 29 |
"k8s.io/kube-openapi/pkg/util" |
| 30 |
"k8s.io/kube-openapi/pkg/validation/spec" |
| 31 |
) |
| 32 |
|
| 33 |
const ( |
| 34 |
OpenAPIVersion = "2.0" |
| 35 |
) |
| 36 |
|
| 37 |
type openAPI struct { |
| 38 |
config *common.Config |
| 39 |
swagger *spec.Swagger |
| 40 |
protocolList []string |
| 41 |
definitions map[string]common.OpenAPIDefinition |
| 42 |
} |
| 43 |
|
| 44 |
// BuildOpenAPISpec builds OpenAPI spec given a list of route containers and common.Config to customize it. |
| 45 |
// |
| 46 |
// Deprecated: BuildOpenAPISpecFromRoutes should be used instead. |
| 47 |
func BuildOpenAPISpec(routeContainers []*restful.WebService, config *common.Config) (*spec.Swagger, error) { |
| 48 |
return BuildOpenAPISpecFromRoutes(restfuladapter.AdaptWebServices(routeContainers), config) |
| 49 |
} |
| 50 |
|
| 51 |
// BuildOpenAPISpecFromRoutes builds OpenAPI spec given a list of route containers and common.Config to customize it. |
| 52 |
func BuildOpenAPISpecFromRoutes(routeContainers []common.RouteContainer, config *common.Config) (*spec.Swagger, error) { |
| 53 |
o := newOpenAPI(config) |
| 54 |
err := o.buildPaths(routeContainers) |
| 55 |
if err != nil { |
| 56 |
return nil, err |
| 57 |
} |
| 58 |
return o.finalizeSwagger() |
| 59 |
} |
| 60 |
|
| 61 |
// BuildOpenAPIDefinitionsForResource builds a partial OpenAPI spec given a sample object and common.Config to customize it. |
| 62 |
func BuildOpenAPIDefinitionsForResource(model interface{}, config *common.Config) (*spec.Definitions, error) { |
| 63 |
o := newOpenAPI(config) |
| 64 |
// We can discard the return value of toSchema because all we care about is the side effect of calling it. |
| 65 |
// All the models created for this resource get added to o.swagger.Definitions |
| 66 |
_, err := o.toSchema(util.GetCanonicalTypeName(model)) |
| 67 |
if err != nil { |
| 68 |
return nil, err |
| 69 |
} |
| 70 |
swagger, err := o.finalizeSwagger() |
| 71 |
if err != nil { |
| 72 |
return nil, err |
| 73 |
} |
| 74 |
return &swagger.Definitions, nil |
| 75 |
} |
| 76 |
|
| 77 |
// BuildOpenAPIDefinitionsForResources returns the OpenAPI spec which includes the definitions for the |
| 78 |
// passed type names. |
| 79 |
func BuildOpenAPIDefinitionsForResources(config *common.Config, names ...string) (*spec.Swagger, error) { |
| 80 |
o := newOpenAPI(config) |
| 81 |
// We can discard the return value of toSchema because all we care about is the side effect of calling it. |
| 82 |
// All the models created for this resource get added to o.swagger.Definitions |
| 83 |
for _, name := range names { |
| 84 |
_, err := o.toSchema(name) |
| 85 |
if err != nil { |
| 86 |
return nil, err |
| 87 |
} |
| 88 |
} |
| 89 |
return o.finalizeSwagger() |
| 90 |
} |
| 91 |
|
| 92 |
// newOpenAPI sets up the openAPI object so we can build the spec. |
| 93 |
func newOpenAPI(config *common.Config) openAPI { |
| 94 |
o := openAPI{ |
| 95 |
config: config, |
| 96 |
swagger: &spec.Swagger{ |
| 97 |
SwaggerProps: spec.SwaggerProps{ |
| 98 |
Swagger: OpenAPIVersion, |
| 99 |
Definitions: spec.Definitions{}, |
| 100 |
Responses: config.ResponseDefinitions, |
| 101 |
Paths: &spec.Paths{Paths: map[string]spec.PathItem{}}, |
| 102 |
Info: config.Info, |
| 103 |
}, |
| 104 |
}, |
| 105 |
} |
| 106 |
|
| 107 |
if o.config.GetOperationIDAndTagsFromRoute == nil { |
| 108 |
// Map the deprecated handler to the common interface, if provided. |
| 109 |
if o.config.GetOperationIDAndTags != nil { |
| 110 |
o.config.GetOperationIDAndTagsFromRoute = func(r common.Route) (string, []string, error) { |
| 111 |
restfulRouteAdapter, ok := r.(*restfuladapter.RouteAdapter) |
| 112 |
if !ok { |
| 113 |
return "", nil, fmt.Errorf("config.GetOperationIDAndTags specified but route is not a restful v1 Route") |
| 114 |
} |
| 115 |
|
| 116 |
return o.config.GetOperationIDAndTags(restfulRouteAdapter.Route) |
| 117 |
} |
| 118 |
} else { |
| 119 |
o.config.GetOperationIDAndTagsFromRoute = func(r common.Route) (string, []string, error) { |
| 120 |
return r.OperationName(), nil, nil |
| 121 |
} |
| 122 |
} |
| 123 |
} |
| 124 |
|
| 125 |
if o.config.GetDefinitionName == nil { |
| 126 |
o.config.GetDefinitionName = func(name string) (string, spec.Extensions) { |
| 127 |
return name[strings.LastIndex(name, "/")+1:], nil |
| 128 |
} |
| 129 |
} |
| 130 |
o.definitions = o.config.GetDefinitions(func(name string) spec.Ref { |
| 131 |
defName, _ := o.config.GetDefinitionName(name) |
| 132 |
return spec.MustCreateRef("#/definitions/" + common.EscapeJsonPointer(defName)) |
| 133 |
}) |
| 134 |
if o.config.CommonResponses == nil { |
| 135 |
o.config.CommonResponses = map[int]spec.Response{} |
| 136 |
} |
| 137 |
return o |
| 138 |
} |
| 139 |
|
| 140 |
// finalizeSwagger is called after the spec is built and returns the final spec. |
| 141 |
// NOTE: finalizeSwagger also make changes to the final spec, as specified in the config. |
| 142 |
func (o *openAPI) finalizeSwagger() (*spec.Swagger, error) { |
| 143 |
if o.config.SecurityDefinitions != nil { |
| 144 |
o.swagger.SecurityDefinitions = *o.config.SecurityDefinitions |
| 145 |
o.swagger.Security = o.config.DefaultSecurity |
| 146 |
} |
| 147 |
if o.config.PostProcessSpec != nil { |
| 148 |
var err error |
| 149 |
o.swagger, err = o.config.PostProcessSpec(o.swagger) |
| 150 |
if err != nil { |
| 151 |
return nil, err |
| 152 |
} |
| 153 |
} |
| 154 |
|
| 155 |
return deduplicateParameters(o.swagger) |
| 156 |
} |
| 157 |
|
| 158 |
func (o *openAPI) buildDefinitionRecursively(name string) error { |
| 159 |
uniqueName, extensions := o.config.GetDefinitionName(name) |
| 160 |
escapedName := common.EscapeJsonPointer(uniqueName) |
| 161 |
if _, ok := o.swagger.Definitions[escapedName]; ok { |
| 162 |
return nil |
| 163 |
} |
| 164 |
if item, ok := o.definitions[name]; ok { |
| 165 |
schema := spec.Schema{ |
| 166 |
VendorExtensible: item.Schema.VendorExtensible, |
| 167 |
SchemaProps: item.Schema.SchemaProps, |
| 168 |
SwaggerSchemaProps: item.Schema.SwaggerSchemaProps, |
| 169 |
} |
| 170 |
if extensions != nil { |
| 171 |
if schema.Extensions == nil { |
| 172 |
schema.Extensions = spec.Extensions{} |
| 173 |
} |
| 174 |
for k, v := range extensions { |
| 175 |
schema.Extensions[k] = v |
| 176 |
} |
| 177 |
} |
| 178 |
if v, ok := item.Schema.Extensions[common.ExtensionV2Schema]; ok { |
| 179 |
if v2Schema, isOpenAPISchema := v.(spec.Schema); isOpenAPISchema { |
| 180 |
schema = v2Schema |
| 181 |
} |
| 182 |
} |
| 183 |
o.swagger.Definitions[escapedName] = schema |
| 184 |
for _, v := range item.Dependencies { |
| 185 |
if err := o.buildDefinitionRecursively(v); err != nil { |
| 186 |
return err |
| 187 |
} |
| 188 |
} |
| 189 |
} else { |
| 190 |
return fmt.Errorf("cannot find model definition for %v. If you added a new type, you may need to add +k8s:openapi-gen=true to the package or type and run code-gen again", name) |
| 191 |
} |
| 192 |
return nil |
| 193 |
} |
| 194 |
|
| 195 |
// buildDefinitionForType build a definition for a given type and return a referable name to its definition. |
| 196 |
// This is the main function that keep track of definitions used in this spec and is depend on code generated |
| 197 |
// by k8s.io/kubernetes/cmd/libs/go2idl/openapi-gen. |
| 198 |
func (o *openAPI) buildDefinitionForType(name string) (string, error) { |
| 199 |
if err := o.buildDefinitionRecursively(name); err != nil { |
| 200 |
return "", err |
| 201 |
} |
| 202 |
defName, _ := o.config.GetDefinitionName(name) |
| 203 |
return "#/definitions/" + common.EscapeJsonPointer(defName), nil |
| 204 |
} |
| 205 |
|
| 206 |
// buildPaths builds OpenAPI paths using go-restful's web services. |
| 207 |
func (o *openAPI) buildPaths(routeContainers []common.RouteContainer) error { |
| 208 |
pathsToIgnore := util.NewTrie(o.config.IgnorePrefixes) |
| 209 |
duplicateOpId := make(map[string]string) |
| 210 |
for _, w := range routeContainers { |
| 211 |
rootPath := w.RootPath() |
| 212 |
if pathsToIgnore.HasPrefix(rootPath) { |
| 213 |
continue |
| 214 |
} |
| 215 |
commonParams, err := o.buildParameters(w.PathParameters()) |
| 216 |
if err != nil { |
| 217 |
return err |
| 218 |
} |
| 219 |
for path, routes := range groupRoutesByPath(w.Routes()) { |
| 220 |
// go-swagger has special variable definition {$NAME:*} that can only be |
| 221 |
// used at the end of the path and it is not recognized by OpenAPI. |
| 222 |
if strings.HasSuffix(path, ":*}") { |
| 223 |
path = path[:len(path)-3] + "}" |
| 224 |
} |
| 225 |
if pathsToIgnore.HasPrefix(path) { |
| 226 |
continue |
| 227 |
} |
| 228 |
// Aggregating common parameters make API spec (and generated clients) simpler |
| 229 |
inPathCommonParamsMap, err := o.findCommonParameters(routes) |
| 230 |
if err != nil { |
| 231 |
return err |
| 232 |
} |
| 233 |
pathItem, exists := o.swagger.Paths.Paths[path] |
| 234 |
if exists { |
| 235 |
return fmt.Errorf("duplicate webservice route has been found for path: %v", path) |
| 236 |
} |
| 237 |
pathItem = spec.PathItem{ |
| 238 |
PathItemProps: spec.PathItemProps{ |
| 239 |
Parameters: make([]spec.Parameter, 0), |
| 240 |
}, |
| 241 |
} |
| 242 |
// add web services's parameters as well as any parameters appears in all ops, as common parameters |
| 243 |
pathItem.Parameters = append(pathItem.Parameters, commonParams...) |
| 244 |
for _, p := range inPathCommonParamsMap { |
| 245 |
pathItem.Parameters = append(pathItem.Parameters, p) |
| 246 |
} |
| 247 |
sortParameters(pathItem.Parameters) |
| 248 |
for _, route := range routes { |
| 249 |
op, err := o.buildOperations(route, inPathCommonParamsMap) |
| 250 |
sortParameters(op.Parameters) |
| 251 |
if err != nil { |
| 252 |
return err |
| 253 |
} |
| 254 |
dpath, exists := duplicateOpId[op.ID] |
| 255 |
if exists { |
| 256 |
return fmt.Errorf("duplicate Operation ID %v for path %v and %v", op.ID, dpath, path) |
| 257 |
} else { |
| 258 |
duplicateOpId[op.ID] = path |
| 259 |
} |
| 260 |
switch strings.ToUpper(route.Method()) { |
| 261 |
case "GET": |
| 262 |
pathItem.Get = op |
| 263 |
case "POST": |
| 264 |
pathItem.Post = op |
| 265 |
case "HEAD": |
| 266 |
pathItem.Head = op |
| 267 |
case "PUT": |
| 268 |
pathItem.Put = op |
| 269 |
case "DELETE": |
| 270 |
pathItem.Delete = op |
| 271 |
case "OPTIONS": |
| 272 |
pathItem.Options = op |
| 273 |
case "PATCH": |
| 274 |
pathItem.Patch = op |
| 275 |
} |
| 276 |
} |
| 277 |
o.swagger.Paths.Paths[path] = pathItem |
| 278 |
} |
| 279 |
} |
| 280 |
return nil |
| 281 |
} |
| 282 |
|
| 283 |
// buildOperations builds operations for each webservice path |
| 284 |
func (o *openAPI) buildOperations(route common.Route, inPathCommonParamsMap map[interface{}]spec.Parameter) (ret *spec.Operation, err error) { |
| 285 |
ret = &spec.Operation{ |
| 286 |
OperationProps: spec.OperationProps{ |
| 287 |
Description: route.Description(), |
| 288 |
Consumes: route.Consumes(), |
| 289 |
Produces: route.Produces(), |
| 290 |
Schemes: o.config.ProtocolList, |
| 291 |
Responses: &spec.Responses{ |
| 292 |
ResponsesProps: spec.ResponsesProps{ |
| 293 |
StatusCodeResponses: make(map[int]spec.Response), |
| 294 |
}, |
| 295 |
}, |
| 296 |
}, |
| 297 |
} |
| 298 |
for k, v := range route.Metadata() { |
| 299 |
if strings.HasPrefix(k, common.ExtensionPrefix) { |
| 300 |
if ret.Extensions == nil { |
| 301 |
ret.Extensions = spec.Extensions{} |
| 302 |
} |
| 303 |
ret.Extensions.Add(k, v) |
| 304 |
} |
| 305 |
} |
| 306 |
if ret.ID, ret.Tags, err = o.config.GetOperationIDAndTagsFromRoute(route); err != nil { |
| 307 |
return ret, err |
| 308 |
} |
| 309 |
|
| 310 |
// Build responses |
| 311 |
for _, resp := range route.StatusCodeResponses() { |
| 312 |
ret.Responses.StatusCodeResponses[resp.Code()], err = o.buildResponse(resp.Model(), resp.Message()) |
| 313 |
if err != nil { |
| 314 |
return ret, err |
| 315 |
} |
| 316 |
} |
| 317 |
// If there is no response but a write sample, assume that write sample is an http.StatusOK response. |
| 318 |
if len(ret.Responses.StatusCodeResponses) == 0 && route.ResponsePayloadSample() != nil { |
| 319 |
ret.Responses.StatusCodeResponses[http.StatusOK], err = o.buildResponse(route.ResponsePayloadSample(), "OK") |
| 320 |
if err != nil { |
| 321 |
return ret, err |
| 322 |
} |
| 323 |
} |
| 324 |
for code, resp := range o.config.CommonResponses { |
| 325 |
if _, exists := ret.Responses.StatusCodeResponses[code]; !exists { |
| 326 |
ret.Responses.StatusCodeResponses[code] = resp |
| 327 |
} |
| 328 |
} |
| 329 |
// If there is still no response, use default response provided. |
| 330 |
if len(ret.Responses.StatusCodeResponses) == 0 { |
| 331 |
ret.Responses.Default = o.config.DefaultResponse |
| 332 |
} |
| 333 |
|
| 334 |
// Build non-common Parameters |
| 335 |
ret.Parameters = make([]spec.Parameter, 0) |
| 336 |
for _, param := range route.Parameters() { |
| 337 |
if _, isCommon := inPathCommonParamsMap[mapKeyFromParam(param)]; !isCommon { |
| 338 |
openAPIParam, err := o.buildParameter(param, route.RequestPayloadSample()) |
| 339 |
if err != nil { |
| 340 |
return ret, err |
| 341 |
} |
| 342 |
ret.Parameters = append(ret.Parameters, openAPIParam) |
| 343 |
} |
| 344 |
} |
| 345 |
return ret, nil |
| 346 |
} |
| 347 |
|
| 348 |
func (o *openAPI) buildResponse(model interface{}, description string) (spec.Response, error) { |
| 349 |
schema, err := o.toSchema(util.GetCanonicalTypeName(model)) |
| 350 |
if err != nil { |
| 351 |
return spec.Response{}, err |
| 352 |
} |
| 353 |
return spec.Response{ |
| 354 |
ResponseProps: spec.ResponseProps{ |
| 355 |
Description: description, |
| 356 |
Schema: schema, |
| 357 |
}, |
| 358 |
}, nil |
| 359 |
} |
| 360 |
|
| 361 |
func (o *openAPI) findCommonParameters(routes []common.Route) (map[interface{}]spec.Parameter, error) { |
| 362 |
commonParamsMap := make(map[interface{}]spec.Parameter, 0) |
| 363 |
paramOpsCountByName := make(map[interface{}]int, 0) |
| 364 |
paramNameKindToDataMap := make(map[interface{}]common.Parameter, 0) |
| 365 |
for _, route := range routes { |
| 366 |
routeParamDuplicateMap := make(map[interface{}]bool) |
| 367 |
s := "" |
| 368 |
params := route.Parameters() |
| 369 |
for _, param := range params { |
| 370 |
m, _ := json.Marshal(param) |
| 371 |
s += string(m) + "\n" |
| 372 |
key := mapKeyFromParam(param) |
| 373 |
if routeParamDuplicateMap[key] { |
| 374 |
msg, _ := json.Marshal(params) |
| 375 |
return commonParamsMap, fmt.Errorf("duplicate parameter %v for route %v, %v", param.Name(), string(msg), s) |
| 376 |
} |
| 377 |
routeParamDuplicateMap[key] = true |
| 378 |
paramOpsCountByName[key]++ |
| 379 |
paramNameKindToDataMap[key] = param |
| 380 |
} |
| 381 |
} |
| 382 |
for key, count := range paramOpsCountByName { |
| 383 |
paramData := paramNameKindToDataMap[key] |
| 384 |
if count == len(routes) && paramData.Kind() != common.BodyParameterKind { |
| 385 |
openAPIParam, err := o.buildParameter(paramData, nil) |
| 386 |
if err != nil { |
| 387 |
return commonParamsMap, err |
| 388 |
} |
| 389 |
commonParamsMap[key] = openAPIParam |
| 390 |
} |
| 391 |
} |
| 392 |
return commonParamsMap, nil |
| 393 |
} |
| 394 |
|
| 395 |
func (o *openAPI) toSchema(name string) (_ *spec.Schema, err error) { |
| 396 |
if openAPIType, openAPIFormat := common.OpenAPITypeFormat(name); openAPIType != "" { |
| 397 |
return &spec.Schema{ |
| 398 |
SchemaProps: spec.SchemaProps{ |
| 399 |
Type: []string{openAPIType}, |
| 400 |
Format: openAPIFormat, |
| 401 |
}, |
| 402 |
}, nil |
| 403 |
} else { |
| 404 |
ref, err := o.buildDefinitionForType(name) |
| 405 |
if err != nil { |
| 406 |
return nil, err |
| 407 |
} |
| 408 |
return &spec.Schema{ |
| 409 |
SchemaProps: spec.SchemaProps{ |
| 410 |
Ref: spec.MustCreateRef(ref), |
| 411 |
}, |
| 412 |
}, nil |
| 413 |
} |
| 414 |
} |
| 415 |
|
| 416 |
func (o *openAPI) buildParameter(restParam common.Parameter, bodySample interface{}) (ret spec.Parameter, err error) { |
| 417 |
ret = spec.Parameter{ |
| 418 |
ParamProps: spec.ParamProps{ |
| 419 |
Name: restParam.Name(), |
| 420 |
Description: restParam.Description(), |
| 421 |
Required: restParam.Required(), |
| 422 |
}, |
| 423 |
} |
| 424 |
switch restParam.Kind() { |
| 425 |
case common.BodyParameterKind: |
| 426 |
if bodySample != nil { |
| 427 |
ret.In = "body" |
| 428 |
ret.Schema, err = o.toSchema(util.GetCanonicalTypeName(bodySample)) |
| 429 |
return ret, err |
| 430 |
} else { |
| 431 |
// There is not enough information in the body parameter to build the definition. |
| 432 |
// Body parameter has a data type that is a short name but we need full package name |
| 433 |
// of the type to create a definition. |
| 434 |
return ret, fmt.Errorf("restful body parameters are not supported: %v", restParam.DataType()) |
| 435 |
} |
| 436 |
case common.PathParameterKind: |
| 437 |
ret.In = "path" |
| 438 |
if !restParam.Required() { |
| 439 |
return ret, fmt.Errorf("path parameters should be marked at required for parameter %v", restParam) |
| 440 |
} |
| 441 |
case common.QueryParameterKind: |
| 442 |
ret.In = "query" |
| 443 |
case common.HeaderParameterKind: |
| 444 |
ret.In = "header" |
| 445 |
case common.FormParameterKind: |
| 446 |
ret.In = "formData" |
| 447 |
default: |
| 448 |
return ret, fmt.Errorf("unknown restful operation kind : %v", restParam.Kind()) |
| 449 |
} |
| 450 |
openAPIType, openAPIFormat := common.OpenAPITypeFormat(restParam.DataType()) |
| 451 |
if openAPIType == "" { |
| 452 |
return ret, fmt.Errorf("non-body Restful parameter type should be a simple type, but got : %v", restParam.DataType()) |
| 453 |
} |
| 454 |
ret.Type = openAPIType |
| 455 |
ret.Format = openAPIFormat |
| 456 |
ret.UniqueItems = !restParam.AllowMultiple() |
| 457 |
return ret, nil |
| 458 |
} |
| 459 |
|
| 460 |
func (o *openAPI) buildParameters(restParam []common.Parameter) (ret []spec.Parameter, err error) { |
| 461 |
ret = make([]spec.Parameter, len(restParam)) |
| 462 |
for i, v := range restParam { |
| 463 |
ret[i], err = o.buildParameter(v, nil) |
| 464 |
if err != nil { |
| 465 |
return ret, err |
| 466 |
} |
| 467 |
} |
| 468 |
return ret, nil |
| 469 |
} |