github.com/spinnaker/spin@v1.30.0/gateapi/client.go (about) 1 /* 2 * Spinnaker API 3 * 4 * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) 5 * 6 * API version: 1.0.0 7 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) 8 */ 9 10 package swagger 11 12 import ( 13 "bytes" 14 "context" 15 "encoding/json" 16 "encoding/xml" 17 "errors" 18 "fmt" 19 "io" 20 "mime/multipart" 21 "net/http" 22 "net/url" 23 "os" 24 "path/filepath" 25 "reflect" 26 "regexp" 27 "strconv" 28 "strings" 29 "time" 30 "unicode/utf8" 31 32 "golang.org/x/oauth2" 33 ) 34 35 var ( 36 jsonCheck = regexp.MustCompile("(?i:(?:application|text)/json)") 37 xmlCheck = regexp.MustCompile("(?i:(?:application|text)/xml)") 38 ) 39 40 // APIClient manages communication with the Spinnaker API API v1.0.0 41 // In most cases there should be only one, shared, APIClient. 42 type APIClient struct { 43 cfg *Configuration 44 common service // Reuse a single struct instead of allocating one for each service on the heap. 45 46 // API Services 47 48 AmazonInfrastructureControllerApi *AmazonInfrastructureControllerApiService 49 50 ApplicationControllerApi *ApplicationControllerApiService 51 52 ArtifactControllerApi *ArtifactControllerApiService 53 54 AuthControllerApi *AuthControllerApiService 55 56 BakeControllerApi *BakeControllerApiService 57 58 BuildControllerApi *BuildControllerApiService 59 60 CiControllerApi *CiControllerApiService 61 62 ClusterControllerApi *ClusterControllerApiService 63 64 ConcourseControllerApi *ConcourseControllerApiService 65 66 CredentialsControllerApi *CredentialsControllerApiService 67 68 DeckPluginsControllerApi *DeckPluginsControllerApiService 69 70 EcsServerGroupEventsControllerApi *EcsServerGroupEventsControllerApiService 71 72 ExecutionsControllerApi *ExecutionsControllerApiService 73 74 FirewallControllerApi *FirewallControllerApiService 75 76 ImageControllerApi *ImageControllerApiService 77 78 InstanceControllerApi *InstanceControllerApiService 79 80 JobControllerApi *JobControllerApiService 81 82 LoadBalancerControllerApi *LoadBalancerControllerApiService 83 84 ManagedControllerApi *ManagedControllerApiService 85 86 NetworkControllerApi *NetworkControllerApiService 87 88 PipelineConfigControllerApi *PipelineConfigControllerApiService 89 90 PipelineControllerApi *PipelineControllerApiService 91 92 PipelineTemplatesControllerApi *PipelineTemplatesControllerApiService 93 94 PluginInfoControllerApi *PluginInfoControllerApiService 95 96 PluginPublishControllerApi *PluginPublishControllerApiService 97 98 PluginsInstalledControllerApi *PluginsInstalledControllerApiService 99 100 ProjectControllerApi *ProjectControllerApiService 101 102 PubsubSubscriptionControllerApi *PubsubSubscriptionControllerApiService 103 104 RawResourceControllerApi *RawResourceControllerApiService 105 106 ReorderPipelinesControllerApi *ReorderPipelinesControllerApiService 107 108 SearchControllerApi *SearchControllerApiService 109 110 SecurityGroupControllerApi *SecurityGroupControllerApiService 111 112 ServerGroupControllerApi *ServerGroupControllerApiService 113 114 ServerGroupManagerControllerApi *ServerGroupManagerControllerApiService 115 116 SnapshotControllerApi *SnapshotControllerApiService 117 118 SubnetControllerApi *SubnetControllerApiService 119 120 TaskControllerApi *TaskControllerApiService 121 122 V2CanaryConfigControllerApi *V2CanaryConfigControllerApiService 123 124 V2CanaryControllerApi *V2CanaryControllerApiService 125 126 V2PipelineTemplatesControllerApi *V2PipelineTemplatesControllerApiService 127 128 VersionControllerApi *VersionControllerApiService 129 130 WebhookControllerApi *WebhookControllerApiService 131 } 132 133 type service struct { 134 client *APIClient 135 } 136 137 // NewAPIClient creates a new API client. Requires a userAgent string describing your application. 138 // optionally a custom http.Client to allow for advanced features such as caching. 139 func NewAPIClient(cfg *Configuration) *APIClient { 140 if cfg.HTTPClient == nil { 141 cfg.HTTPClient = http.DefaultClient 142 } 143 144 c := &APIClient{} 145 c.cfg = cfg 146 c.common.client = c 147 148 // API Services 149 c.AmazonInfrastructureControllerApi = (*AmazonInfrastructureControllerApiService)(&c.common) 150 c.ApplicationControllerApi = (*ApplicationControllerApiService)(&c.common) 151 c.ArtifactControllerApi = (*ArtifactControllerApiService)(&c.common) 152 c.AuthControllerApi = (*AuthControllerApiService)(&c.common) 153 c.BakeControllerApi = (*BakeControllerApiService)(&c.common) 154 c.BuildControllerApi = (*BuildControllerApiService)(&c.common) 155 c.CiControllerApi = (*CiControllerApiService)(&c.common) 156 c.ClusterControllerApi = (*ClusterControllerApiService)(&c.common) 157 c.ConcourseControllerApi = (*ConcourseControllerApiService)(&c.common) 158 c.CredentialsControllerApi = (*CredentialsControllerApiService)(&c.common) 159 c.DeckPluginsControllerApi = (*DeckPluginsControllerApiService)(&c.common) 160 c.EcsServerGroupEventsControllerApi = (*EcsServerGroupEventsControllerApiService)(&c.common) 161 c.ExecutionsControllerApi = (*ExecutionsControllerApiService)(&c.common) 162 c.FirewallControllerApi = (*FirewallControllerApiService)(&c.common) 163 c.ImageControllerApi = (*ImageControllerApiService)(&c.common) 164 c.InstanceControllerApi = (*InstanceControllerApiService)(&c.common) 165 c.JobControllerApi = (*JobControllerApiService)(&c.common) 166 c.LoadBalancerControllerApi = (*LoadBalancerControllerApiService)(&c.common) 167 c.ManagedControllerApi = (*ManagedControllerApiService)(&c.common) 168 c.NetworkControllerApi = (*NetworkControllerApiService)(&c.common) 169 c.PipelineConfigControllerApi = (*PipelineConfigControllerApiService)(&c.common) 170 c.PipelineControllerApi = (*PipelineControllerApiService)(&c.common) 171 c.PipelineTemplatesControllerApi = (*PipelineTemplatesControllerApiService)(&c.common) 172 c.PluginInfoControllerApi = (*PluginInfoControllerApiService)(&c.common) 173 c.PluginPublishControllerApi = (*PluginPublishControllerApiService)(&c.common) 174 c.PluginsInstalledControllerApi = (*PluginsInstalledControllerApiService)(&c.common) 175 c.ProjectControllerApi = (*ProjectControllerApiService)(&c.common) 176 c.PubsubSubscriptionControllerApi = (*PubsubSubscriptionControllerApiService)(&c.common) 177 c.RawResourceControllerApi = (*RawResourceControllerApiService)(&c.common) 178 c.ReorderPipelinesControllerApi = (*ReorderPipelinesControllerApiService)(&c.common) 179 c.SearchControllerApi = (*SearchControllerApiService)(&c.common) 180 c.SecurityGroupControllerApi = (*SecurityGroupControllerApiService)(&c.common) 181 c.ServerGroupControllerApi = (*ServerGroupControllerApiService)(&c.common) 182 c.ServerGroupManagerControllerApi = (*ServerGroupManagerControllerApiService)(&c.common) 183 c.SnapshotControllerApi = (*SnapshotControllerApiService)(&c.common) 184 c.SubnetControllerApi = (*SubnetControllerApiService)(&c.common) 185 c.TaskControllerApi = (*TaskControllerApiService)(&c.common) 186 c.V2CanaryConfigControllerApi = (*V2CanaryConfigControllerApiService)(&c.common) 187 c.V2CanaryControllerApi = (*V2CanaryControllerApiService)(&c.common) 188 c.V2PipelineTemplatesControllerApi = (*V2PipelineTemplatesControllerApiService)(&c.common) 189 c.VersionControllerApi = (*VersionControllerApiService)(&c.common) 190 c.WebhookControllerApi = (*WebhookControllerApiService)(&c.common) 191 192 return c 193 } 194 195 func atoi(in string) (int, error) { 196 return strconv.Atoi(in) 197 } 198 199 // selectHeaderContentType select a content type from the available list. 200 func selectHeaderContentType(contentTypes []string) string { 201 if len(contentTypes) == 0 { 202 return "" 203 } 204 if contains(contentTypes, "application/json") { 205 return "application/json" 206 } 207 return contentTypes[0] // use the first content type specified in 'consumes' 208 } 209 210 // selectHeaderAccept join all accept types and return 211 func selectHeaderAccept(accepts []string) string { 212 if len(accepts) == 0 { 213 return "" 214 } 215 216 if contains(accepts, "application/json") { 217 return "application/json" 218 } 219 220 return strings.Join(accepts, ",") 221 } 222 223 // contains is a case insenstive match, finding needle in a haystack 224 func contains(haystack []string, needle string) bool { 225 for _, a := range haystack { 226 if strings.ToLower(a) == strings.ToLower(needle) { 227 return true 228 } 229 } 230 return false 231 } 232 233 // Verify optional parameters are of the correct type. 234 func typeCheckParameter(obj interface{}, expected string, name string) error { 235 // Make sure there is an object. 236 if obj == nil { 237 return nil 238 } 239 240 // Check the type is as expected. 241 if reflect.TypeOf(obj).String() != expected { 242 return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) 243 } 244 return nil 245 } 246 247 // parameterToString convert interface{} parameters to string, using a delimiter if format is provided. 248 func parameterToString(obj interface{}, collectionFormat string) string { 249 var delimiter string 250 251 switch collectionFormat { 252 case "pipes": 253 delimiter = "|" 254 case "ssv": 255 delimiter = " " 256 case "tsv": 257 delimiter = "\t" 258 case "csv": 259 delimiter = "," 260 } 261 262 if reflect.TypeOf(obj).Kind() == reflect.Slice { 263 return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") 264 } 265 266 return fmt.Sprintf("%v", obj) 267 } 268 269 // callAPI do the request. 270 func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { 271 return c.cfg.HTTPClient.Do(request) 272 } 273 274 // Change base path to allow switching to mocks 275 func (c *APIClient) ChangeBasePath(path string) { 276 c.cfg.BasePath = path 277 } 278 279 // prepareRequest build the request 280 func (c *APIClient) prepareRequest( 281 ctx context.Context, 282 path string, method string, 283 postBody interface{}, 284 headerParams map[string]string, 285 queryParams url.Values, 286 formParams url.Values, 287 fileName string, 288 fileBytes []byte) (localVarRequest *http.Request, err error) { 289 290 var body *bytes.Buffer 291 292 // Detect postBody type and post. 293 if postBody != nil { 294 contentType := headerParams["Content-Type"] 295 if contentType == "" { 296 contentType = detectContentType(postBody) 297 headerParams["Content-Type"] = contentType 298 } 299 300 body, err = setBody(postBody, contentType) 301 if err != nil { 302 return nil, err 303 } 304 } 305 306 // add form parameters and file if available. 307 if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { 308 if body != nil { 309 return nil, errors.New("Cannot specify postBody and multipart form at the same time.") 310 } 311 body = &bytes.Buffer{} 312 w := multipart.NewWriter(body) 313 314 for k, v := range formParams { 315 for _, iv := range v { 316 if strings.HasPrefix(k, "@") { // file 317 err = addFile(w, k[1:], iv) 318 if err != nil { 319 return nil, err 320 } 321 } else { // form value 322 w.WriteField(k, iv) 323 } 324 } 325 } 326 if len(fileBytes) > 0 && fileName != "" { 327 w.Boundary() 328 //_, fileNm := filepath.Split(fileName) 329 part, err := w.CreateFormFile("file", filepath.Base(fileName)) 330 if err != nil { 331 return nil, err 332 } 333 _, err = part.Write(fileBytes) 334 if err != nil { 335 return nil, err 336 } 337 // Set the Boundary in the Content-Type 338 headerParams["Content-Type"] = w.FormDataContentType() 339 } 340 341 // Set Content-Length 342 headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) 343 w.Close() 344 } 345 346 if strings.HasPrefix(headerParams["Content-Type"], "application/x-www-form-urlencoded") && len(formParams) > 0 { 347 if body != nil { 348 return nil, errors.New("Cannot specify postBody and x-www-form-urlencoded form at the same time.") 349 } 350 body = &bytes.Buffer{} 351 body.WriteString(formParams.Encode()) 352 // Set Content-Length 353 headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) 354 } 355 356 // Setup path and query parameters 357 url, err := url.Parse(path) 358 if err != nil { 359 return nil, err 360 } 361 362 // Adding Query Param 363 query := url.Query() 364 for k, v := range queryParams { 365 for _, iv := range v { 366 query.Add(k, iv) 367 } 368 } 369 370 // Encode the parameters. 371 url.RawQuery = query.Encode() 372 373 // Generate a new request 374 if body != nil { 375 localVarRequest, err = http.NewRequest(method, url.String(), body) 376 } else { 377 localVarRequest, err = http.NewRequest(method, url.String(), nil) 378 } 379 if err != nil { 380 return nil, err 381 } 382 383 // add header parameters, if any 384 if len(headerParams) > 0 { 385 headers := http.Header{} 386 for h, v := range headerParams { 387 headers.Set(h, v) 388 } 389 localVarRequest.Header = headers 390 } 391 392 // Override request host, if applicable 393 if c.cfg.Host != "" { 394 localVarRequest.Host = c.cfg.Host 395 } 396 397 // Add the user agent to the request. 398 localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) 399 400 if ctx != nil { 401 // add context to the request 402 localVarRequest = localVarRequest.WithContext(ctx) 403 404 // Walk through any authentication. 405 406 // OAuth2 authentication 407 if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { 408 // We were able to grab an oauth2 token from the context 409 var latestToken *oauth2.Token 410 if latestToken, err = tok.Token(); err != nil { 411 return nil, err 412 } 413 414 latestToken.SetAuthHeader(localVarRequest) 415 } 416 417 // Basic HTTP Authentication 418 if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { 419 localVarRequest.SetBasicAuth(auth.UserName, auth.Password) 420 } 421 422 // AccessToken Authentication 423 if auth, ok := ctx.Value(ContextAccessToken).(string); ok { 424 localVarRequest.Header.Add("Authorization", "Bearer "+auth) 425 } 426 } 427 428 for header, value := range c.cfg.DefaultHeader { 429 localVarRequest.Header.Add(header, value) 430 } 431 432 return localVarRequest, nil 433 } 434 435 func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { 436 if strings.Contains(contentType, "application/xml") { 437 if err = xml.Unmarshal(b, v); err != nil { 438 return err 439 } 440 return nil 441 } else if strings.Contains(contentType, "application/json") { 442 if err = json.Unmarshal(b, v); err != nil { 443 return err 444 } 445 return nil 446 } 447 return errors.New("undefined response type") 448 } 449 450 // Add a file to the multipart request 451 func addFile(w *multipart.Writer, fieldName, path string) error { 452 file, err := os.Open(path) 453 if err != nil { 454 return err 455 } 456 defer file.Close() 457 458 part, err := w.CreateFormFile(fieldName, filepath.Base(path)) 459 if err != nil { 460 return err 461 } 462 _, err = io.Copy(part, file) 463 464 return err 465 } 466 467 // Prevent trying to import "fmt" 468 func reportError(format string, a ...interface{}) error { 469 return fmt.Errorf(format, a...) 470 } 471 472 // Set request body from an interface{} 473 func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { 474 if bodyBuf == nil { 475 bodyBuf = &bytes.Buffer{} 476 } 477 478 if reader, ok := body.(io.Reader); ok { 479 _, err = bodyBuf.ReadFrom(reader) 480 } else if b, ok := body.([]byte); ok { 481 _, err = bodyBuf.Write(b) 482 } else if s, ok := body.(string); ok { 483 _, err = bodyBuf.WriteString(s) 484 } else if s, ok := body.(*string); ok { 485 _, err = bodyBuf.WriteString(*s) 486 } else if jsonCheck.MatchString(contentType) { 487 err = json.NewEncoder(bodyBuf).Encode(body) 488 } else if xmlCheck.MatchString(contentType) { 489 xml.NewEncoder(bodyBuf).Encode(body) 490 } 491 492 if err != nil { 493 return nil, err 494 } 495 496 if bodyBuf.Len() == 0 { 497 err = fmt.Errorf("Invalid body type %s\n", contentType) 498 return nil, err 499 } 500 return bodyBuf, nil 501 } 502 503 // detectContentType method is used to figure out `Request.Body` content type for request header 504 func detectContentType(body interface{}) string { 505 contentType := "text/plain; charset=utf-8" 506 kind := reflect.TypeOf(body).Kind() 507 508 switch kind { 509 case reflect.Struct, reflect.Map, reflect.Ptr: 510 contentType = "application/json; charset=utf-8" 511 case reflect.String: 512 contentType = "text/plain; charset=utf-8" 513 default: 514 if b, ok := body.([]byte); ok { 515 contentType = http.DetectContentType(b) 516 } else if kind == reflect.Slice { 517 contentType = "application/json; charset=utf-8" 518 } 519 } 520 521 return contentType 522 } 523 524 // Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go 525 type cacheControl map[string]string 526 527 func parseCacheControl(headers http.Header) cacheControl { 528 cc := cacheControl{} 529 ccHeader := headers.Get("Cache-Control") 530 for _, part := range strings.Split(ccHeader, ",") { 531 part = strings.Trim(part, " ") 532 if part == "" { 533 continue 534 } 535 if strings.ContainsRune(part, '=') { 536 keyval := strings.Split(part, "=") 537 cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") 538 } else { 539 cc[part] = "" 540 } 541 } 542 return cc 543 } 544 545 // CacheExpires helper function to determine remaining time before repeating a request. 546 func CacheExpires(r *http.Response) time.Time { 547 // Figure out when the cache expires. 548 var expires time.Time 549 now, err := time.Parse(time.RFC1123, r.Header.Get("date")) 550 if err != nil { 551 return time.Now() 552 } 553 respCacheControl := parseCacheControl(r.Header) 554 555 if maxAge, ok := respCacheControl["max-age"]; ok { 556 lifetime, err := time.ParseDuration(maxAge + "s") 557 if err != nil { 558 expires = now 559 } 560 expires = now.Add(lifetime) 561 } else { 562 expiresHeader := r.Header.Get("Expires") 563 if expiresHeader != "" { 564 expires, err = time.Parse(time.RFC1123, expiresHeader) 565 if err != nil { 566 expires = now 567 } 568 } 569 } 570 return expires 571 } 572 573 func strlen(s string) int { 574 return utf8.RuneCountInString(s) 575 } 576 577 // GenericSwaggerError Provides access to the body, error and model on returned errors. 578 type GenericSwaggerError struct { 579 body []byte 580 error string 581 model interface{} 582 } 583 584 // Error returns non-empty string if there was an error. 585 func (e GenericSwaggerError) Error() string { 586 return e.error 587 } 588 589 // Body returns the raw bytes of the response 590 func (e GenericSwaggerError) Body() []byte { 591 return e.body 592 } 593 594 // Model returns the unpacked model of the error 595 func (e GenericSwaggerError) Model() interface{} { 596 return e.model 597 }