├── .gitignore ├── .travis.yml ├── LICENSE ├── Makefile ├── README.md ├── cluster.go ├── credentials.go ├── glide.lock ├── glide.yaml ├── libcarina.go ├── libcarina_test.go ├── metadata.go └── task.go /.gitignore: -------------------------------------------------------------------------------- 1 | /vendor -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.6 5 | 6 | install: 7 | - make get-deps 8 | 9 | script: 10 | - make test 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2015 Rackspace 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | GOFILES = $(wildcard **/*.go) 2 | GOFILES_NOVENDOR = $(shell go list ./... | grep -v /vendor/) 3 | 4 | default: get-deps validate local 5 | 6 | get-deps: 7 | go get github.com/Masterminds/glide 8 | glide install 9 | 10 | validate: 11 | go fmt $(GOFILES_NOVENDOR) 12 | go vet $(GOFILES_NOVENDOR) 13 | go list ./... | grep -v /vendor/ | xargs -L1 golint --set_exit_status 14 | 15 | local: $(GOFILES) 16 | go build . 17 | 18 | test: local 19 | go test -v $(GOFILES_NOVENDOR) 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # libcarina 2 | 3 | [![GoDoc](https://godoc.org/github.com/getcarina/libcarina?status.png)](https://godoc.org/github.com/getcarina/libcarina) 4 | 5 | Provisional Go bindings for the beta release of [Carina](https://getcarina.com) by Rackspace. The `carina` client source 6 | code can be found at [https://github.com/getcarina/carina](https://github.com/getcarina/carina). 7 | 8 | ![](https://cloud.githubusercontent.com/assets/836375/10503963/e5bcca8c-72c0-11e5-8e14-2c1697297d7e.png) 9 | 10 | ## Examples 11 | 12 | ### Create 13 | Create a new cluster 14 | 15 | ```go 16 | package main 17 | 18 | import ( 19 | "time" 20 | 21 | "github.com/getcarina/libcarina" 22 | ) 23 | 24 | func createCluster(username string, apikey string, clusterName string) error { 25 | // Connect to Carina 26 | cli, _ := libcarina.NewClusterClient(libcarina.BetaEndpoint, username, apikey, "") 27 | 28 | // Create a new cluster 29 | cluster, err := cli.Create(libcarina.Cluster{ 30 | Name: clusterName, 31 | ClusterTypeId: 1, 32 | }) 33 | 34 | // Wait for the cluster to become active 35 | for cluster.Status == "creating" { 36 | time.Sleep(10 * time.Second) 37 | cluster, err = cli.Get(cluster.ID) 38 | } 39 | 40 | return err 41 | } 42 | ``` 43 | 44 | ### Swarm 45 | Connect to a Docker Swarm cluster 46 | 47 | ```go 48 | package main 49 | 50 | import ( 51 | "fmt" 52 | "os" 53 | "time" 54 | 55 | "github.com/getcarina/libcarina" 56 | "github.com/samalba/dockerclient" 57 | ) 58 | 59 | func connectCluster(username string, apikey string, clusterID string) { 60 | // Connect to Carina 61 | cli, _ := libcarina.NewClusterClient(libcarina.BetaEndpoint, username, apikey, "") 62 | 63 | // Download the cluster credentials 64 | creds, _ := cli.GetCredentials(clusterID) 65 | 66 | // Get the IP of the host and the TLS configuration 67 | host, _ := creds.ParseHost() 68 | cfg, _ := creds.GetTLSConfig() 69 | 70 | // Do the Dockers! 71 | docker, _ := dockerclient.NewDockerClient(host, cfg) 72 | info, _ := docker.Info() 73 | fmt.Println(info) 74 | } 75 | ``` 76 | 77 | ### Kubernetes 78 | Connect to a Kubernetes cluster 79 | 80 | ```go 81 | package main 82 | 83 | import ( 84 | "fmt" 85 | "github.com/getcarina/libcarina" 86 | 87 | client "k8s.io/kubernetes/pkg/client/unversioned" 88 | "k8s.io/kubernetes/pkg/client/restclient" 89 | "k8s.io/kubernetes/pkg/api" 90 | ) 91 | 92 | func connectCluster(username string, apikey string, clusterID string) { 93 | // Connect to Carina 94 | cli, _ := libcarina.NewClusterClient(libcarina.BetaEndpoint, username, apikey, "") 95 | 96 | // Download the cluster credentials 97 | creds, _ := cli.GetCredentials(clusterID) 98 | 99 | // K8s stuff and things! 100 | k8cfg := &restclient.Config{ 101 | Host: creds.ParseHost(), 102 | CertData: creds.Cert, 103 | CAData: creds.CA, 104 | KeyData: creds.Key, 105 | } 106 | client, err := client.New(config) 107 | pods, err := client.Pods(api.NamespaceDefault).List(api.ListOptions{}) 108 | 109 | return err 110 | } 111 | ``` 112 | -------------------------------------------------------------------------------- /cluster.go: -------------------------------------------------------------------------------- 1 | package libcarina 2 | 3 | // Cluster is a cluster of Docker nodes 4 | type Cluster struct { 5 | // ID of the cluster 6 | ID string `json:"id"` 7 | 8 | // Name of the cluster 9 | Name string `json:"name"` 10 | 11 | // Type of cluster 12 | Type *ClusterType `json:"cluster_type"` 13 | 14 | // Nodes in the cluster 15 | Nodes int `json:"node_count,omitempty"` 16 | 17 | // Status of the cluster 18 | Status string `json:"status,omitempty"` 19 | } 20 | 21 | // ClusterType defines a type of cluster 22 | // Essentially the template used to create a new cluster 23 | type ClusterType struct { 24 | // ID of the cluster type 25 | ID int `json:"id"` 26 | 27 | // Name of the cluster type 28 | Name string `json:"name"` 29 | 30 | // Specifies if the cluster type is available to be used for new clusters 31 | IsActive bool `json:"active"` 32 | 33 | // COE (container orchestration engine) used by the cluster 34 | COE string `json:"coe"` 35 | 36 | // Underlying type of the host nodes, such as lxc or vm 37 | HostType string `json:"host_type"` 38 | } 39 | 40 | // CreateClusterOpts defines the set of parameters when creating a cluster 41 | type CreateClusterOpts struct { 42 | // Name of the cluster 43 | Name string `json:"name"` 44 | 45 | // Type of cluster 46 | ClusterTypeID int `json:"cluster_type_id"` 47 | 48 | // Nodes in the cluster 49 | Nodes int `json:"node_count,omitempty"` 50 | } 51 | -------------------------------------------------------------------------------- /credentials.go: -------------------------------------------------------------------------------- 1 | package libcarina 2 | 3 | import ( 4 | "crypto/tls" 5 | "crypto/x509" 6 | "fmt" 7 | "io/ioutil" 8 | "net" 9 | "net/url" 10 | "path/filepath" 11 | "strings" 12 | "time" 13 | 14 | "github.com/pkg/errors" 15 | ) 16 | 17 | const verifyCredentialsTimeout = 2 * time.Second 18 | 19 | // CredentialsBundle is a set of certificates and environment information necessary to connect to a cluster 20 | type CredentialsBundle struct { 21 | Files map[string][]byte 22 | Err error 23 | } 24 | 25 | // NewCredentialsBundle initializes an empty credentials bundle 26 | func NewCredentialsBundle() *CredentialsBundle { 27 | return &CredentialsBundle{ 28 | Files: make(map[string][]byte), 29 | } 30 | } 31 | 32 | // LoadCredentialsBundle loads a credentials bundle from the filesystem 33 | func LoadCredentialsBundle(credentialsPath string) *CredentialsBundle { 34 | files, err := ioutil.ReadDir(credentialsPath) 35 | if err != nil { 36 | return &CredentialsBundle{ 37 | Err: errors.Wrapf(err, "Invalid credentials bundle. Cannot list files in %s", credentialsPath), 38 | } 39 | } 40 | 41 | creds := NewCredentialsBundle() 42 | for _, file := range files { 43 | filePath := filepath.Join(credentialsPath, file.Name()) 44 | fileContents, err := ioutil.ReadFile(filePath) 45 | if err != nil { 46 | creds.Err = errors.Wrapf(err, "Invalid credentials bundle. Cannot read %s", filePath) 47 | return creds 48 | } 49 | creds.Files[file.Name()] = fileContents 50 | } 51 | 52 | return creds 53 | } 54 | 55 | // GetCA returns the contents of ca.pem 56 | func (creds *CredentialsBundle) GetCA() []byte { 57 | return creds.Files["ca.pem"] 58 | } 59 | 60 | // GetCert returns the contents of cert.pem 61 | func (creds *CredentialsBundle) GetCert() []byte { 62 | return creds.Files["cert.pem"] 63 | } 64 | 65 | // GetKey returns the contents of key.pem 66 | func (creds *CredentialsBundle) GetKey() []byte { 67 | return creds.Files["key.pem"] 68 | } 69 | 70 | // Verify validates that we can connect to the Docker host specified in the credentials bundle 71 | func (creds *CredentialsBundle) Verify() error { 72 | if creds.Err != nil { 73 | return creds.Err 74 | } 75 | 76 | tlsConfig, err := creds.GetTLSConfig() 77 | if err != nil { 78 | return err 79 | } 80 | 81 | host, err := creds.ParseHost() 82 | if err != nil { 83 | return err 84 | } 85 | 86 | telephone := &net.Dialer{Timeout: verifyCredentialsTimeout} 87 | conn, err := tls.DialWithDialer(telephone, "tcp", host, tlsConfig) 88 | if err != nil { 89 | return errors.Wrapf(err, "Invalid credentials bundle. Unable to connect to %s", host) 90 | } 91 | conn.Close() 92 | 93 | return nil 94 | } 95 | 96 | // ParseHost finds the COE Endpoint, e.g. the swarm or kubernetes ip and port 97 | func (creds *CredentialsBundle) ParseHost() (string, error) { 98 | var host string 99 | var ok bool 100 | 101 | if config, isDocker := creds.Files["docker.env"]; isDocker { 102 | host, ok = parseHost(config, "DOCKER_HOST=") 103 | if !ok { 104 | return "", errors.New("Invalid credentials bundle. Could not parse DOCKER_HOST from docker.env") 105 | } 106 | } else if config, isKubernetes := creds.Files["kubectl.config"]; isKubernetes { 107 | host, ok = parseHost(config, "server:") 108 | if !ok { 109 | return "", errors.New("Invalid credentials bundle. Could not parse server from kubectl.config") 110 | } 111 | } else { 112 | return "", errors.New("Invalid credentials bundle. Missing both docker.env and kubectl.config") 113 | } 114 | 115 | hostURL, err := url.Parse(host) 116 | if err != nil { 117 | return "", fmt.Errorf("Invalid credentials bundle. Bad host URL %s", host) 118 | } 119 | 120 | // The dialer gets mad if we don't specify a port 121 | // So use the default 443 for HTTPS endpoints 122 | if !strings.Contains(hostURL.Host, ":") { 123 | if hostURL.Scheme == "https" { 124 | hostURL.Host += ":443" 125 | } else { 126 | return "", fmt.Errorf("Invalid credentials bundle. Could not determine the host port from %s", host) 127 | } 128 | } 129 | 130 | return hostURL.Host, nil 131 | } 132 | 133 | func parseHost(config []byte, token string) (string, bool) { 134 | lines := strings.Split(string(config), "\n") 135 | for _, line := range lines { 136 | host := strings.Split(line, token) 137 | if len(host) == 2 { 138 | return strings.TrimSpace(host[1]), true 139 | } 140 | } 141 | 142 | return "", false 143 | } 144 | 145 | // GetTLSConfig puts together the necessary TLS configuration to connect to the COE Endpoint returned by ParseHost 146 | func (creds *CredentialsBundle) GetTLSConfig() (*tls.Config, error) { 147 | var tlsConfig tls.Config 148 | tlsConfig.InsecureSkipVerify = true 149 | certPool := x509.NewCertPool() 150 | 151 | certPool.AppendCertsFromPEM(creds.GetCA()) 152 | tlsConfig.RootCAs = certPool 153 | keypair, err := tls.X509KeyPair(creds.GetCert(), creds.GetKey()) 154 | if err != nil { 155 | return &tlsConfig, errors.Wrap(err, "Invalid credentials bundle. Keypair mis-match") 156 | } 157 | tlsConfig.Certificates = []tls.Certificate{keypair} 158 | return &tlsConfig, nil 159 | } 160 | -------------------------------------------------------------------------------- /glide.lock: -------------------------------------------------------------------------------- 1 | hash: 66a83db7e1fcb0ee3e6856ae25a48bf1b59bf7354da2c3b2f8a4c5956057b22b 2 | updated: 2016-10-27T11:29:46.026241422-05:00 3 | imports: 4 | - name: github.com/gophercloud/gophercloud 5 | version: b267f2372f44b2479bb598d4e333804b667b80e5 6 | vcs: git 7 | subpackages: 8 | - rackspace 9 | - name: github.com/Masterminds/semver 10 | version: 8d0431362b544d1a3536cca26684828866a7de09 11 | - name: github.com/mitchellh/mapstructure 12 | version: f3009df150dadf309fdee4a54ed65c124afad715 13 | - name: github.com/pkg/errors 14 | version: 645ef00459ed84a119197bfb8d8205042c6df63d 15 | - name: github.com/rackspace/gophercloud 16 | version: e00690e87603abe613e9f02c816c7c4bef82e063 17 | subpackages: 18 | - rackspace 19 | - openstack 20 | - openstack/utils 21 | - rackspace/identity/v2/tokens 22 | - openstack/identity/v2/tokens 23 | - openstack/identity/v3/tokens 24 | - openstack/identity/v2/tenants 25 | - testhelper 26 | - testhelper/client 27 | - pagination 28 | testImports: [] 29 | -------------------------------------------------------------------------------- /glide.yaml: -------------------------------------------------------------------------------- 1 | package: github.com/getcarina/libcarina 2 | import: 3 | - package: github.com/Masterminds/semver 4 | version: ^1.1.1 5 | - package: github.com/pkg/errors 6 | version: ^0.8.0 7 | - package: github.com/gophercloud/gophercloud 8 | version: magnum 9 | vcs: git 10 | subpackages: 11 | - rackspace 12 | -------------------------------------------------------------------------------- /libcarina.go: -------------------------------------------------------------------------------- 1 | package libcarina 2 | 3 | import ( 4 | "archive/zip" 5 | "bytes" 6 | "encoding/json" 7 | "fmt" 8 | "io" 9 | "io/ioutil" 10 | "net/http" 11 | "path" 12 | "regexp" 13 | "strings" 14 | 15 | "github.com/pkg/errors" 16 | "github.com/rackspace/gophercloud" 17 | "github.com/rackspace/gophercloud/rackspace" 18 | ) 19 | 20 | // UserAgentPrefix is the default user agent string, consumers should append their application version to `CarinaClient.UserAgent`. 21 | const UserAgentPrefix = "libcarina/" + LibVersion 22 | 23 | // CarinaClient accesses Carina directly 24 | type CarinaClient struct { 25 | Client *http.Client 26 | Username string 27 | Token string 28 | Endpoint string 29 | UserAgent string 30 | } 31 | 32 | // HTTPErr is returned when API requests are not successful 33 | type HTTPErr struct { 34 | Method string 35 | URL string 36 | StatusCode int 37 | Status string 38 | Body string 39 | } 40 | 41 | // CarinaGenericErrorResponse represents the response returned by Carina when a request fails 42 | type CarinaGenericErrorResponse struct { 43 | Errors []CarinaError `json:"errors"` 44 | } 45 | 46 | // CarinaError represents an error message from the Carina API 47 | type CarinaError struct { 48 | Code string `json:"code"` 49 | Detail string `json:"detail"` 50 | RequestID string `json:"request_id"` 51 | Status int `json:"status"` 52 | Title string `json:"title"` 53 | } 54 | 55 | // CarinaUnacceptableErrorResonse represents the response returned by Carina when the StatusCode is 406 56 | type CarinaUnacceptableErrorResonse struct { 57 | Errors []CarinaUnacceptableError `json:"errors"` 58 | } 59 | 60 | // CarinaUnacceptableError represents a 406 response from the Carina API 61 | type CarinaUnacceptableError struct { 62 | CarinaError 63 | MaxVersion string `json:"max_version"` 64 | MinVersion string `json:"min_version"` 65 | } 66 | 67 | // genericError is a multi-purpose error formatter for generic errors from the Carina API 68 | func (err HTTPErr) genericError() string { 69 | var carinaResp CarinaGenericErrorResponse 70 | 71 | jsonErr := json.Unmarshal([]byte(err.Body), &carinaResp) 72 | if jsonErr != nil { 73 | return fmt.Sprintf("%s %s (%d)", err.Method, err.URL, err.StatusCode) 74 | } 75 | 76 | var errorMessages bytes.Buffer 77 | for _, carinaErr := range carinaResp.Errors { 78 | errorMessages.WriteString("\nMessage: ") 79 | errorMessages.WriteString(carinaErr.Title) 80 | errorMessages.WriteString(" - ") 81 | errorMessages.WriteString(carinaErr.Detail) 82 | } 83 | return fmt.Sprintf("%s %s (%d)%s", err.Method, err.URL, err.StatusCode, errorMessages.String()) 84 | } 85 | 86 | // unacceptableError is a error formatter for parsing a 406 response from the Carina API 87 | func (err HTTPErr) unacceptableError() string { 88 | var carinaResp CarinaUnacceptableErrorResonse 89 | 90 | jsonErr := json.Unmarshal([]byte(err.Body), &carinaResp) 91 | if jsonErr != nil { 92 | return err.genericError() 93 | } 94 | 95 | var errorMessages bytes.Buffer 96 | for _, carinaErr := range carinaResp.Errors { 97 | errorMessages.WriteString("\nMessage: ") 98 | errorMessages.WriteString(carinaErr.Title) 99 | errorMessages.WriteString(" - The client supports ") 100 | errorMessages.WriteString(SupportedAPIVersion) 101 | errorMessages.WriteString(" while the server supports ") 102 | errorMessages.WriteString(carinaErr.MinVersion) 103 | errorMessages.WriteString(" - ") 104 | errorMessages.WriteString(carinaErr.MaxVersion) 105 | errorMessages.WriteString(".") 106 | } 107 | return fmt.Sprintf("%s %s (%d)%s", err.Method, err.URL, err.StatusCode, errorMessages.String()) 108 | } 109 | 110 | // Error routes to either genericError or other, more-specific, response formatters to give provide a user-friendly error 111 | func (err HTTPErr) Error() string { 112 | switch err.StatusCode { 113 | default: 114 | return err.genericError() 115 | case 406: 116 | return err.unacceptableError() 117 | } 118 | } 119 | 120 | // NewClient create an authenticated CarinaClient 121 | func NewClient(username string, apikey string, region string, authEndpointOverride string, cachedToken string, cachedEndpoint string) (*CarinaClient, error) { 122 | authEndpoint := rackspace.RackspaceUSIdentity 123 | if authEndpointOverride != "" { 124 | authEndpoint = authEndpointOverride 125 | } 126 | 127 | verifyToken := func() error { 128 | req, err := http.NewRequest("HEAD", authEndpoint+"tokens/"+cachedToken, nil) 129 | if err != nil { 130 | return errors.WithStack(err) 131 | } 132 | 133 | req.Header.Add("Accept", "application/json") 134 | req.Header.Add("X-Auth-Token", cachedToken) 135 | req.Header.Add("User-Agent", UserAgentPrefix) 136 | 137 | httpClient := &http.Client{} 138 | resp, err := httpClient.Do(req) 139 | if err != nil { 140 | return errors.WithStack(err) 141 | } 142 | 143 | defer resp.Body.Close() 144 | 145 | if resp.StatusCode != 200 { 146 | return fmt.Errorf("Cached token is invalid") 147 | } 148 | 149 | return nil 150 | } 151 | 152 | // Attempt to authenticate with the cached token first, falling back on the apikey 153 | if cachedToken == "" || verifyToken() != nil { 154 | ao := &gophercloud.AuthOptions{ 155 | Username: username, 156 | APIKey: apikey, 157 | IdentityEndpoint: authEndpoint, 158 | } 159 | 160 | provider, err := rackspace.AuthenticatedClient(*ao) 161 | if err != nil { 162 | return nil, errors.WithStack(err) 163 | } 164 | cachedToken = provider.TokenID 165 | 166 | eo := gophercloud.EndpointOpts{Region: region} 167 | eo.ApplyDefaults(CarinaEndpointType) 168 | url, err := provider.EndpointLocator(eo) 169 | if err != nil { 170 | return nil, errors.WithStack(err) 171 | } 172 | 173 | cachedEndpoint = strings.TrimRight(url, "/") 174 | } 175 | 176 | return &CarinaClient{ 177 | Client: &http.Client{}, 178 | Username: username, 179 | Token: cachedToken, 180 | Endpoint: cachedEndpoint, 181 | UserAgent: UserAgentPrefix, 182 | }, nil 183 | } 184 | 185 | // NewRequest handles a request using auth used by Carina 186 | func (c *CarinaClient) NewRequest(method string, uri string, body io.Reader) (*http.Response, error) { 187 | req, err := http.NewRequest(method, c.Endpoint+uri, body) 188 | if err != nil { 189 | return nil, errors.WithStack(err) 190 | } 191 | 192 | req.Header.Add("Content-Type", "application/json") 193 | req.Header.Add("Accept", "application/json") 194 | req.Header.Add("X-Auth-Token", c.Token) 195 | req.Header.Set("User-Agent", c.UserAgent) 196 | req.Header.Add("API-Version", CarinaEndpointType+" "+SupportedAPIVersion) 197 | 198 | resp, err := c.Client.Do(req) 199 | if err != nil { 200 | return nil, errors.WithStack(err) 201 | } 202 | 203 | if resp.StatusCode >= 400 { 204 | err := HTTPErr{ 205 | Method: req.Method, 206 | URL: req.URL.String(), 207 | StatusCode: resp.StatusCode, 208 | Status: resp.Status, 209 | } 210 | defer resp.Body.Close() 211 | b, _ := ioutil.ReadAll(resp.Body) 212 | err.Body = string(b) 213 | return nil, errors.WithStack(err) 214 | } 215 | 216 | return resp, nil 217 | } 218 | 219 | // List the current clusters 220 | func (c *CarinaClient) List() ([]*Cluster, error) { 221 | resp, err := c.NewRequest("GET", "/clusters", nil) 222 | if err != nil { 223 | return nil, err 224 | } 225 | 226 | var result struct { 227 | Clusters []*Cluster `json:"clusters"` 228 | } 229 | defer resp.Body.Close() 230 | err = json.NewDecoder(resp.Body).Decode(&result) 231 | if err != nil { 232 | return nil, errors.WithStack(err) 233 | } 234 | 235 | return result.Clusters, nil 236 | } 237 | 238 | func clusterFromResponse(resp *http.Response, err error) (*Cluster, error) { 239 | if err != nil { 240 | return nil, errors.WithStack(err) 241 | } 242 | 243 | cluster := &Cluster{} 244 | defer resp.Body.Close() 245 | err = json.NewDecoder(resp.Body).Decode(&cluster) 246 | if err != nil { 247 | return nil, errors.WithStack(err) 248 | } 249 | return cluster, nil 250 | } 251 | 252 | func isClusterID(token string) bool { 253 | r := regexp.MustCompile("^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$") 254 | return r.MatchString(token) 255 | } 256 | 257 | func (c *CarinaClient) lookupClusterName(token string) (string, error) { 258 | if !isClusterID(token) { 259 | return token, nil 260 | } 261 | 262 | clusters, err := c.List() 263 | if err != nil { 264 | return "", err 265 | } 266 | 267 | var name string 268 | for _, cluster := range clusters { 269 | if strings.ToLower(cluster.ID) == strings.ToLower(token) { 270 | name = cluster.Name 271 | break 272 | } 273 | } 274 | 275 | if name == "" { 276 | return "", HTTPErr{ 277 | StatusCode: http.StatusNotFound, 278 | Status: "404 NOT FOUND", 279 | Body: `{"message": "Cluster "` + token + ` not found"}`} 280 | } 281 | 282 | return name, nil 283 | } 284 | 285 | func (c *CarinaClient) lookupClusterID(token string) (string, error) { 286 | if isClusterID(token) { 287 | return token, nil 288 | } 289 | 290 | clusters, err := c.List() 291 | if err != nil { 292 | return "", err 293 | } 294 | 295 | var id string 296 | for _, cluster := range clusters { 297 | if strings.ToLower(cluster.Name) == strings.ToLower(token) { 298 | if id != "" { 299 | return "", fmt.Errorf("The cluster (%s) is not unique. Retry the request using the cluster id", token) 300 | } 301 | id = cluster.ID 302 | } 303 | } 304 | 305 | if id == "" { 306 | return "", HTTPErr{ 307 | StatusCode: http.StatusNotFound, 308 | Status: "404 NOT FOUND", 309 | Body: `{"message": "Cluster "` + token + ` not found"}`} 310 | } 311 | 312 | return id, nil 313 | } 314 | 315 | // ListClusterTypes returns a list of cluster types 316 | func (c *CarinaClient) ListClusterTypes() ([]*ClusterType, error) { 317 | resp, err := c.NewRequest("GET", "/cluster_types", nil) 318 | if err != nil { 319 | return nil, err 320 | } 321 | 322 | var result struct { 323 | Types []*ClusterType `json:"cluster_types"` 324 | } 325 | defer resp.Body.Close() 326 | err = json.NewDecoder(resp.Body).Decode(&result) 327 | if err != nil { 328 | return nil, errors.WithStack(err) 329 | } 330 | 331 | return result.Types, nil 332 | } 333 | 334 | // Get a cluster by cluster by its name or id 335 | func (c *CarinaClient) Get(token string) (*Cluster, error) { 336 | id, err := c.lookupClusterID(token) 337 | if err != nil { 338 | return nil, err 339 | } 340 | 341 | uri := path.Join("/clusters", id) 342 | resp, err := c.NewRequest("GET", uri, nil) 343 | return clusterFromResponse(resp, err) 344 | } 345 | 346 | // Create a new cluster with cluster options 347 | func (c *CarinaClient) Create(clusterOpts *CreateClusterOpts) (*Cluster, error) { 348 | clusterOptsJSON, err := json.Marshal(clusterOpts) 349 | if err != nil { 350 | return nil, errors.WithStack(err) 351 | } 352 | 353 | body := bytes.NewReader(clusterOptsJSON) 354 | resp, err := c.NewRequest("POST", "/clusters", body) 355 | return clusterFromResponse(resp, err) 356 | } 357 | 358 | // Resize a cluster with resize task options 359 | func (c *CarinaClient) Resize(token string, nodes int) (*Cluster, error) { 360 | id, err := c.lookupClusterID(token) 361 | if err != nil { 362 | return nil, err 363 | } 364 | 365 | resizeOpts := newResizeOpts(nodes) 366 | resizeOptsJSON, err := json.Marshal(resizeOpts) 367 | if err != nil { 368 | return nil, errors.WithStack(err) 369 | } 370 | 371 | body := bytes.NewReader(resizeOptsJSON) 372 | uri := path.Join("/clusters", id, "tasks") 373 | resp, err := c.NewRequest("POST", uri, body) 374 | if err != nil { 375 | return nil, err 376 | } 377 | defer resp.Body.Close() 378 | 379 | return c.Get(token) 380 | } 381 | 382 | // GetCredentials returns a Credentials struct for the given cluster name 383 | func (c *CarinaClient) GetCredentials(token string) (*CredentialsBundle, error) { 384 | id, err := c.lookupClusterID(token) 385 | if err != nil { 386 | return nil, err 387 | } 388 | 389 | name, err := c.lookupClusterName(token) 390 | if err != nil { 391 | return nil, err 392 | } 393 | 394 | uri := path.Join("/clusters", id, "credentials/zip") 395 | resp, err := c.NewRequest("GET", uri, nil) 396 | if err != nil { 397 | return nil, err 398 | } 399 | 400 | // Read the body as a zip file 401 | buf := &bytes.Buffer{} 402 | _, err = io.Copy(buf, resp.Body) 403 | if err != nil { 404 | return nil, errors.WithStack(err) 405 | } 406 | 407 | b := bytes.NewReader(buf.Bytes()) 408 | zipr, err := zip.NewReader(b, int64(b.Len())) 409 | if err != nil { 410 | return nil, errors.WithStack(err) 411 | } 412 | 413 | // Fetch the contents for each file in the zipfile 414 | creds := NewCredentialsBundle() 415 | for _, zf := range zipr.File { 416 | _, fname := path.Split(zf.Name) 417 | fi := zf.FileInfo() 418 | 419 | if fi.IsDir() { 420 | // Explicitly skip past directories (the UUID directory from a previous release) 421 | continue 422 | } 423 | 424 | rc, err := zf.Open() 425 | if err != nil { 426 | return nil, errors.WithStack(err) 427 | } 428 | 429 | b, err := ioutil.ReadAll(rc) 430 | if err != nil { 431 | return nil, errors.WithStack(err) 432 | } 433 | creds.Files[fname] = b 434 | } 435 | 436 | appendClusterName(name, creds) 437 | 438 | return creds, nil 439 | } 440 | 441 | // Set the CLUSTER_NAME environment variable in the scripts 442 | func appendClusterName(name string, creds *CredentialsBundle) { 443 | addStmt := func(fileName string, stmt string) { 444 | script := creds.Files[fileName] 445 | script = append(script, []byte(stmt)...) 446 | creds.Files[fileName] = script 447 | } 448 | 449 | for fileName := range creds.Files { 450 | switch fileName { 451 | case "docker.env", "kubectl.env": 452 | addStmt(fileName, fmt.Sprintf("\nexport CARINA_CLUSTER_NAME=%s\n", name)) 453 | case "docker.fish", "kubectl.fish": 454 | addStmt(fileName, fmt.Sprintf("\nset -x CARINA_CLUSTER_NAME %s\n", name)) 455 | case "docker.ps1", "kubectl.ps1": 456 | addStmt(fileName, fmt.Sprintf("\n$env:CARINA_CLUSTER_NAME=\"%s\"\n", name)) 457 | case "docker.cmd", "kubectl.cmd": 458 | addStmt(fileName, fmt.Sprintf("\nset CARINA_CLUSTER_NAME=%s\n", name)) 459 | } 460 | } 461 | } 462 | 463 | // Delete nukes a cluster out of existence 464 | func (c *CarinaClient) Delete(token string) (*Cluster, error) { 465 | id, err := c.lookupClusterID(token) 466 | if err != nil { 467 | return nil, err 468 | } 469 | 470 | uri := path.Join("/clusters", id) 471 | resp, err := c.NewRequest("DELETE", uri, nil) 472 | return clusterFromResponse(resp, err) 473 | } 474 | -------------------------------------------------------------------------------- /libcarina_test.go: -------------------------------------------------------------------------------- 1 | package libcarina 2 | 3 | import ( 4 | "net/http" 5 | "reflect" 6 | "testing" 7 | 8 | "fmt" 9 | "github.com/pkg/errors" 10 | "net/http/httptest" 11 | ) 12 | 13 | const mockUsername = "test-user" 14 | const mockAPIKey = "1234" 15 | const mockRegion = "DFW" 16 | const mockToken = "" 17 | 18 | const microversionUnsupportedJSON = `{"errors":[{"code":"make-coe-api.microverion-unsupported","detail":"If the api-version header is sent, it must be in the format 'rax:container X.Y' where 1.0 <= X.Y <= 1.0","links":[{"href":"https://getcarina.com/docs/","rel":"help"}],"max_version":"1.0","min_version":"1.0","request_id":"620c8d81-b8f9-4bb0-952b-6d08ae42eda0","status":406,"title":"Microversion unsupported"}]}` 19 | 20 | type handler func(w http.ResponseWriter, r *http.Request) 21 | 22 | func identityHandler(w http.ResponseWriter, r *http.Request) { 23 | w.Header().Set("Content-Type", "application/json") 24 | 25 | switch r.RequestURI { 26 | case "/v2.0/tokens": 27 | fmt.Fprintln(w, `{"access":{"serviceCatalog":[{"endpoints":[{"tenantId":"963451","publicURL":"https:\/\/api.dfw.getcarina.com","region":"DFW"}],"name":"cloudContainer","type":"rax:container"}],"user":{"name":"fake-user","id":"fake-userid"},"token":{"expires":"3000-01-01T12:00:00Z","id":"fake-token","tenant":{"name":"fake-tenantname","id":"fake-tenantid"}}}}`) 28 | default: 29 | w.WriteHeader(404) 30 | fmt.Fprintln(w, "unexpected request: "+r.RequestURI) 31 | } 32 | } 33 | 34 | func microversionUnsupportedHandler(w http.ResponseWriter, r *http.Request) { 35 | w.Header().Set("Content-Type", "application/json") 36 | w.WriteHeader(406) 37 | fmt.Fprintln(w, microversionUnsupportedJSON) 38 | } 39 | 40 | func createMockCarina(h handler) (*httptest.Server, *httptest.Server) { 41 | return httptest.NewServer(http.HandlerFunc(h)), httptest.NewServer(http.HandlerFunc(identityHandler)) 42 | } 43 | 44 | func createMockCarinaClient(identity string, endpoint string) (*CarinaClient, error) { 45 | client, err := NewClient(mockUsername, mockAPIKey, mockRegion, identity, mockToken, endpoint) 46 | if err != nil { 47 | return client, err 48 | } 49 | client.Endpoint = endpoint 50 | return client, nil 51 | } 52 | 53 | func assertMicroversionUnsupportedHandled(t *testing.T, err error) { 54 | if err == nil { 55 | t.Error("expected to get error") 56 | } 57 | cause := errors.Cause(err) 58 | if httpErr, ok := cause.(HTTPErr); ok { 59 | if httpErr.StatusCode != 406 { 60 | t.Error("expected StatusCode of 406, got", httpErr.StatusCode) 61 | } 62 | } else { 63 | t.Error("expected to get HTTPErr, got", reflect.TypeOf(err)) 64 | } 65 | } 66 | 67 | func TestMicroversionUnsupportedNewRequest(t *testing.T) { 68 | mockCarina, mockIdentity := createMockCarina(microversionUnsupportedHandler) 69 | defer mockCarina.Close() 70 | defer mockIdentity.Close() 71 | 72 | carinaClient, err := createMockCarinaClient(mockIdentity.URL+"/v2.0/", mockCarina.URL) 73 | if err != nil { 74 | t.Error("wasn't able to create carinaClient pointed at mockCarina.URL with error:", err) 75 | t.FailNow() 76 | } 77 | resp, err := carinaClient.NewRequest("GET", "/clusters", nil) 78 | if resp != nil { 79 | t.Error("expected nil response, got", resp) 80 | } 81 | assertMicroversionUnsupportedHandled(t, err) 82 | } 83 | 84 | func TestMicroversionUnsupportedGet(t *testing.T) { 85 | mockCarina, mockIdentity := createMockCarina(microversionUnsupportedHandler) 86 | defer mockCarina.Close() 87 | defer mockIdentity.Close() 88 | 89 | carinaClient, err := createMockCarinaClient(mockIdentity.URL+"/v2.0/", mockCarina.URL) 90 | if err != nil { 91 | t.Error("wasn't able to create carinaClient pointed at mockCarina.URL with error:", err) 92 | t.FailNow() 93 | } 94 | resp, err := carinaClient.Get("9f18f7f9-aeb4-4c7c-91ef-e13ff94e352c") 95 | if resp != nil { 96 | t.Error("expected nil response, got", resp) 97 | } 98 | assertMicroversionUnsupportedHandled(t, err) 99 | } 100 | 101 | func TestMicroversionUnsupportedList(t *testing.T) { 102 | mockCarina, mockIdentity := createMockCarina(microversionUnsupportedHandler) 103 | defer mockCarina.Close() 104 | defer mockIdentity.Close() 105 | 106 | carinaClient, err := createMockCarinaClient(mockIdentity.URL+"/v2.0/", mockCarina.URL) 107 | if err != nil { 108 | t.Error("wasn't able to create carinaClient pointed at mockCarina.URL with error:", err) 109 | t.FailNow() 110 | } 111 | resp, err := carinaClient.List() 112 | if resp != nil { 113 | t.Error("expected nil response, got", resp) 114 | } 115 | assertMicroversionUnsupportedHandled(t, err) 116 | } 117 | 118 | func TestMicroversionUnsupportedListClusterTypes(t *testing.T) { 119 | mockCarina, mockIdentity := createMockCarina(microversionUnsupportedHandler) 120 | defer mockCarina.Close() 121 | defer mockIdentity.Close() 122 | 123 | carinaClient, err := createMockCarinaClient(mockIdentity.URL+"/v2.0/", mockCarina.URL) 124 | if err != nil { 125 | t.Error("wasn't able to create carinaClient pointed at mockCarina.URL with error:", err) 126 | t.FailNow() 127 | } 128 | resp, err := carinaClient.ListClusterTypes() 129 | if resp != nil { 130 | t.Error("expected nil response, got", resp) 131 | } 132 | assertMicroversionUnsupportedHandled(t, err) 133 | } 134 | 135 | func TestMicroversionUnsupportedCreate(t *testing.T) { 136 | mockCarina, mockIdentity := createMockCarina(microversionUnsupportedHandler) 137 | defer mockCarina.Close() 138 | defer mockIdentity.Close() 139 | 140 | carinaClient, err := createMockCarinaClient(mockIdentity.URL+"/v2.0/", mockCarina.URL) 141 | if err != nil { 142 | t.Error("wasn't able to create carinaClient pointed at mockCarina.URL with error:", err) 143 | t.FailNow() 144 | } 145 | clusterOpts := &CreateClusterOpts{ 146 | Name: "test-cluster", 147 | ClusterTypeID: 1, 148 | Nodes: 2, 149 | } 150 | resp, err := carinaClient.Create(clusterOpts) 151 | if resp != nil { 152 | t.Error("expected nil response, got", resp) 153 | } 154 | assertMicroversionUnsupportedHandled(t, err) 155 | } 156 | 157 | func TestMicroversionUnsupportedDelete(t *testing.T) { 158 | mockCarina, mockIdentity := createMockCarina(microversionUnsupportedHandler) 159 | defer mockCarina.Close() 160 | defer mockIdentity.Close() 161 | 162 | carinaClient, err := createMockCarinaClient(mockIdentity.URL+"/v2.0/", mockCarina.URL) 163 | if err != nil { 164 | t.Error("wasn't able to create carinaClient pointed at mockCarina.URL with error:", err) 165 | t.FailNow() 166 | } 167 | resp, err := carinaClient.Delete("9f18f7f9-aeb4-4c7c-91ef-e13ff94e352c") 168 | if resp != nil { 169 | t.Error("expected nil response, got", resp) 170 | } 171 | assertMicroversionUnsupportedHandled(t, err) 172 | } 173 | 174 | func TestMicroversionUnsupportedResize(t *testing.T) { 175 | mockCarina, mockIdentity := createMockCarina(microversionUnsupportedHandler) 176 | defer mockCarina.Close() 177 | defer mockIdentity.Close() 178 | 179 | carinaClient, err := createMockCarinaClient(mockIdentity.URL+"/v2.0/", mockCarina.URL) 180 | if err != nil { 181 | t.Error("wasn't able to create carinaClient pointed at mockCarina.URL with error:", err) 182 | t.FailNow() 183 | } 184 | resp, err := carinaClient.Resize("9f18f7f9-aeb4-4c7c-91ef-e13ff94e352c", 3) 185 | if resp != nil { 186 | t.Error("expected nil response, got", resp) 187 | } 188 | assertMicroversionUnsupportedHandled(t, err) 189 | } 190 | 191 | func TestMicroversionUnsupportedGetCredentials(t *testing.T) { 192 | mockCarina, mockIdentity := createMockCarina(microversionUnsupportedHandler) 193 | defer mockCarina.Close() 194 | defer mockIdentity.Close() 195 | 196 | carinaClient, err := createMockCarinaClient(mockIdentity.URL+"/v2.0/", mockCarina.URL) 197 | if err != nil { 198 | t.Error("wasn't able to create carinaClient pointed at mockCarina.URL with error:", err) 199 | t.FailNow() 200 | } 201 | resp, err := carinaClient.GetCredentials("9f18f7f9-aeb4-4c7c-91ef-e13ff94e352c") 202 | if resp != nil { 203 | t.Error("expected nil response, got", resp) 204 | } 205 | assertMicroversionUnsupportedHandled(t, err) 206 | } 207 | -------------------------------------------------------------------------------- /metadata.go: -------------------------------------------------------------------------------- 1 | package libcarina 2 | 3 | // SupportedAPIVersion is the version of the API against which this library was developed 4 | const SupportedAPIVersion = "1.0" 5 | 6 | // LibVersion is the version of this library, and should be keep synchronized with the git tag 7 | const LibVersion = "2.0.0" 8 | 9 | // CarinaEndpointType is the endpoint type in the service catalog 10 | const CarinaEndpointType = "rax:container" 11 | 12 | // APIMetadata contains information about the API 13 | type APIMetadata struct { 14 | // Versions is a list of supported API versions 15 | Versions []*APIVersion 16 | } 17 | 18 | // APIVersion defines a version of the API 19 | type APIVersion struct { 20 | ID string `json:"id"` 21 | Status string `json:"current"` 22 | Minimum string `json:"min_version"` 23 | Maximum string `json:"max_version"` 24 | } 25 | -------------------------------------------------------------------------------- /task.go: -------------------------------------------------------------------------------- 1 | package libcarina 2 | 3 | const ( 4 | resizeTaskType = "resize" 5 | ) 6 | 7 | // ResizeInput is an input params for a resize task 8 | type resizeInput struct { 9 | // Node count to resize cluster to 10 | NodeCount int `json:"node_count"` 11 | } 12 | 13 | // ResizeTaskOpts is a data structure for the resize task 14 | type resizeTaskOpts struct { 15 | Type string `json:"type"` 16 | Input *resizeInput `json:"input"` 17 | } 18 | 19 | func newResizeOpts(nodes int) *resizeTaskOpts { 20 | return &resizeTaskOpts{Type: resizeTaskType, Input: &resizeInput{NodeCount: nodes}} 21 | } 22 | --------------------------------------------------------------------------------