diff --git a/go.mod b/go.mod index 71095ea6..205f9aa2 100644 --- a/go.mod +++ b/go.mod @@ -5,12 +5,12 @@ go 1.22 require ( github.com/alexellis/go-execute/v2 v2.2.1 github.com/golang/mock v1.6.0 - github.com/inlets/cloud-provision v0.6.9 + github.com/inlets/cloud-provision v0.7.0 github.com/linode/linodego v1.27.1 github.com/morikuni/aec v1.0.0 github.com/pkg/errors v0.9.1 - github.com/sethvargo/go-password v0.3.0 - github.com/spf13/cobra v1.8.0 + github.com/sethvargo/go-password v0.3.1 + github.com/spf13/cobra v1.8.1 github.com/spf13/pflag v1.0.5 ) diff --git a/go.sum b/go.sum index e01e585e..0e5b757e 100644 --- a/go.sum +++ b/go.sum @@ -105,6 +105,7 @@ github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWH github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -262,6 +263,8 @@ github.com/inlets/cloud-provision v0.6.8 h1:UmpkcaR+6y68K7suFqhsPLLtkccVhBbggE0N github.com/inlets/cloud-provision v0.6.8/go.mod h1:zK0cG+FIZuKHyxx0PwBim5qM1AApAxmZfCExZa3VVqc= github.com/inlets/cloud-provision v0.6.9 h1:x2UUucTKNAGI69vLxggCcxuYEHFGNehOakHd2UJfKdM= github.com/inlets/cloud-provision v0.6.9/go.mod h1:VRZaOMJD/edkEfKrRtU8LGMwqhXn3eJ6i8YDdoe5jPs= +github.com/inlets/cloud-provision v0.7.0 h1:ci0OjyN+u9VE/SIuyt68yp4nn2+VOJQPnz0DA2MsEmM= +github.com/inlets/cloud-provision v0.7.0/go.mod h1:UE/q1bx3Bl0Kxxsrgn4TmpC+PiHanolR7Y8PJihVHfI= github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= @@ -370,6 +373,8 @@ github.com/sethvargo/go-password v0.2.0 h1:BTDl4CC/gjf/axHMaDQtw507ogrXLci6XRiLc github.com/sethvargo/go-password v0.2.0/go.mod h1:Ym4Mr9JXLBycr02MFuVQ/0JHidNetSgbzutTr3zsYXE= github.com/sethvargo/go-password v0.3.0 h1:OLFHZ91Z7NiNP3dnaPxLxCDXlb6TBuxFzMvv6bu+Ptw= github.com/sethvargo/go-password v0.3.0/go.mod h1:p6we8DZ0eyYXof9pon7Cqrw98N4KTaYiadDml1dUEEw= +github.com/sethvargo/go-password v0.3.1 h1:WqrLTjo7X6AcVYfC6R7GtSyuUQR9hGyAj/f1PYQZCJU= +github.com/sethvargo/go-password v0.3.1/go.mod h1:rXofC1zT54N7R8K/h1WDUdkf9BOx5OptoxrMBcrXzvs= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= @@ -379,6 +384,8 @@ github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0= github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho= +github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= +github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= diff --git a/vendor/github.com/inlets/cloud-provision/provision/civo.go b/vendor/github.com/inlets/cloud-provision/provision/civo.go deleted file mode 100644 index 4763c13f..00000000 --- a/vendor/github.com/inlets/cloud-provision/provision/civo.go +++ /dev/null @@ -1,267 +0,0 @@ -// Copyright (c) Inlets Author(s) 2019. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -package provision - -import ( - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "log" - "net/http" - "net/url" - - "strings" - "time" -) - -// CivoProvisioner creates instances on civo.com -type CivoProvisioner struct { - APIKey string -} - -// Network represents a network for civo vm instances to connect to -type Network struct { - ID string `json:"id"` - Name string `json:"name,omitempty"` - Default bool `json:"default,omitempty"` - CIDR string `json:"cidr,omitempty"` - Label string `json:"label,omitempty"` -} - -// NewCivoProvisioner with an accessKey -func NewCivoProvisioner(accessKey string) (*CivoProvisioner, error) { - return &CivoProvisioner{ - APIKey: accessKey, - }, nil -} - -// Status gets the status of the exit node -func (p *CivoProvisioner) Status(id string) (*ProvisionedHost, error) { - host := &ProvisionedHost{} - - apiURL := fmt.Sprint("https://api.civo.com/v2/instances/", id) - - req, err := http.NewRequest(http.MethodGet, apiURL, nil) - if err != nil { - return host, err - } - addAuth(req, p.APIKey) - - req.Header.Add("Accept", "application/json") - instance := createdInstance{} - - res, err := http.DefaultClient.Do(req) - if err != nil { - return host, err - } - - var body []byte - if res.Body != nil { - defer res.Body.Close() - body, _ = ioutil.ReadAll(res.Body) - } - - if res.StatusCode != http.StatusOK { - return host, fmt.Errorf("unexpected HTTP code: %d\n%q", res.StatusCode, string(body)) - } - - unmarshalErr := json.Unmarshal(body, &instance) - if unmarshalErr != nil { - return host, unmarshalErr - } - - return &ProvisionedHost{ - ID: instance.ID, - IP: instance.PublicIP, - Status: strings.ToLower(instance.Status), - }, nil -} - -// Delete terminates the exit node -func (p *CivoProvisioner) Delete(request HostDeleteRequest) error { - var id string - var err error - if len(request.ID) > 0 { - id = request.ID - } else { - id, err = p.lookupID(request) - if err != nil { - return err - } - } - - apiURL := fmt.Sprint("https://api.civo.com/v2/instances/", id) - _, err = apiCall(p.APIKey, http.MethodDelete, apiURL, nil) - if err != nil { - return err - } - return nil -} - -// Provision creates a new exit node -func (p *CivoProvisioner) Provision(host BasicHost) (*ProvisionedHost, error) { - - log.Printf("Provisioning host with Civo\n") - - if host.Region == "" { - host.Region = "lon1" - } - - res, err := provisionCivoInstance(host, p.APIKey) - - if err != nil { - return nil, err - } - - return &ProvisionedHost{ - ID: res.ID, - }, nil -} - -// List returns a list of exit nodes -func (p *CivoProvisioner) List(filter ListFilter) ([]*ProvisionedHost, error) { - var inlets []*ProvisionedHost - apiURL := fmt.Sprintf("https://api.civo.com/v2/instances/?tags=%s", filter.Filter) - body, err := apiCall(p.APIKey, http.MethodGet, apiURL, nil) - if err != nil { - return inlets, err - } - - var resp apiResponse - unmarshalErr := json.Unmarshal(body, &resp) - if unmarshalErr != nil { - return inlets, unmarshalErr - } - - for _, instance := range resp.Items { - host := &ProvisionedHost{ - IP: instance.PublicIP, - ID: instance.ID, - Status: instance.Status, - } - inlets = append(inlets, host) - } - return inlets, nil -} - -func (p *CivoProvisioner) lookupID(request HostDeleteRequest) (string, error) { - inlets, err := p.List(ListFilter{Filter: "inlets"}) - if err != nil { - return "", err - } - for _, inlet := range inlets { - if inlet.IP == request.IP { - return inlet.ID, nil - } - } - return "", fmt.Errorf("no host with ip: %s", request.IP) -} - -// gets the default network for the selected region. -func getDefaultNetwork(key, region string) (*Network, error) { - apiURL := "https://api.civo.com/v2/networks" - values := url.Values{} - values.Add("region", region) - body, err := apiCall(key, http.MethodGet, apiURL, strings.NewReader(values.Encode())) - if err != nil { - return nil, err - } - - networks := []Network{} - if err := json.Unmarshal(body, &networks); err != nil { - return nil, err - } - - for _, network := range networks { - if network.Default { - return &network, nil - } - } - return nil, errors.New("no default network found") -} - -func provisionCivoInstance(host BasicHost, key string) (createdInstance, error) { - instance := createdInstance{} - - network, err := getDefaultNetwork(key, host.Region) - if err != nil { - return instance, err - } - - apiURL := "https://api.civo.com/v2/instances" - - values := url.Values{} - values.Add("hostname", host.Name) - values.Add("size", host.Plan) - values.Add("public_ip", "create") - values.Add("template_id", host.OS) - values.Add("initial_user", "civo") - values.Add("script", host.UserData) - values.Add("region", host.Region) - values.Add("network_id", network.ID) - values.Add("tags", "inlets") - - body, err := apiCall(key, http.MethodPost, apiURL, strings.NewReader(values.Encode())) - if err != nil { - return instance, err - } - - unmarshalErr := json.Unmarshal(body, &instance) - if unmarshalErr != nil { - return instance, unmarshalErr - } - - fmt.Printf("Instance ID: %s\n", instance.ID) - return instance, nil -} - -func apiCall(key, method, url string, requestBody io.Reader) ([]byte, error) { - - req, err := http.NewRequest(method, url, requestBody) - if err != nil { - return nil, err - } - addAuth(req, key) - - req.Header.Add("Accept", "application/json") - req.Header.Add("Content-Type", "application/x-www-form-urlencoded") - - res, err := http.DefaultClient.Do(req) - if err != nil { - return nil, err - } - - var body []byte - if res.Body != nil { - defer res.Body.Close() - body, err = ioutil.ReadAll(res.Body) - if err != nil { - return nil, err - } - } - - if res.StatusCode != http.StatusOK { - return nil, fmt.Errorf("unexpected HTTP code: %d\n%q", res.StatusCode, string(body)) - } - - return body, nil -} - -type apiResponse struct { - Items []createdInstance `json:"items"` -} - -type createdInstance struct { - ID string `json:"id"` - CreatedAt time.Time `json:"created_at"` - PublicIP string `json:"public_ip"` - Status string `json:"status"` -} - -func addAuth(r *http.Request, APIKey string) { - r.Header.Add("Authorization", fmt.Sprintf("bearer %s", APIKey)) - r.Header.Add("User-Agent", "inlets") -} diff --git a/vendor/github.com/inlets/cloud-provision/provision/equinix_metal.go b/vendor/github.com/inlets/cloud-provision/provision/equinix_metal.go deleted file mode 100644 index b9ce2325..00000000 --- a/vendor/github.com/inlets/cloud-provision/provision/equinix_metal.go +++ /dev/null @@ -1,128 +0,0 @@ -package provision - -import ( - "fmt" - - "github.com/hashicorp/go-retryablehttp" - "github.com/packethost/packngo" -) - -// EquinixMetalProvisioner provisions a host to Equinix Metal -type EquinixMetalProvisioner struct { - client *packngo.Client -} - -// NewEquinixMetalProvisioner create a EquinixMetalProvisioner with an accessKey -func NewEquinixMetalProvisioner(accessKey string) (*EquinixMetalProvisioner, error) { - httpClient := retryablehttp.NewClient() - - return &EquinixMetalProvisioner{ - client: packngo.NewClientWithAuth("", accessKey, httpClient.HTTPClient), - }, nil -} - -// Status returns the IP, ID and Status of the exit node -func (p *EquinixMetalProvisioner) Status(id string) (*ProvisionedHost, error) { - device, _, err := p.client.Devices.Get(id, nil) - - if err != nil { - return nil, err - } - - state := device.State - - ip := "" - for _, network := range device.Network { - if network.Public { - ip = network.IpAddressCommon.Address - break - } - } - - return &ProvisionedHost{ - ID: device.ID, - Status: state, - IP: ip, - }, nil -} - -// Delete terminates the exit node -func (p *EquinixMetalProvisioner) Delete(request HostDeleteRequest) error { - var id string - var err error - if len(request.ID) > 0 { - id = request.ID - } else { - id, err = p.lookupID(request) - if err != nil { - return err - } - } - force := true - _, err = p.client.Devices.Delete(id, force) - return err -} - -// Provision a host -func (p *EquinixMetalProvisioner) Provision(host BasicHost) (*ProvisionedHost, error) { - if host.Region == "" { - host.Region = "am6" - } - createReq := &packngo.DeviceCreateRequest{ - Plan: host.Plan, - Facility: []string{host.Region}, - Hostname: host.Name, - ProjectID: host.Additional["project_id"], - SpotInstance: false, - OS: host.OS, - BillingCycle: "hourly", - UserData: host.UserData, - Tags: []string{"inlets"}, - NoSSHKeys: true, - } - - device, _, err := p.client.Devices.Create(createReq) - - if err != nil { - return nil, err - } - - return &ProvisionedHost{ - ID: device.ID, - }, nil -} - -// List returns a list of exit nodes -func (p *EquinixMetalProvisioner) List(filter ListFilter) ([]*ProvisionedHost, error) { - var inlets []*ProvisionedHost - devices, _, err := p.client.Devices.List(filter.ProjectID, nil) - if err != nil { - return nil, err - } - for _, device := range devices { - for _, tag := range device.Tags { - if tag == filter.Filter { - net := device.GetNetworkInfo() - host := &ProvisionedHost{ - IP: net.PublicIPv4, - ID: device.ID, - } - inlets = append(inlets, host) - } - } - } - return inlets, nil -} - -func (p *EquinixMetalProvisioner) lookupID(request HostDeleteRequest) (string, error) { - inlets, err := p.List(ListFilter{Filter: "inlets", ProjectID: request.ProjectID}) - if err != nil { - return "", err - } - for _, inlet := range inlets { - if inlet.IP == request.IP { - return inlet.ID, nil - } - } - return "", fmt.Errorf("no host with ip: %s", request.IP) -} diff --git a/vendor/github.com/packethost/packngo/.gitignore b/vendor/github.com/packethost/packngo/.gitignore deleted file mode 100644 index 7cc2daad..00000000 --- a/vendor/github.com/packethost/packngo/.gitignore +++ /dev/null @@ -1,30 +0,0 @@ -### Go template -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof -*.swp - -# IDEs -.idea**/** -.vscode diff --git a/vendor/github.com/packethost/packngo/CHANGELOG.md b/vendor/github.com/packethost/packngo/CHANGELOG.md deleted file mode 100644 index 53b6de27..00000000 --- a/vendor/github.com/packethost/packngo/CHANGELOG.md +++ /dev/null @@ -1,12 +0,0 @@ -# Changelog - -This project adheres to [Semantic -Versioning](http://semver.org/spec/v2.0.0.html). - -All notable changes to this project will be documented at -. Drafts release notes may be -used to track features that will be available in future releases. - -The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/), -breaking changes, additions, removals, and fixes should be pointed out in the -release notes. diff --git a/vendor/github.com/packethost/packngo/CONTRIBUTING.md b/vendor/github.com/packethost/packngo/CONTRIBUTING.md deleted file mode 100644 index 368e3a4a..00000000 --- a/vendor/github.com/packethost/packngo/CONTRIBUTING.md +++ /dev/null @@ -1,119 +0,0 @@ -# Contributing - -Thanks for your interest in improving this project! Before we get technical, -make sure you have reviewed the [code of conduct](code-of-conduct.md), -[Developer Certificate of Origin](DCO), and [OWNERS](OWNERS.md) files. Code will -be licensed according to [LICENSE.txt](LICENSE.txt). - -## Pull Requests - -When creating a pull request, please refer to an open issue. If there is no -issue open for the pull request you are creating, please create one. Frequently, -pull requests may be merged or closed while the underlying issue being addressed -is not fully addressed. Issues are a place to discuss the problem in need of a -solution. Pull requests are a place to discuss an implementation of one -particular answer to that problem. A pull request may not address all (or any) -of the problems expressed in the issue, so it is important to track these -separately. - -## Code Quality - -### Documentation - -All public functions and variables should include at least a short description -of the functionality they provide. Comments should be formatted according to -. - -Documentation at will be -generated from these comments. - -The documentation provided for packngo fields and functions should be at or -better than the quality provided at . -When the API documentation provides a lengthy description, a linking to the -related API documentation will benefit users. - -### Linters - -`golangci-lint` is used to verify that the style of the code remains consistent. - -Before committing, it's a good idea to run `goimports -w .`. -([goimports](https://pkg.go.dev/golang.org/x/tools/cmd/goimports?tab=doc)) and -`gofmt -w *.go`. ([gofmt](https://golang.org/cmd/gofmt/)) - -`make lint` can be used to verify style before creating a pull request. - -## Building and Testing - -The [Makefile](./Makefile) contains the targets to build, lint and test: - -```sh -make build -make lint -make test -``` - -These normally will be run in a docker image of golang. To run locally, just run -with `BUILD=local`: - -```sh -make build BUILD=local -make lint BUILD=local -make test BUILD=local -``` - -### Acceptance Tests - -If you want to run tests against the actual Equinix Metal API, you must set the -environment variable `PACKET_TEST_ACTUAL_API` to a non-empty string and set -`PACKNGO_TEST_RECORDER` to `disabled`. The device tests wait for the device -creation, so it's best to run a few in parallel. - -To run a particular test, you can do - -```sh -PACKNGO_TEST_ACTUAL_API=1 go test -v -run=TestAccDeviceBasic --timeout=2h -``` - -If you want to see HTTP requests, set the `PACKNGO_DEBUG` env var to non-empty -string, for example: - -```sh -PACKNGO_DEBUG=1 PACKNGO_TEST_ACTUAL_API=1 go test -v -run=TestAccVolumeUpdate -``` - -### Test Fixtures - -By default, `go test ./...` will skip most of the tests unless -`PACKNGO_TEST_ACTUAL_API` is non-empty. - -With the `PACKNGO_TEST_ACTUAL_API` environment variable set, tests will be run -against the Equinix Metal API, creating real infrastructure and incurring costs. - -The `PACKNGO_TEST_RECORDER` variable can be used to record and playback API -responses to test code changes without the delay and costs of making actual API -calls. When unset, `PACKNGO_TEST_RECORDER` acts as though it was set to -`disabled`. This is the default behavior. This default behavior may change in -the future once fixtures are available for all tests. - -When `PACKNGO_TEST_RECORDER` is set to `play`, tests will playback API responses -from recorded HTTP response fixtures. This is idea for refactoring and making -changes to request and response handling without introducing changes to the data -sent or received by the Equinix Metal API. - -When adding support for new end-points, recorded test sessions should be added. -Record the HTTP interactions to fixtures by setting the environment variable -`PACKNGO_TEST_RECORDER` to `record`. - -The fixtures are automatically named according to the test they were run from. -They are placed in `fixtures/`. The API token used during authentication is -automatically removed from these fixtures. Nonetheless, caution should be -exercised before committing any fixtures into the project. Account details -includes API tokens, contact, and payment details could easily be leaked by -committing fixtures that haven't been thoroughly reviewed. - -### Automation (CI/CD) - -Today, Drone tests pull requests using tests defined in -[.drone.yml](.drone.yml). - -See [RELEASE.md](RELEASE.md) for details on the release process. diff --git a/vendor/github.com/packethost/packngo/DCO b/vendor/github.com/packethost/packngo/DCO deleted file mode 100644 index 068953d4..00000000 --- a/vendor/github.com/packethost/packngo/DCO +++ /dev/null @@ -1,37 +0,0 @@ -Developer Certificate of Origin -Version 1.1 - -Copyright (C) 2004, 2006 The Linux Foundation and its contributors. -660 York Street, Suite 102, -San Francisco, CA 94110 USA - -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. - - -Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -(a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -(b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -(c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -(d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. - diff --git a/vendor/github.com/packethost/packngo/LICENSE.txt b/vendor/github.com/packethost/packngo/LICENSE.txt deleted file mode 100644 index 57c50110..00000000 --- a/vendor/github.com/packethost/packngo/LICENSE.txt +++ /dev/null @@ -1,56 +0,0 @@ -Copyright (c) 2014 The packngo AUTHORS. All rights reserved. - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -====================== -Portions of the client are based on code at: -https://github.com/google/go-github/ and -https://github.com/digitalocean/godo - -Copyright (c) 2013 The go-github AUTHORS. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/vendor/github.com/packethost/packngo/Makefile b/vendor/github.com/packethost/packngo/Makefile deleted file mode 100644 index 17c8036b..00000000 --- a/vendor/github.com/packethost/packngo/Makefile +++ /dev/null @@ -1,24 +0,0 @@ -IMG ?= golang:1.16 - -# enable go modules, disabled CGO - -GOENV ?= GO111MODULE=on CGO_ENABLED=0 -export GO111MODULE=on -export CGO_ENABLED=0 - -# we build in a docker image, unless we are set to BUILD=local -GO ?= docker run --rm -v $(PWD):/app -w /app $(IMG) env $(GOENV) -ifeq ($(BUILD),local) -GO = -endif - - -build: - $(GO) go build -i -v ./... - -lint: - @docker run --rm -v $(CURDIR):/app -w /app golangci/golangci-lint:v1.34.1 golangci-lint run -v - -test: - $(GO) test ./... - diff --git a/vendor/github.com/packethost/packngo/OWNERS.md b/vendor/github.com/packethost/packngo/OWNERS.md deleted file mode 100644 index ffc1a7b3..00000000 --- a/vendor/github.com/packethost/packngo/OWNERS.md +++ /dev/null @@ -1,24 +0,0 @@ -# Owners - -This project is governed by [Equinix Metal] and benefits from a community of users that -collaborate and contribute to its use in Go powered projects, such as the [Equinix -Terraform provider], the [Docker machine driver], the Kubernetes [CCM], -the [Equinix Metal CLI], and others. - -Members of the Equinix Metal Github organization will strive to triage issues in a -timely manner, see [SUPPORT.md] for details. - -See the [Equinix Labs Glossary] for more details about this file. - -## Maintainers - -Maintainers of this repository are defined within the [CODEOWNERS] file. - -[Equinix Metal]: https://metal.equinix.com -[Equinix Terraform provider]: https://github.com/equinix/terraform-provider-equinix -[Docker machine driver]: https://github.com/equinix/docker-machine-driver-metal -[CCM]: https://github.com/equinix/cloud-provider-equinix-metal -[Equinix Metal CLI]: https://github.com/equinix/metal-cli -[SUPPORT.md]: SUPPORT.md -[Equinix Labs Glossary]: https://github.com/equinix-labs/equinix-labs/blob/main/glossary.md#ownersmd -[CODEOWNERS]: CODEOWNERS diff --git a/vendor/github.com/packethost/packngo/README.md b/vendor/github.com/packethost/packngo/README.md deleted file mode 100644 index 54f4d704..00000000 --- a/vendor/github.com/packethost/packngo/README.md +++ /dev/null @@ -1,155 +0,0 @@ -# packngo - -[![Deprecated](https://img.shields.io/badge/Stability-Deprecated-red.svg)](https://github.com/equinix-labs/equinix-labs/blob/main/uniform-standards.md) -[![Release](https://img.shields.io/github/v/release/packethost/packngo)](https://github.com/packethost/packngo/releases/latest) -[![GoDoc](https://godoc.org/github.com/packethost/packngo?status.svg)](https://godoc.org/github.com/packethost/packngo) -[![Go Report Card](https://goreportcard.com/badge/github.com/packethost/packngo)](https://goreportcard.com/report/github.com/packethost/packngo) -[![Slack](https://slack.equinixmetal.com/badge.svg)](https://slack.equinixmetal.com/) -[![Twitter Follow](https://img.shields.io/twitter/follow/equinixmetal.svg?style=social&label=Follow)](https://twitter.com/intent/follow?screen_name=equinixmetal) - -> **[Deprecated](https://github.com/equinix-labs/equinix-labs/blob/main/deprecated-statement.md)** This repository is Deprecated, meaning that this software is only supported or maintained by Equinix Metal and its community in a case-by-case basis. It has been replaced by [`equinix-sdk-go`](https://github.com/equinix/equinix-sdk-go), which is generated from Equinix OpenAPI specs and is intended to support Equinix services beyond only Metal. - -A Golang client for the Equinix Metal API. ([Packet is now Equinix Metal](https://blog.equinix.com/blog/2020/10/06/equinix-metal-metal-and-more/)) - -## Installation - -To import this library into your Go project: - -```go -import "github.com/packethost/packngo" -``` - -**Note:** A minimum of Go 1.14 is required for development. - -Download module with: - -```sh -go get github.com/packethost/packngo -``` - -## Stability and Compatibility - -This repository is [Maintained](https://github.com/equinix-labs/equinix-labs/blob/main/maintained-statement.md) meaning that this software is supported by Equinix Metal and its community - available to use in production environments. - -Packngo is currently provided with a major version of [v0](https://blog.golang.org/v2-go-modules). We'll try to avoid breaking changes to this library, but they will certainly happen as we work towards a stable v1 library. See [CHANGELOG.md](CHANGELOG.md) for details on the latest additions, removals, fixes, and breaking changes. - -While packngo provides an interface to most of the [Equinix Metal API](https://metal.equinix.com/developers/api/), the API is regularly adding new features. To request or contribute support for more API end-points or added fields, [create an issue](https://github.com/packethost/packngo/issues/new). - -See [SUPPORT.md](SUPPORT.md) for any other issues. - -## Usage - -To authenticate to the Equinix Metal API, you must have your API token exported in env var `PACKET_AUTH_TOKEN`. - -This code snippet initializes Equinix Metal API client, and lists your Projects: - -```go -package main - -import ( - "log" - - "github.com/packethost/packngo" -) - -func main() { - c, err := packngo.NewClient() - if err != nil { - log.Fatal(err) - } - - ps, _, err := c.Projects.List(nil) - if err != nil { - log.Fatal(err) - } - for _, p := range ps { - log.Println(p.ID, p.Name) - } -} - -``` - -This library is used by the official [terraform-provider-equinix](https://github.com/equinix/terraform-provider-equinix). - -You can also learn a lot from the `*_test.go` sources. Almost all out tests touch the Equinix Metal API, so you can see how auth, querying and POSTing works. For example [devices_test.go](devices_test.go). - -
-Linked Resources - -### Linked resources in Get\* and List\* functions - -The Equinix Metal API includes references to related entities for a wide selection of resource types, indicated by `href` fields. The Equinix Metal API allows for these entities to be included in the API response, saving the user from making more round-trip API requests. This is useful for linked resources, e.g members of a project, devices in a project. Similarly, by excluding entities that are included by default, you can reduce the API response time and payload size. - -Control of this behavior is provided through [common attributes](https://metal.equinix.com/developers/api/common-parameters/) that can be used to toggle, by field name, which referenced resources will be included as values in API responses. The API exposes this feature through `?include=` and `?exclude=` query parameters which accept a comma-separated list of field names. These field names can be dotted to reference nested entities. - -Most of the packngo `Get` functions take references to `GetOptions` parameters (or `ListOptions` for `List` functions). These types include an `Include` and `Exclude` slice that will be converted to query parameters upon request. - -For example, if you want to list users in a project, you can fetch the project via `Projects.Get(pid, nil)` call. The result of this call will be a `Project` which has a `Users []User` attribute. The items in the `[]User` slice only have a non-zero URL attribute, the rest of the fields will be type defaults. You can then parse the ID of the User resources and fetch them consequently. - -Optionally, you can use the ListOptions struct in the project fetch call to include the Users (`members` JSON tag). Then, every item in the `[]User` slice will have all (not only the `Href`) attributes populated. - -```go -Projects.Get(pid, &packngo.ListOptions{Includes: []{'members'}}) -``` - -The following is a more comprehensive illustration of Includes and Excludes. - -```go -import ( - "log" - - "github.com/packethost/packngo" -) - -func listProjectsAndUsers(lo *packngo.ListOptions) { - c, err := packngo.NewClient() - if err != nil { - log.Fatal(err) - } - - ps, _, err := c.Projects.List(lo) - if err != nil { - log.Fatal(err) - } - log.Printf("Listing for listOptions %+v\n", lo) - for _, p := range ps { - log.Printf("project resource %s has %d users", p.Name, len(p.Users)) - for _, u := range p.Users { - if u.Email != "" && u.FullName != "" { - log.Printf(" user %s has email %s\n", u.FullName, u.Email) - } else { - log.Printf(" only got user link %s\n", u.URL) - } - } - } -} - -func main() { - loMembers := &packngo.ListOptions{Includes: []string{"members"}} - loMembersOut := &packngo.ListOptions{Excludes: []string{"members"}} - listProjectsAndUsers(loMembers) - listProjectsAndUsers(nil) - listProjectsAndUsers(loMembersOut) -} -``` - -
- -### Deprecation and Sunset - -If the Equinix Metal API returns a [RFC-8594](https://tools.ietf.org/html/rfc8594) `Deprecation` or `Sunset` header, packngo will log this header to stderr with any accompanied `Link` headers. - -Example: - -```console -WARNING: "POST /deprecate-and-sunset" reported deprecation -WARNING: "POST /deprecate-and-sunset" reported sunsetting on Sat, 1 Aug 2020 23:59:59 GMT -WARNING: See for deprecation details -WARNING: See for sunset details -WARNING: See for sunset details -WARNING: See for deprecation details -``` - -## Contributing - -See [CONTIBUTING.md](CONTRIBUTING.md). diff --git a/vendor/github.com/packethost/packngo/RELEASE.md b/vendor/github.com/packethost/packngo/RELEASE.md deleted file mode 100644 index 74a9ac2d..00000000 --- a/vendor/github.com/packethost/packngo/RELEASE.md +++ /dev/null @@ -1,40 +0,0 @@ -# Releases - -This file serves to provide guidance and act as a checklist for any maintainers -to this project, now or in the future. This file should be updated with any -changes to the process. Automated processes should be described well enough that -they can be run in the absence of that automation. - -* See [CHANGELOG.md](CHANGELOG.md) for notes on versioning. -* Fetch the latest origin branches: - - ```sh - git fetch origin - git checkout master - git pull - ``` - -* Verify that your branch matches the upstream branch: - - ```sh - git branch --points-at=master -r | grep origin/master >/dev/null || echo "master differs from origin/master" - ``` - -* Tag `master` with a semver tag that suits the level of changes - introduced: - - ```sh - git tag -m "v0.8.0" -a v0.8.0 master # use -s if gpg is available - ``` -* Push the tag: - - ```sh - git push --tags origin master v0.8.0 - ``` -* Create a release from the tag (include a keepachangelog.com formatted description): - - (use the correct - version) - -Releases can be followed through the GitHub Atom feed at -. diff --git a/vendor/github.com/packethost/packngo/SUPPORT.md b/vendor/github.com/packethost/packngo/SUPPORT.md deleted file mode 100644 index 86f8401f..00000000 --- a/vendor/github.com/packethost/packngo/SUPPORT.md +++ /dev/null @@ -1,17 +0,0 @@ -# Support - -Please [open a GitHub Issue] stating any problems that you encounter using this -software. Be sure to leave a descriptive report of the problem, including the -environment you were running in and the expected behavior. Be careful not to -include any sensitive information such as API Keys, IP addresses or their -ranges, or any resource identifiers (UUID or ID) of your organizations, -projects, or devices. - -As an open-source project, the priority, timing, or eventual resolution is not -guaranteed. Issues will be addressed based on priorities that may or may not -be reflected in Github or issue comments. - -For other forms of support, including our Slack community, visit -. - -[open a GitHub Issue]: https://github.com/packethost/packngo/issues/new \ No newline at end of file diff --git a/vendor/github.com/packethost/packngo/api_call_options.go b/vendor/github.com/packethost/packngo/api_call_options.go deleted file mode 100644 index c1b4db70..00000000 --- a/vendor/github.com/packethost/packngo/api_call_options.go +++ /dev/null @@ -1,222 +0,0 @@ -package packngo - -import ( - "fmt" - "net/url" - "strconv" - "strings" -) - -type ListSortDirection string - -const ( - SortDirectionAsc ListSortDirection = "asc" - SortDirectionDesc ListSortDirection = "desc" -) - -// GetOptions are options common to Equinix Metal API GET requests -type GetOptions struct { - // Includes are a list of fields to expand in the request results. - // - // For resources that contain collections of other resources, the Equinix Metal API - // will only return the `Href` value of these resources by default. In - // nested API Go types, this will result in objects that have zero values in - // all fiends except their `Href` field. When an object's associated field - // name is "included", the returned fields will be Uumarshalled into the - // nested object. Field specifiers can use a dotted notation up to three - // references deep. (For example, "memberships.projects" can be used in - // ListUsers.) - Includes []string `url:"include,omitempty,comma"` - - // Excludes reduce the size of the API response by removing nested objects - // that may be returned. - // - // The default behavior of the Equinix Metal API is to "exclude" fields, but some - // API endpoints have an "include" behavior on certain fields. Nested Go - // types unmarshalled into an "excluded" field will only have a values in - // their `Href` field. - Excludes []string `url:"exclude,omitempty,comma"` - - // QueryParams for API URL, used for arbitrary filters - QueryParams map[string]string `url:"-"` - - // Page is the page of results to retrieve for paginated result sets - Page int `url:"page,omitempty"` - - // PerPage is the number of results to return per page for paginated result - // sets, - PerPage int `url:"per_page,omitempty"` - - // Search is a special API query parameter that, for resources that support - // it, will filter results to those with any one of various fields matching - // the supplied keyword. For example, a resource may have a defined search - // behavior matches either a name or a fingerprint field, while another - // resource may match entirely different fields. Search is currently - // implemented for SSHKeys and uses an exact match. - Search string `url:"search,omitempty"` - - SortBy string `url:"sort_by,omitempty"` - SortDirection ListSortDirection `url:"sort_direction,omitempty"` - - Meta meta `url:"-"` -} - -type ListOptions = GetOptions -type SearchOptions = GetOptions - -type QueryAppender interface { - WithQuery(path string) string // we use this in all List functions (urlQuery) - GetPage() int // we use this in List - Including(...string) // we use this in Device List to add facility - Excluding(...string) -} - -// GetOptions returns GetOptions from GetOptions (and is nil-receiver safe) -func (g *GetOptions) GetOptions() *GetOptions { - getOpts := GetOptions{} - if g != nil { - getOpts.Includes = g.Includes - getOpts.Excludes = g.Excludes - } - return &getOpts -} - -func (g *GetOptions) WithQuery(apiPath string) string { - params := g.Encode() - if params != "" { - // parse path, take existing vars - return fmt.Sprintf("%s?%s", apiPath, params) - } - return apiPath -} - -// OptionsGetter provides GetOptions -type OptionsGetter interface { - GetOptions() *GetOptions -} - -func (g *GetOptions) GetPage() int { // guaranteed int - if g == nil { - return 0 - } - return g.Page -} - -func (g *GetOptions) CopyOrNew() *GetOptions { - if g == nil { - return &GetOptions{} - } - ret := *g - return &ret -} - -func (g *GetOptions) Filter(key, value string) *GetOptions { - return g.AddParam(key, value) -} - -// AddParam adds key=value to URL path -func (g *GetOptions) AddParam(key, value string) *GetOptions { - ret := g.CopyOrNew() - if ret.QueryParams == nil { - ret.QueryParams = map[string]string{} - } - ret.QueryParams[key] = value - return ret -} - -// Including ensures that the variadic refs are included in a copy of the -// options, resulting in expansion of the the referred sub-resources. Unknown -// values within refs will be silently ignore by the API. -func (g *GetOptions) Including(refs ...string) *GetOptions { - ret := g.CopyOrNew() - for _, v := range refs { - if !contains(ret.Includes, v) { - ret.Includes = append(ret.Includes, v) - } - } - return ret -} - -// Excluding ensures that the variadic refs are included in the "Excluded" param -// in a copy of the options. -// Unknown values within refs will be silently ignore by the API. -func (g *GetOptions) Excluding(refs ...string) *GetOptions { - ret := g.CopyOrNew() - for _, v := range refs { - if !contains(ret.Excludes, v) { - ret.Excludes = append(ret.Excludes, v) - } - } - return ret -} - -func stripQuery(inURL string) string { - u, _ := url.Parse(inURL) - u.RawQuery = "" - return u.String() -} - -// nextPage is common and extracted from all List functions -func nextPage(meta meta, opts *GetOptions) (path string) { - if meta.Next != nil && (opts.GetPage() == 0) { - optsCopy := opts.CopyOrNew() - optsCopy.Page = meta.CurrentPageNum + 1 - return optsCopy.WithQuery(stripQuery(meta.Next.Href)) - } - if opts != nil { - opts.Meta = meta - } - return "" -} - -const ( - IncludeParam = "include" - ExcludeParam = "exclude" - PageParam = "page" - PerPageParam = "per_page" - SearchParam = "search" - SortByParam = "sort_by" - SortDirectionParam = "sort_direction" -) - -// Encode generates a URL query string ("?foo=bar") -func (g *GetOptions) Encode() string { - if g == nil { - return "" - } - v := url.Values{} - for k, val := range g.QueryParams { - v.Add(k, val) - } - // the names parameters will rewrite arbitrary options - if g.Includes != nil && len(g.Includes) > 0 { - v.Add(IncludeParam, strings.Join(g.Includes, ",")) - } - if g.Excludes != nil && len(g.Excludes) > 0 { - v.Add(ExcludeParam, strings.Join(g.Excludes, ",")) - } - if g.Page != 0 { - v.Add(PageParam, strconv.Itoa(g.Page)) - } - if g.PerPage != 0 { - v.Add(PerPageParam, strconv.Itoa(g.PerPage)) - } - if g.Search != "" { - v.Add(SearchParam, g.Search) - } - if g.SortBy != "" { - v.Add(SortByParam, g.SortBy) - } - if g.SortDirection != "" { - v.Add(SortDirectionParam, string(g.SortDirection)) - } - return v.Encode() -} - -/* -// Encode generates a URL query string ("?foo=bar") -func (g *GetOptions) Encode() string { - urlValues, _ := query.Values(g) - return urlValues.Encode() -} -*/ diff --git a/vendor/github.com/packethost/packngo/apikeys.go b/vendor/github.com/packethost/packngo/apikeys.go deleted file mode 100644 index 6aa0bfc6..00000000 --- a/vendor/github.com/packethost/packngo/apikeys.go +++ /dev/null @@ -1,191 +0,0 @@ -package packngo - -import ( - "fmt" - "path" -) - -const ( - apiKeyBasePath = "/api-keys" -) - -// APIKeyService interface defines available device methods -type APIKeyService interface { - UserList(*ListOptions) ([]APIKey, *Response, error) - ProjectList(string, *ListOptions) ([]APIKey, *Response, error) - UserGet(string, *GetOptions) (*APIKey, error) - ProjectGet(string, string, *GetOptions) (*APIKey, error) - Create(*APIKeyCreateRequest) (*APIKey, *Response, error) - Delete(string) (*Response, error) -} - -type apiKeyRoot struct { - APIKeys []APIKey `json:"api_keys"` -} - -type APIKey struct { - // ID is the UUIDv4 representing an API key in API requests and responses. - ID string `json:"id"` - - // Description is any text description of the key. This can be used to - // describe the purpose of the key. - Description string `json:"description"` - - // Token is a sensitive credential that can be used as a `Client.APIKey` to - // access Equinix Metal resources. - Token string `json:"token"` - - // ReadOnly keys can not create new resources. - ReadOnly bool `json:"read_only"` - - // Created is the creation date of the API key. - Created string `json:"created_at"` - - // Updated is the last-update date of the API key. - Updated string `json:"updated_at"` - - // User will be non-nil when getting or listing an User API key. - User *User `json:"user"` - - // Project will be non-nil when getting or listing a Project API key - Project *Project `json:"project"` -} - -// APIKeyCreateRequest type used to create an api key. -type APIKeyCreateRequest struct { - // Description is any text description of the key. This can be used to - // describe the purpose of the key. - Description string `json:"description"` - - // ReadOnly keys can not create new resources. - ReadOnly bool `json:"read_only"` - - // ProjectID when non-empty will result in the creation of a Project API - // key. - ProjectID string `json:"-"` -} - -func (s APIKeyCreateRequest) String() string { - return Stringify(s) -} - -// APIKeyServiceOp implements APIKeyService -type APIKeyServiceOp struct { - client *Client -} - -func (s *APIKeyServiceOp) list(url string, opts *ListOptions) ([]APIKey, *Response, error) { - root := new(apiKeyRoot) - apiPathQuery := opts.WithQuery(url) - - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, root) - if err != nil { - return nil, resp, err - } - - return root.APIKeys, resp, err -} - -// ProjectList lists the API keys associated with a project having `projectID` -// match `Project.ID`. -func (s *APIKeyServiceOp) ProjectList(projectID string, opts *ListOptions) ([]APIKey, *Response, error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(projectBasePath, projectID, apiKeyBasePath) - return s.list(endpointPath, opts) -} - -// UserList returns the API keys for the User associated with the -// `Client.APIKey`. -// -// When `Client.APIKey` is a Project API key, this method will return an access -// denied error. -func (s *APIKeyServiceOp) UserList(opts *ListOptions) ([]APIKey, *Response, error) { - endpointPath := path.Join(userBasePath, apiKeyBasePath) - return s.list(endpointPath, opts) -} - -// ProjectGet returns the Project API key with the given `APIKey.ID`. -// -// In other methods, it is typical for a Response to be returned, which could -// include a StatusCode of `http.StatusNotFound` (404 error) when the resource -// was not found. The Equinix Metal API does not expose a get by ID endpoint for -// APIKeys. That is why in this method, all API keys are listed and compared -// for a match. Therefor, the Response is not returned and a custom error will -// be returned when the key is not found. -func (s *APIKeyServiceOp) ProjectGet(projectID, apiKeyID string, opts *GetOptions) (*APIKey, error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, validateErr - } - if validateErr := ValidateUUID(apiKeyID); validateErr != nil { - return nil, validateErr - } - pkeys, _, err := s.ProjectList(projectID, opts) - if err != nil { - return nil, err - } - for _, k := range pkeys { - if k.ID == apiKeyID { - return &k, nil - } - } - return nil, fmt.Errorf("Project (%s) API key %s not found", projectID, apiKeyID) -} - -// UserGet returns the User API key with the given `APIKey.ID`. -// -// In other methods, it is typical for a Response to be returned, which could -// include a StatusCode of `http.StatusNotFound` (404 error) when the resource -// was not found. The Equinix Metal API does not expose a get by ID endpoint for -// APIKeys. That is why in this method, all API keys are listed and compared -// for a match. Therefor, the Response is not returned and a custom error will -// be returned when the key is not found. -func (s *APIKeyServiceOp) UserGet(apiKeyID string, opts *GetOptions) (*APIKey, error) { - if validateErr := ValidateUUID(apiKeyID); validateErr != nil { - return nil, validateErr - } - ukeys, _, err := s.UserList(opts) - if err != nil { - return nil, err - } - for _, k := range ukeys { - if k.ID == apiKeyID { - return &k, nil - } - } - return nil, fmt.Errorf("User API key %s not found", apiKeyID) -} - -// Create creates a new API key. -// -// The API key can be either an User API key or a Project API key, determined by -// the value (or emptiness) of `APIKeyCreateRequest.ProjectID`. Either `User` or -// `Project` will be non-nil in the `APIKey` depending on this factor. -func (s *APIKeyServiceOp) Create(createRequest *APIKeyCreateRequest) (*APIKey, *Response, error) { - apiPath := path.Join(userBasePath, apiKeyBasePath) - if createRequest.ProjectID != "" { - apiPath = path.Join(projectBasePath, createRequest.ProjectID, apiKeyBasePath) - } - apiKey := new(APIKey) - - resp, err := s.client.DoRequest("POST", apiPath, createRequest, apiKey) - if err != nil { - return nil, resp, err - } - - return apiKey, resp, err -} - -// Delete deletes an API key by `APIKey.ID` -// -// The API key can be either an User API key or a Project API key. -// -// Project API keys can not be used to delete themselves. -func (s *APIKeyServiceOp) Delete(apiKeyID string) (*Response, error) { - if validateErr := ValidateUUID(apiKeyID); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(userBasePath, apiKeyBasePath, apiKeyID) - return s.client.DoRequest("DELETE", apiPath, nil, nil) -} diff --git a/vendor/github.com/packethost/packngo/batches.go b/vendor/github.com/packethost/packngo/batches.go deleted file mode 100644 index b660f549..00000000 --- a/vendor/github.com/packethost/packngo/batches.go +++ /dev/null @@ -1,118 +0,0 @@ -package packngo - -import ( - "fmt" - "path" -) - -const batchBasePath = "/batches" - -// BatchService interface defines available batch methods -type BatchService interface { - Get(batchID string, getOpt *GetOptions) (*Batch, *Response, error) - List(ProjectID string, listOpt *ListOptions) ([]Batch, *Response, error) - Create(projectID string, batches *BatchCreateRequest) ([]Batch, *Response, error) - Delete(string, bool) (*Response, error) -} - -// Batch type -type Batch struct { - ID string `json:"id"` - ErrorMessages []string `json:"error_messages,omitempty"` - - // State may be 'failed' or 'completed' - State string `json:"state,omitempty"` - Quantity int32 `json:"quantity,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - Href string `json:"href,omitempty"` - Project Href `json:"project,omitempty"` - Devices []Device `json:"devices,omitempty"` -} - -//BatchesList represents collection of batches -type batchesList struct { - Batches []Batch `json:"batches,omitempty"` -} - -// BatchCreateRequest type used to create batch of device instances -type BatchCreateRequest struct { - Batches []BatchCreateDevice `json:"batches"` -} - -// BatchCreateDevice type used to describe batch instances -type BatchCreateDevice struct { - DeviceCreateRequest - Quantity int32 `json:"quantity"` - FacilityDiversityLevel int32 `json:"facility_diversity_level,omitempty"` - SpotInstance bool `json:"spot_instance,omitempty"` - SpotPriceMax float64 `json:"spot_price_max,omitempty"` -} - -// BatchServiceOp implements BatchService -type BatchServiceOp struct { - client *Client -} - -// Get returns batch details -func (s *BatchServiceOp) Get(batchID string, opts *GetOptions) (*Batch, *Response, error) { - if validateErr := ValidateUUID(batchID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(batchBasePath, batchID) - apiPathQuery := opts.WithQuery(endpointPath) - batch := new(Batch) - - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, batch) - if err != nil { - return nil, resp, err - } - - return batch, resp, err -} - -// List returns batches on a project -func (s *BatchServiceOp) List(projectID string, opts *ListOptions) (batches []Batch, resp *Response, err error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(projectBasePath, projectID, batchBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - subset := new(batchesList) - resp, err = s.client.DoRequest("GET", apiPathQuery, nil, subset) - if err != nil { - return nil, resp, err - } - - batches = append(batches, subset.Batches...) - return batches, resp, err -} - -// Create function to create batch of device instances -func (s *BatchServiceOp) Create(projectID string, request *BatchCreateRequest) ([]Batch, *Response, error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(projectBasePath, projectID, "devices", "batch") - - batches := new(batchesList) - resp, err := s.client.DoRequest("POST", apiPath, request, batches) - - if err != nil { - return nil, resp, err - } - - return batches.Batches, resp, err -} - -// Delete function to remove an instance batch -func (s *BatchServiceOp) Delete(id string, removeDevices bool) (*Response, error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, validateErr - } - // API doc days the remove_associated_instances params shout be in the body - // https://metal.equinix.com/developers/api/batches/#delete-the-batch - // .. does this even work? - apiPath := fmt.Sprintf("%s/%s?remove_associated_instances=%t", batchBasePath, id, removeDevices) - - return s.client.DoRequest("DELETE", apiPath, nil, nil) -} diff --git a/vendor/github.com/packethost/packngo/bgp_configs.go b/vendor/github.com/packethost/packngo/bgp_configs.go deleted file mode 100644 index c6929b51..00000000 --- a/vendor/github.com/packethost/packngo/bgp_configs.go +++ /dev/null @@ -1,94 +0,0 @@ -package packngo - -import ( - "path" -) - -var ( - bgpConfigPostBasePath = "/bgp-configs" - bgpConfigGetBasePath = "/bgp-config" -) - -// BGPConfigService interface defines available BGP config methods -type BGPConfigService interface { - Get(projectID string, getOpt *GetOptions) (*BGPConfig, *Response, error) - Create(projectID string, request CreateBGPConfigRequest) (*Response, error) - // Delete(configID string) (resp *Response, err error) TODO: Not in Equinix Metal API -} - -// BGPConfigServiceOp implements BgpConfigService -type BGPConfigServiceOp struct { - client *Client -} - -// CreateBGPConfigRequest struct -type CreateBGPConfigRequest struct { - DeploymentType string `json:"deployment_type,omitempty"` - Asn int `json:"asn,omitempty"` - Md5 string `json:"md5,omitempty"` - UseCase string `json:"use_case,omitempty"` -} - -// BGPConfig represents an Equinix Metal BGP Config -type BGPConfig struct { - ID string `json:"id,omitempty"` - Status string `json:"status,omitempty"` - DeploymentType string `json:"deployment_type,omitempty"` - Asn int `json:"asn,omitempty"` - RouteObject string `json:"route_object,omitempty"` - Md5 string `json:"md5,omitempty"` - MaxPrefix int `json:"max_prefix,omitempty"` - Project Project `json:"project,omitempty"` - CreatedAt Timestamp `json:"created_at,omitempty"` - RequestedAt Timestamp `json:"requested_at,omitempty"` - Sessions []BGPSession `json:"sessions,omitempty"` - Href string `json:"href,omitempty"` -} - -// Create function -func (s *BGPConfigServiceOp) Create(projectID string, request CreateBGPConfigRequest) (*Response, error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(projectBasePath, projectID, bgpConfigPostBasePath) - - resp, err := s.client.DoRequest("POST", apiPath, request, nil) - if err != nil { - return resp, err - } - - return resp, err -} - -// Get function -func (s *BGPConfigServiceOp) Get(projectID string, opts *GetOptions) (bgpConfig *BGPConfig, resp *Response, err error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(projectBasePath, projectID, bgpConfigGetBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - - subset := new(BGPConfig) - - resp, err = s.client.DoRequest("GET", apiPathQuery, nil, subset) - if err != nil { - return nil, resp, err - } - - return subset, resp, err -} - -// Delete function TODO: this is not implemented in the Equinix Metal API -// func (s *BGPConfigServiceOp) Delete(configID string) (resp *Response, err error) { -// if validateErr := ValidateUUID(configID); validateErr != nil { -// return nil, validateErr -// } -// apiPath := fmt.Sprintf("%ss/%s", bgpConfigBasePath, configID) - -// resp, err = s.client.DoRequest("DELETE", apiPath, nil, nil) -// if err != nil { -// return resp, err -// } - -// return resp, err -// } diff --git a/vendor/github.com/packethost/packngo/bgp_sessions.go b/vendor/github.com/packethost/packngo/bgp_sessions.go deleted file mode 100644 index 69be6d34..00000000 --- a/vendor/github.com/packethost/packngo/bgp_sessions.go +++ /dev/null @@ -1,131 +0,0 @@ -package packngo - -import ( - "path" -) - -var bgpSessionBasePath = "/bgp/sessions" -var bgpNeighborsBasePath = "/bgp/neighbors" -var bgpDiscoverBasePath = "/bgp/discover" - -// BGPSessionService interface defines available BGP session methods -type BGPSessionService interface { - Get(string, *GetOptions) (*BGPSession, *Response, error) - Create(string, CreateBGPSessionRequest) (*BGPSession, *Response, error) - Update(string, UpdateBGPSessionRequest) (*BGPSession, *Response, error) - Delete(string) (*Response, error) -} - -type bgpSessionsRoot struct { - Sessions []BGPSession `json:"bgp_sessions"` - Meta meta `json:"meta"` -} - -// BGPSessionServiceOp implements BgpSessionService -type BGPSessionServiceOp struct { - client *Client -} - -// BGPSession represents an Equinix Metal BGP Session -type BGPSession struct { - ID string `json:"id,omitempty"` - Status string `json:"status,omitempty"` - LearnedRoutes []string `json:"learned_routes,omitempty"` - AddressFamily string `json:"address_family,omitempty"` - Device Device `json:"device,omitempty"` - Href string `json:"href,omitempty"` - DefaultRoute *bool `json:"default_route,omitempty"` -} - -type bgpNeighborsRoot struct { - BGPNeighbors []BGPNeighbor `json:"bgp_neighbors"` -} - -// BGPNeighor is struct for listing BGP neighbors of a device -type BGPNeighbor struct { - AddressFamily int `json:"address_family"` - CustomerAs int `json:"customer_as"` - CustomerIP string `json:"customer_ip"` - Md5Enabled bool `json:"md5_enabled"` - Md5Password string `json:"md5_password"` - Multihop bool `json:"multihop"` - PeerAs int `json:"peer_as"` - PeerIps []string `json:"peer_ips"` - RoutesIn []BGPRoute `json:"routes_in"` - RoutesOut []BGPRoute `json:"routes_out"` -} - -// BGPRoute is a struct for Route in BGP neighbor listing -type BGPRoute struct { - Route string `json:"route"` - Exact bool `json:"exact"` -} - -// CreateBGPSessionRequest struct -type CreateBGPSessionRequest struct { - AddressFamily string `json:"address_family"` - DefaultRoute *bool `json:"default_route,omitempty"` -} - -// UpdateBGPSessionRequest struct -type UpdateBGPSessionRequest struct { - DefaultRoute bool `json:"default_route"` -} - -// Create function -func (s *BGPSessionServiceOp) Create(deviceID string, request CreateBGPSessionRequest) (*BGPSession, *Response, error) { - if validateErr := ValidateUUID(deviceID); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(deviceBasePath, deviceID, bgpSessionBasePath) - session := new(BGPSession) - - resp, err := s.client.DoRequest("POST", apiPath, request, session) - if err != nil { - return nil, resp, err - } - - return session, resp, err -} - -// Update function -func (s *BGPSessionServiceOp) Update(sessionID string, request UpdateBGPSessionRequest) (*BGPSession, *Response, error) { - if validateErr := ValidateUUID(sessionID); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(bgpSessionBasePath, sessionID) - session := new(BGPSession) - - resp, err := s.client.DoRequest("PUT", apiPath, request, session) - if err != nil { - return nil, resp, err - } - - return session, resp, err -} - -// Delete function -func (s *BGPSessionServiceOp) Delete(id string) (*Response, error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(bgpSessionBasePath, id) - - return s.client.DoRequest("DELETE", apiPath, nil, nil) -} - -// Get function -func (s *BGPSessionServiceOp) Get(id string, opts *GetOptions) (session *BGPSession, response *Response, err error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(bgpSessionBasePath, id) - apiPathQuery := opts.WithQuery(endpointPath) - session = new(BGPSession) - response, err = s.client.DoRequest("GET", apiPathQuery, nil, session) - if err != nil { - return nil, response, err - } - - return session, response, err -} diff --git a/vendor/github.com/packethost/packngo/billing_address.go b/vendor/github.com/packethost/packngo/billing_address.go deleted file mode 100644 index 93255b32..00000000 --- a/vendor/github.com/packethost/packngo/billing_address.go +++ /dev/null @@ -1,7 +0,0 @@ -package packngo - -type BillingAddress struct { - StreetAddress string `json:"street_address,omitempty"` - PostalCode string `json:"postal_code,omitempty"` - CountryCode string `json:"country_code_alpha2,omitempty"` -} diff --git a/vendor/github.com/packethost/packngo/capacities.go b/vendor/github.com/packethost/packngo/capacities.go deleted file mode 100644 index 45ffac60..00000000 --- a/vendor/github.com/packethost/packngo/capacities.go +++ /dev/null @@ -1,103 +0,0 @@ -package packngo - -const ( - capacityBasePath = "/capacity" - capacityBasePathMetros = "/capacity/metros" -) - -// CapacityService interface defines available capacity methods -type CapacityService interface { - List() (*CapacityReport, *Response, error) - ListMetros() (*CapacityReport, *Response, error) - Check(*CapacityInput) (*CapacityInput, *Response, error) - CheckMetros(*CapacityInput) (*CapacityInput, *Response, error) -} - -// CapacityInput struct -type CapacityInput struct { - Servers []ServerInfo `json:"servers,omitempty"` -} - -// ServerInfo struct -type ServerInfo struct { - Facility string `json:"facility,omitempty"` - Metro string `json:"metro,omitempty"` - Plan string `json:"plan,omitempty"` - Quantity int `json:"quantity,omitempty"` - Available bool `json:"available,omitempty"` -} - -type capacityRoot struct { - Capacity CapacityReport `json:"capacity,omitempty"` -} - -// CapacityReport map -type CapacityReport map[string]map[string]CapacityPerBaremetal - -// // CapacityPerFacility struct -// type CapacityPerFacility struct { -// T1SmallX86 *CapacityPerBaremetal `json:"t1.small.x86,omitempty"` -// C1SmallX86 *CapacityPerBaremetal `json:"c1.small.x86,omitempty"` -// M1XlargeX86 *CapacityPerBaremetal `json:"m1.xlarge.x86,omitempty"` -// C1XlargeX86 *CapacityPerBaremetal `json:"c1.xlarge.x86,omitempty"` - -// Baremetal0 *CapacityPerBaremetal `json:"baremetal_0,omitempty"` -// Baremetal1 *CapacityPerBaremetal `json:"baremetal_1,omitempty"` -// Baremetal1e *CapacityPerBaremetal `json:"baremetal_1e,omitempty"` -// Baremetal2 *CapacityPerBaremetal `json:"baremetal_2,omitempty"` -// Baremetal2a *CapacityPerBaremetal `json:"baremetal_2a,omitempty"` -// Baremetal2a2 *CapacityPerBaremetal `json:"baremetal_2a2,omitempty"` -// Baremetal3 *CapacityPerBaremetal `json:"baremetal_3,omitempty"` -// } - -// CapacityPerBaremetal struct -type CapacityPerBaremetal struct { - Level string `json:"level,omitempty"` -} - -// CapacityList struct -type CapacityList struct { - Capacity CapacityReport `json:"capacity,omitempty"` -} - -// CapacityServiceOp implements CapacityService -type CapacityServiceOp struct { - client *Client -} - -func capacityList(client *Client, capUrl string) (*CapacityReport, *Response, error) { - root := new(capacityRoot) - - resp, err := client.DoRequest("GET", capUrl, nil, root) - if err != nil { - return nil, resp, err - } - - return &root.Capacity, nil, nil -} - -// List returns a list of facilities and plans with their current capacity. -func (s *CapacityServiceOp) List() (*CapacityReport, *Response, error) { - return capacityList(s.client, capacityBasePath) -} - -// ListMetros returns a list of metros and plans with their current capacity. -func (s *CapacityServiceOp) ListMetros() (*CapacityReport, *Response, error) { - return capacityList(s.client, capacityBasePathMetros) -} - -func checkCapacity(client *Client, input *CapacityInput, capUrl string) (capInput *CapacityInput, resp *Response, err error) { - capInput = new(CapacityInput) - resp, err = client.DoRequest("POST", capUrl, input, capInput) - return capInput, resp, err -} - -// Check validates if a deploy can be fulfilled in a capacity. -func (s *CapacityServiceOp) Check(input *CapacityInput) (capInput *CapacityInput, resp *Response, err error) { - return checkCapacity(s.client, input, capacityBasePath) -} - -// Check validates if a deploy can be fulfilled in a metro. -func (s *CapacityServiceOp) CheckMetros(input *CapacityInput) (capInput *CapacityInput, resp *Response, err error) { - return checkCapacity(s.client, input, capacityBasePathMetros) -} diff --git a/vendor/github.com/packethost/packngo/clientopt.go b/vendor/github.com/packethost/packngo/clientopt.go deleted file mode 100644 index 11096ab6..00000000 --- a/vendor/github.com/packethost/packngo/clientopt.go +++ /dev/null @@ -1,55 +0,0 @@ -package packngo - -import ( - "net/http" - "net/url" -) - -// ClientOpt is an option usable as an argument to NewClient constructor. -type ClientOpt func(*Client) error - -// WithAuth configures Client with a specific consumerToken and apiKey for subsequent HTTP requests. -func WithAuth(consumerToken string, apiKey string) ClientOpt { - return func(c *Client) error { - c.ConsumerToken = consumerToken - c.APIKey = apiKey - c.apiKeySet = true - - return nil - } -} - -// WithHTTPClient configures Client to use a specific httpClient for subsequent HTTP requests. -func WithHTTPClient(httpClient *http.Client) ClientOpt { - return func(c *Client) error { - c.client = httpClient - - return nil - } -} - -// WithBaseURL configures Client to use a nonstandard API URL, e.g. for mocking the remote API. -func WithBaseURL(apiBaseURL string) ClientOpt { - return func(c *Client) error { - u, err := url.Parse(apiBaseURL) - if err != nil { - return err - } - - c.BaseURL = u - - return nil - } -} - -// WithHeader configures Client to use the given HTTP header set. -// The headers X-Auth-Token, X-Consumer-Token, User-Agent will be ignored even if provided in the set. -func WithHeader(header http.Header) ClientOpt { - return func(c *Client) error { - for k, v := range header { - c.header[k] = v - } - - return nil - } -} diff --git a/vendor/github.com/packethost/packngo/code-of-conduct.md b/vendor/github.com/packethost/packngo/code-of-conduct.md deleted file mode 100644 index 3a14e528..00000000 --- a/vendor/github.com/packethost/packngo/code-of-conduct.md +++ /dev/null @@ -1,3 +0,0 @@ -# Code Of Conduct - -Please refer to the [Contributor Covenant](https://www.contributor-covenant.org/version/1/2/0/code-of-conduct/). diff --git a/vendor/github.com/packethost/packngo/connections.go b/vendor/github.com/packethost/packngo/connections.go deleted file mode 100644 index bba8d74d..00000000 --- a/vendor/github.com/packethost/packngo/connections.go +++ /dev/null @@ -1,331 +0,0 @@ -package packngo - -import ( - "errors" - "fmt" - "path" - "time" -) - -type ConnectionRedundancy string -type ConnectionType string -type ConnectionPortRole string -type ConnectionMode string - -const ( - connectionBasePath = "/connections" - ConnectionShared ConnectionType = "shared" - ConnectionDedicated ConnectionType = "dedicated" - ConnectionRedundant ConnectionRedundancy = "redundant" - ConnectionPrimary ConnectionRedundancy = "primary" - ConnectionPortPrimary ConnectionPortRole = "primary" - ConnectionPortSecondary ConnectionPortRole = "secondary" - ConnectionModeStandard ConnectionMode = "standard" - ConnectionModeTunnel ConnectionMode = "tunnel" - ConnectionDeleteTimeout = 60 * time.Second - ConnectionDeleteCheck = 2 * time.Second -) - -type ConnectionService interface { - OrganizationCreate(string, *ConnectionCreateRequest) (*Connection, *Response, error) - ProjectCreate(string, *ConnectionCreateRequest) (*Connection, *Response, error) - Update(string, *ConnectionUpdateRequest, *GetOptions) (*Connection, *Response, error) - OrganizationList(string, *GetOptions) ([]Connection, *Response, error) - ProjectList(string, *GetOptions) ([]Connection, *Response, error) - Delete(string, bool) (*Response, error) - Get(string, *GetOptions) (*Connection, *Response, error) - Events(string, *GetOptions) ([]Event, *Response, error) - PortEvents(string, string, *GetOptions) ([]Event, *Response, error) - Ports(string, *GetOptions) ([]ConnectionPort, *Response, error) - Port(string, string, *GetOptions) (*ConnectionPort, *Response, error) - VirtualCircuits(string, string, *GetOptions) ([]VirtualCircuit, *Response, error) -} - -type ConnectionServiceOp struct { - client *Client -} - -type connectionPortsRoot struct { - Ports []ConnectionPort `json:"ports"` -} - -type connectionsRoot struct { - Connections []Connection `json:"interconnections"` - Meta meta `json:"meta"` -} - -type ConnectionPort struct { - *Href `json:",inline"` - ID string `json:"id"` - LinkStatus string `json:"link_status,omitempty"` - Name string `json:"name,omitempty"` - Organization *Organization `json:"organization,omitempty"` - Role ConnectionPortRole `json:"role,omitempty"` - // Speed is the maximum allowed throughput. This value inherits changes made in the Equinix Fabric API. - Speed uint64 `json:"speed,omitempty"` - Status string `json:"status,omitempty"` - Tokens []FabricServiceToken `json:"tokens,omitempty"` - VirtualCircuits []VirtualCircuit `json:"virtual_circuits,omitempty"` -} - -type Connection struct { - ID string `json:"id"` - ContactEmail string `json:"contact_email,omitempty"` - Name string `json:"name,omitempty"` - Status string `json:"status,omitempty"` - Redundancy ConnectionRedundancy `json:"redundancy,omitempty"` - Facility *Facility `json:"facility,omitempty"` - Metro *Metro `json:"metro,omitempty"` - Type ConnectionType `json:"type,omitempty"` - Mode *ConnectionMode `json:"mode,omitempty"` - Description string `json:"description,omitempty"` - Project *Project `json:"project,omitempty"` - Organization *Organization `json:"organization,omitempty"` - Speed uint64 `json:"speed,omitempty"` - Token string `json:"token,omitempty"` - Tokens []FabricServiceToken `json:"service_tokens,omitempty"` - Tags []string `json:"tags,omitempty"` - Ports []ConnectionPort `json:"ports,omitempty"` - ServiceTokenType string `json:"service_token_type,omitempty"` -} - -type ConnectionCreateRequest struct { - ContactEmail string `json:"contact_email,omitempty"` - Description *string `json:"description,omitempty"` - Facility string `json:"facility,omitempty"` - Metro string `json:"metro,omitempty"` - Mode ConnectionMode `json:"mode,omitempty"` - Name string `json:"name,omitempty"` - Project string `json:"project,omitempty"` - Redundancy ConnectionRedundancy `json:"redundancy,omitempty"` - ServiceTokenType FabricServiceTokenType `json:"service_token_type,omitempty"` - Speed uint64 `json:"speed,omitempty"` - Tags []string `json:"tags,omitempty"` - Type ConnectionType `json:"type,omitempty"` - VLANs []int `json:"vlans,omitempty"` -} - -type ConnectionUpdateRequest struct { - Redundancy ConnectionRedundancy `json:"redundancy,omitempty"` - Mode *ConnectionMode `json:"mode,omitempty"` - Description *string `json:"description,omitempty"` - Tags []string `json:"tags,omitempty"` -} - -func (c *Connection) PortByRole(r ConnectionPortRole) *ConnectionPort { - for _, p := range c.Ports { - if p.Role == r { - return &p - } - } - return nil -} - -func (s *ConnectionServiceOp) create(apiUrl string, createRequest *ConnectionCreateRequest) (*Connection, *Response, error) { - connection := new(Connection) - resp, err := s.client.DoRequest("POST", apiUrl, createRequest, connection) - if err != nil { - return nil, resp, err - } - - return connection, resp, err -} - -func (s *ConnectionServiceOp) OrganizationCreate(id string, createRequest *ConnectionCreateRequest) (*Connection, *Response, error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, nil, validateErr - } - apiUrl := path.Join(organizationBasePath, id, connectionBasePath) - return s.create(apiUrl, createRequest) -} - -func (s *ConnectionServiceOp) ProjectCreate(id string, createRequest *ConnectionCreateRequest) (*Connection, *Response, error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, nil, validateErr - } - apiUrl := path.Join(projectBasePath, id, connectionBasePath) - return s.create(apiUrl, createRequest) -} - -func (s *ConnectionServiceOp) list(url string, opts *GetOptions) (connections []Connection, resp *Response, err error) { - apiPathQuery := opts.WithQuery(url) - - for { - subset := new(connectionsRoot) - - resp, err = s.client.DoRequest("GET", apiPathQuery, nil, subset) - if err != nil { - return nil, resp, err - } - - connections = append(connections, subset.Connections...) - - if apiPathQuery = nextPage(subset.Meta, opts); apiPathQuery != "" { - continue - } - - return - } - -} - -func (s *ConnectionServiceOp) OrganizationList(id string, opts *GetOptions) ([]Connection, *Response, error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, nil, validateErr - } - apiUrl := path.Join(organizationBasePath, id, connectionBasePath) - return s.list(apiUrl, opts) -} - -func (s *ConnectionServiceOp) ProjectList(id string, opts *GetOptions) ([]Connection, *Response, error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, nil, validateErr - } - apiUrl := path.Join(projectBasePath, id, connectionBasePath) - return s.list(apiUrl, opts) -} - -func (s *ConnectionServiceOp) Delete(id string, wait bool) (*Response, error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(connectionBasePath, id) - connection := new(Connection) - - resp, err := s.client.DoRequest("DELETE", apiPath, nil, connection) - if err != nil { - return resp, err - } - // We really miss context here. - if wait { - timeout := time.After(ConnectionDeleteTimeout) - //ticker := time.Tick(ConnectionDeleteCheck) - ticker := time.NewTicker(ConnectionDeleteCheck) - for { - select { - case <-ticker.C: - c, resp2, err := s.Get(id, nil) - if resp2.StatusCode == 404 { - // Connection has been deleted - return resp, nil - } - if err != nil { - return resp, err - } - if c.Status != "deleting" { - return resp, fmt.Errorf("Connection %s is in undexpected state %s", id, c.Status) - } - case <-timeout: - return resp, errors.New("Timeout waiting for connection to be deleted") - } - } - } - return resp, nil -} - -func (s *ConnectionServiceOp) Port(connID, portID string, opts *GetOptions) (*ConnectionPort, *Response, error) { - if validateErr := ValidateUUID(connID); validateErr != nil { - return nil, nil, validateErr - } - if validateErr := ValidateUUID(portID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(connectionBasePath, connID, portBasePath, portID) - apiPathQuery := opts.WithQuery(endpointPath) - port := new(ConnectionPort) - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, port) - if err != nil { - return nil, resp, err - } - return port, resp, err -} - -func (s *ConnectionServiceOp) Get(id string, opts *GetOptions) (*Connection, *Response, error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(connectionBasePath, id) - apiPathQuery := opts.WithQuery(endpointPath) - connection := new(Connection) - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, connection) - if err != nil { - return nil, resp, err - } - return connection, resp, err -} - -func (s *ConnectionServiceOp) Update(id string, updateRequest *ConnectionUpdateRequest, opts *GetOptions) (*Connection, *Response, error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(connectionBasePath, id) - apiPathQuery := opts.WithQuery(endpointPath) - connection := new(Connection) - resp, err := s.client.DoRequest("PUT", apiPathQuery, updateRequest, connection) - if err != nil { - return nil, resp, err - } - - return connection, resp, err -} - -func (s *ConnectionServiceOp) Ports(connID string, opts *GetOptions) ([]ConnectionPort, *Response, error) { - if validateErr := ValidateUUID(connID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(connectionBasePath, connID, portBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - ports := new(connectionPortsRoot) - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, ports) - if err != nil { - return nil, resp, err - } - return ports.Ports, resp, nil - -} - -func (s *ConnectionServiceOp) Events(id string, opts *GetOptions) ([]Event, *Response, error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(connectionBasePath, id, eventBasePath) - return listEvents(s.client, apiPath, opts) -} - -func (s *ConnectionServiceOp) PortEvents(connID, portID string, opts *GetOptions) ([]Event, *Response, error) { - if validateErr := ValidateUUID(connID); validateErr != nil { - return nil, nil, validateErr - } - if validateErr := ValidateUUID(portID); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(connectionBasePath, connID, portBasePath, portID, eventBasePath) - return listEvents(s.client, apiPath, opts) -} - -func (s *ConnectionServiceOp) VirtualCircuits(connID, portID string, opts *GetOptions) (vcs []VirtualCircuit, resp *Response, err error) { - if validateErr := ValidateUUID(connID); validateErr != nil { - return nil, nil, validateErr - } - if validateErr := ValidateUUID(portID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(connectionBasePath, connID, portBasePath, portID, virtualCircuitBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - for { - subset := new(virtualCircuitsRoot) - - resp, err = s.client.DoRequest("GET", apiPathQuery, nil, subset) - if err != nil { - return nil, resp, err - } - - vcs = append(vcs, subset.VirtualCircuits...) - - if apiPathQuery = nextPage(subset.Meta, opts); apiPathQuery != "" { - continue - } - - return - } -} diff --git a/vendor/github.com/packethost/packngo/device_ports.go b/vendor/github.com/packethost/packngo/device_ports.go deleted file mode 100644 index 026e0ad8..00000000 --- a/vendor/github.com/packethost/packngo/device_ports.go +++ /dev/null @@ -1,332 +0,0 @@ -package packngo - -import ( - "fmt" - "strings" -) - -const portBasePath = "/ports" - -// DevicePortService handles operations on a port which belongs to a particular device -// -// Deprecated: use PortService or Device methods -type DevicePortService interface { - Assign(*PortAssignRequest) (*Port, *Response, error) - Unassign(*PortAssignRequest) (*Port, *Response, error) - AssignNative(*PortAssignRequest) (*Port, *Response, error) - UnassignNative(string) (*Port, *Response, error) - Bond(*Port, bool) (*Port, *Response, error) - Disbond(*Port, bool) (*Port, *Response, error) - DeviceToNetworkType(string, string) (*Device, error) - DeviceNetworkType(string) (string, error) - PortToLayerTwo(string, string) (*Port, *Response, error) - PortToLayerThree(string, string) (*Port, *Response, error) - GetPortByName(string, string) (*Port, error) - GetOddEthPorts(*Device) (map[string]*Port, error) - GetAllEthPorts(*Device) (map[string]*Port, error) - ConvertDevice(*Device, string) error -} - -// DevicePortServiceOp implements DevicePortService on the Equinix Metal API -// -// Deprecated: use PortServiceOp or Device methods -type DevicePortServiceOp struct { - client *Client -} - -// GetPortByName returns the matching Port on the specified device -// -// Deprecated: use Device.GetPortByName -func (i *DevicePortServiceOp) GetPortByName(deviceID, name string) (*Port, error) { - device, _, err := i.client.Devices.Get(deviceID, nil) - if err != nil { - return nil, err - } - return device.GetPortByName(name) -} - -// Assign the specified VLAN to the specified Port -// -// Deprecated: use PortServiceOp.Assign -func (i *DevicePortServiceOp) Assign(par *PortAssignRequest) (*Port, *Response, error) { - return i.client.Ports.Assign(par.PortID, par.VirtualNetworkID) -} - -// AssignNative designates the specified VLAN as the native VLAN for the -// specified Port -// -// Deprecated: use PortServiceOp.AssignNative -func (i *DevicePortServiceOp) AssignNative(par *PortAssignRequest) (*Port, *Response, error) { - return i.client.Ports.AssignNative(par.PortID, par.VirtualNetworkID) -} - -// UnassignNative removes the native VLAN from the specified Port -// -// Deprecated: use PortServiceOp.UnassignNative -func (i *DevicePortServiceOp) UnassignNative(portID string) (*Port, *Response, error) { - if validateErr := ValidateUUID(portID); validateErr != nil { - return nil, nil, validateErr - } - return i.client.Ports.UnassignNative(portID) -} - -// Unassign removes the specified VLAN from the specified Port -// -// Deprecated: use PortServiceOp.Unassign -func (i *DevicePortServiceOp) Unassign(par *PortAssignRequest) (*Port, *Response, error) { - return i.client.Ports.Unassign(par.PortID, par.VirtualNetworkID) -} - -// Bond enabled bonding on the specified port -// -// Deprecated: use PortServiceOp.Bond -func (i *DevicePortServiceOp) Bond(p *Port, bulk_enable bool) (*Port, *Response, error) { - if p.Data.Bonded { - return p, nil, nil - } - - return i.client.Ports.Bond(p.ID, bulk_enable) -} - -// Disbond disables bonding on the specified port -// -// Deprecated: use PortServiceOp.Disbond -func (i *DevicePortServiceOp) Disbond(p *Port, bulk_disable bool) (*Port, *Response, error) { - if !p.Data.Bonded { - return p, nil, nil - } - return i.client.Ports.Disbond(p.ID, bulk_disable) -} - -// PortToLayerTwo fetches the specified device, finds the matching port by name, -// and converts it to layer2. A port may already be in a layer2 mode, in which -// case the port will be returned with a nil response and nil error with no -// additional action taking place. -// -// Deprecated: use PortServiceOp.ConvertToLayerTwo -func (i *DevicePortServiceOp) PortToLayerTwo(deviceID, portName string) (*Port, *Response, error) { - p, err := i.GetPortByName(deviceID, portName) - if err != nil { - return nil, nil, err - } - if strings.HasPrefix(p.NetworkType, "layer2") { - return p, nil, nil - } - - return i.client.Ports.ConvertToLayerTwo(p.ID) -} - -// PortToLayerThree fetches the specified device, finds the matching port by -// name, and converts it to layer3. A port may already be in a layer3 mode, in -// which case the port will be returned with a nil response and nil error with -// no additional action taking place. -// -// When switching to Layer3, a new set of IP addresses will be requested -// including Public IPv4, Public IPv6, and Private IPv6 addresses. -// -// Deprecated: use PortServiceOp.ConvertToLayerTwo -func (i *DevicePortServiceOp) PortToLayerThree(deviceID, portName string) (*Port, *Response, error) { - p, err := i.GetPortByName(deviceID, portName) - if err != nil { - return nil, nil, err - } - if (p.NetworkType == NetworkTypeL3) || (p.NetworkType == NetworkTypeHybrid) { - return p, nil, nil - } - - ips := []AddressRequest{ - {AddressFamily: 4, Public: true}, - {AddressFamily: 4, Public: false}, - {AddressFamily: 6, Public: true}, - } - - return i.client.Ports.ConvertToLayerThree(p.ID, ips) -} - -// DeviceNetworkType fetches the specified Device and returns a heuristic single -// word network type consistent with the Equinix Metal console experience. -// -// Deprecated: use Device.GetNetworkType -func (i *DevicePortServiceOp) DeviceNetworkType(deviceID string) (string, error) { - if validateErr := ValidateUUID(deviceID); validateErr != nil { - return "", validateErr - } - d, _, err := i.client.Devices.Get(deviceID, nil) - if err != nil { - return "", err - } - return d.GetNetworkType(), nil -} - -// GetAllEthPorts fetches the specified Device and returns a heuristic single -// word network type consistent with the Equinix Metal console experience. -// -// Deprecated: use Device.GetPhysicalPorts -func (i *DevicePortServiceOp) GetAllEthPorts(d *Device) (map[string]*Port, error) { - d, _, err := i.client.Devices.Get(d.ID, nil) - if err != nil { - return nil, err - } - return d.GetPhysicalPorts(), nil -} - -// GetOddEthPorts fetches the specified Device and returns physical -// ports eth1 and eth3. -// -// Deprecated: use Device.GetPhysicalPorts and filter the map to only the keys -// ending with odd digits -func (i *DevicePortServiceOp) GetOddEthPorts(d *Device) (map[string]*Port, error) { - d, _, err := i.client.Devices.Get(d.ID, nil) - if err != nil { - return nil, err - } - ret := map[string]*Port{} - eth1, err := d.GetPortByName("eth1") - if err != nil { - return nil, err - } - ret["eth1"] = eth1 - - eth3, err := d.GetPortByName("eth3") - if err != nil { - return ret, nil - } - ret["eth3"] = eth3 - return ret, nil - -} - -// ConvertDevice converts the specified device's network ports (including -// addresses and vlans) to the named network type, consistent with the Equinix -// Metal console experience. -// -// Deprecated: Equinix Metal devices may support more than two ports and the -// whole-device single word network type can no longer capture the capabilities -// and permutations of device port configurations. -func (i *DevicePortServiceOp) ConvertDevice(d *Device, targetType string) error { - bondPorts := d.GetBondPorts() - - if targetType == NetworkTypeL3 { - // TODO: remove vlans from all the ports - for _, p := range bondPorts { - _, _, err := i.Bond(p, false) - if err != nil { - return err - } - } - _, _, err := i.PortToLayerThree(d.ID, "bond0") - if err != nil { - return err - } - allEthPorts, err := i.GetAllEthPorts(d) - if err != nil { - return err - } - for _, p := range allEthPorts { - _, _, err := i.Bond(p, false) - if err != nil { - return err - } - } - } - if targetType == NetworkTypeHybrid { - for _, p := range bondPorts { - _, _, err := i.Bond(p, false) - if err != nil { - return err - } - } - - _, _, err := i.PortToLayerThree(d.ID, "bond0") - if err != nil { - return err - } - - // ports need to be refreshed before bonding/disbonding - oddEthPorts, err := i.GetOddEthPorts(d) - if err != nil { - return err - } - - for _, p := range oddEthPorts { - _, _, err := i.Disbond(p, false) - if err != nil { - return err - } - } - } - if targetType == NetworkTypeL2Individual { - _, _, err := i.PortToLayerTwo(d.ID, "bond0") - if err != nil { - return err - } - for _, p := range bondPorts { - _, _, err = i.Disbond(p, true) - if err != nil { - return err - } - } - } - if targetType == NetworkTypeL2Bonded { - - for _, p := range bondPorts { - _, _, err := i.PortToLayerTwo(d.ID, p.Name) - if err != nil { - return err - } - } - allEthPorts, err := i.GetAllEthPorts(d) - if err != nil { - return err - } - for _, p := range allEthPorts { - _, _, err := i.Bond(p, false) - if err != nil { - return err - } - } - } - return nil -} - -// DeviceToNetworkType fetches the specified device and converts its network -// ports (including addresses and vlans) to the named network type, consistent -// with the Equinix Metal console experience. -// -// Deprecated: use DevicePortServiceOp.ConvertDevice which this function thinly -// wraps. -func (i *DevicePortServiceOp) DeviceToNetworkType(deviceID string, targetType string) (*Device, error) { - if validateErr := ValidateUUID(deviceID); validateErr != nil { - return nil, validateErr - } - d, _, err := i.client.Devices.Get(deviceID, nil) - if err != nil { - return nil, err - } - - curType := d.GetNetworkType() - - if curType == targetType { - return nil, fmt.Errorf("Device already is in state %s", targetType) - } - err = i.ConvertDevice(d, targetType) - if err != nil { - return nil, err - } - - d, _, err = i.client.Devices.Get(deviceID, nil) - - if err != nil { - return nil, err - } - - finalType := d.GetNetworkType() - - if finalType != targetType { - return nil, fmt.Errorf( - "Failed to convert device %s from %s to %s. New type was %s", - deviceID, curType, targetType, finalType) - - } - return d, err -} diff --git a/vendor/github.com/packethost/packngo/devices.go b/vendor/github.com/packethost/packngo/devices.go deleted file mode 100644 index ace32e68..00000000 --- a/vendor/github.com/packethost/packngo/devices.go +++ /dev/null @@ -1,692 +0,0 @@ -package packngo - -import ( - "encoding/json" - "fmt" - "net/url" - "path" - "strconv" -) - -const deviceBasePath = "/devices" - -const ( - NetworkTypeHybrid = "hybrid" - NetworkTypeL2Bonded = "layer2-bonded" - NetworkTypeL2Individual = "layer2-individual" - NetworkTypeL3 = "layer3" -) - -// DeviceService interface defines available device methods -type DeviceService interface { - List(ProjectID string, opts *ListOptions) ([]Device, *Response, error) - Get(DeviceID string, opts *GetOptions) (*Device, *Response, error) - Create(*DeviceCreateRequest) (*Device, *Response, error) - Update(string, *DeviceUpdateRequest) (*Device, *Response, error) - Delete(string, bool) (*Response, error) - Reboot(string) (*Response, error) - Reinstall(string, *DeviceReinstallFields) (*Response, error) - PowerOff(string) (*Response, error) - PowerOn(string) (*Response, error) - Rescue(string) (*Response, error) - Lock(string) (*Response, error) - Unlock(string) (*Response, error) - ListBGPSessions(deviceID string, opts *ListOptions) ([]BGPSession, *Response, error) - ListBGPNeighbors(deviceID string, opts *ListOptions) ([]BGPNeighbor, *Response, error) - ListEvents(deviceID string, opts *ListOptions) ([]Event, *Response, error) - GetBandwidth(deviceID string, opts *BandwidthOpts) (*BandwidthIO, *Response, error) -} - -type devicesRoot struct { - Devices []Device `json:"devices"` - Meta meta `json:"meta"` -} - -// Device represents an Equinix Metal device from API -type Device struct { - ID string `json:"id"` - Href string `json:"href,omitempty"` - Hostname string `json:"hostname,omitempty"` - Description *string `json:"description,omitempty"` - State string `json:"state,omitempty"` - Created string `json:"created_at,omitempty"` - CreatedBy *UserLite `json:"created_by,omitempty"` - Updated string `json:"updated_at,omitempty"` - Locked bool `json:"locked,omitempty"` - BillingCycle string `json:"billing_cycle,omitempty"` - Storage *CPR `json:"storage,omitempty"` - Tags []string `json:"tags,omitempty"` - Network []*IPAddressAssignment `json:"ip_addresses"` - Volumes []*Volume `json:"volumes"` - OS *OS `json:"operating_system,omitempty"` - Plan *Plan `json:"plan,omitempty"` - Facility *Facility `json:"facility,omitempty"` - Metro *Metro `json:"metro,omitempty"` - Project *Project `json:"project,omitempty"` - ProvisionEvents []*Event `json:"provisioning_events,omitempty"` - ProvisionPer float32 `json:"provisioning_percentage,omitempty"` - UserData string `json:"userdata,omitempty"` - User string `json:"user,omitempty"` - RootPassword string `json:"root_password,omitempty"` - IPXEScriptURL string `json:"ipxe_script_url,omitempty"` - AlwaysPXE bool `json:"always_pxe,omitempty"` - HardwareReservation *HardwareReservation `json:"hardware_reservation,omitempty"` - SpotInstance bool `json:"spot_instance,omitempty"` - SpotPriceMax float64 `json:"spot_price_max,omitempty"` - TerminationTime *Timestamp `json:"termination_time,omitempty"` - NetworkPorts []Port `json:"network_ports,omitempty"` - CustomData map[string]interface{} `json:"customdata,omitempty"` - SSHKeys []SSHKey `json:"ssh_keys,omitempty"` - ShortID string `json:"short_id,omitempty"` - SwitchUUID string `json:"switch_uuid,omitempty"` - SOS string `json:"sos,omitempty"` -} - -type NetworkInfo struct { - PublicIPv4 string - PublicIPv6 string - PrivateIPv4 string -} - -type BandwidthIO struct { - Inbound BandwidthComponent `json:"inbound"` - Outbound BandwidthComponent `json:"outbound"` -} - -func (b *BandwidthIO) UnmarshalJSON(buf []byte) error { - tmp := []interface{}{&b.Inbound, &b.Outbound} - wantLen := len(tmp) - if err := json.Unmarshal(buf, &tmp); err != nil { - return err - } - if g, e := len(tmp), wantLen; g != e { - return fmt.Errorf("wrong number of fields in BandwidthIO: %d != %d", g, e) - } - if b.Inbound.Target == BandwidthOutbound { - b.Inbound, b.Outbound = b.Outbound, b.Inbound - } - return nil -} - -type bandwidthRoot struct { - Bandwidth BandwidthIO `json:"bandwidth"` -} - -type BandwidthTarget string - -// BandwidthTarget enums -const ( - BandwidthInbound BandwidthTarget = "inbound" - BandwidthOutbound BandwidthTarget = "outbound" -) - -// BandwidthTags -type BandwidthTags struct { - // AggregatedBy - AggregatedBy string `json:"aggregatedBy"` - - // Name - Name string `json:"name"` -} - -// BandwidthComponent -type BandwidthComponent struct { - // Datapoints - Datapoints []Datapoint `json:"datapoints"` - - // Tags - Tags BandwidthTags `json:"tags"` - - // Target - Target BandwidthTarget `json:"target"` -} -type Datapoint struct { - // Rate is the aggregated sum of Bytes/Second across all ports - Rate *float64 `json:"rate"` - - // When the rate was captured - When Timestamp `json:"when"` -} - -func (d *Datapoint) UnmarshalJSON(buf []byte) error { - tmp := []interface{}{&d.Rate, &d.When} - wantLen := len(tmp) - if err := json.Unmarshal(buf, &tmp); err != nil { - return err - } - if g, e := len(tmp), wantLen; g != e { - return fmt.Errorf("wrong number of fields in BandwidthComponent: %d != %d", g, e) - } - return nil -} - -type BandwidthOpts struct { - From *Timestamp `json:"from,omitempty"` - Until *Timestamp `json:"until,omitempty"` -} - -func (b *BandwidthOpts) Encode() string { - if b == nil { - return "" - } - v := url.Values{} - if b.From != nil { - v.Add("from", strconv.FormatInt(b.From.UTC().Unix(), 10)) - } - if b.Until != nil { - v.Add("until", strconv.FormatInt(b.Until.UTC().Unix(), 10)) - } - return v.Encode() -} - -func (b *BandwidthOpts) WithQuery(apiPath string) string { - params := b.Encode() - if params != "" { - // parse path, take existing vars - return fmt.Sprintf("%s?%s", apiPath, params) - } - return apiPath -} - -func (d *DeviceServiceOp) GetBandwidth(deviceID string, opts *BandwidthOpts) (*BandwidthIO, *Response, error) { - if validateErr := ValidateUUID(deviceID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(deviceBasePath, deviceID, "bandwidth") - apiPathQuery := opts.WithQuery(endpointPath) - bw := new(bandwidthRoot) - resp, err := d.client.DoRequest("GET", apiPathQuery, nil, bw) - if err != nil { - return nil, resp, err - } - return &bw.Bandwidth, resp, nil -} - -func (d *Device) GetNetworkInfo() NetworkInfo { - ni := NetworkInfo{} - for _, ip := range d.Network { - // Initial device IPs are fixed and marked as "Management" - if ip.Management { - if ip.AddressFamily == 4 { - if ip.Public { - ni.PublicIPv4 = ip.Address - } else { - ni.PrivateIPv4 = ip.Address - } - } else { - ni.PublicIPv6 = ip.Address - } - } - } - return ni -} - -func (d Device) String() string { - return Stringify(d) -} - -func (d *Device) NumOfBonds() int { - numOfBonds := 0 - for _, p := range d.NetworkPorts { - if p.Type == "NetworkBondPort" { - numOfBonds++ - } - } - return numOfBonds -} - -func (d *Device) GetPortsInBond(name string) map[string]*Port { - ports := map[string]*Port{} - for _, port := range d.NetworkPorts { - if port.Bond != nil && port.Bond.Name == name { - p := port - ports[p.Name] = &p - } - } - return ports -} - -func (d *Device) GetBondPorts() map[string]*Port { - ports := map[string]*Port{} - for _, port := range d.NetworkPorts { - if port.Type == "NetworkBondPort" { - p := port - ports[p.Name] = &p - } - } - return ports -} - -func (d *Device) GetPhysicalPorts() map[string]*Port { - ports := map[string]*Port{} - for _, port := range d.NetworkPorts { - if port.Type == "NetworkPort" { - p := port - ports[p.Name] = &p - } - } - return ports -} - -func (d *Device) GetPortByName(name string) (*Port, error) { - for _, port := range d.NetworkPorts { - if port.Name == name { - return &port, nil - } - } - return nil, fmt.Errorf("Port %s not found in device %s", name, d.ID) -} - -type ports map[string]*Port - -func (ports ports) allBonded() bool { - if ports == nil { - return false - } - - if len(ports) == 0 { - return false - } - - for _, p := range ports { - if (p == nil) || (!p.Data.Bonded) { - return false - } - } - return true -} - -func (d *Device) HasManagementIPs() bool { - for _, ip := range d.Network { - if ip.Management { - return true - } - } - return false -} - -// GetNetworkType returns a composite network type identification for a device -// based on the plan, network_type, and IP management state of the device. -// GetNetworkType provides the same composite state rendered in the Packet -// Portal for a given device. -func (d *Device) GetNetworkType() string { - if d.Plan != nil { - if d.Plan.Slug == "baremetal_0" || d.Plan.Slug == "baremetal_1" { - return NetworkTypeL3 - } - if d.Plan.Slug == "baremetal_1e" { - return NetworkTypeHybrid - } - } - - bonds := ports(d.GetBondPorts()) - phys := ports(d.GetPhysicalPorts()) - - if bonds.allBonded() { - if phys.allBonded() { - if !d.HasManagementIPs() { - return NetworkTypeL2Bonded - } - return NetworkTypeL3 - } - return NetworkTypeHybrid - } - return NetworkTypeL2Individual -} - -type IPAddressCreateRequest struct { - // Address Family for IP Address - AddressFamily int `json:"address_family"` - - // Address Type for IP Address - Public bool `json:"public"` - - // CIDR Size for the IP Block created. Valid values depends on the operating system provisioned. - CIDR int `json:"cidr,omitempty"` - - // Reservations are UUIDs of any IP reservations to use when assigning IPs - Reservations []string `json:"ip_reservations,omitempty"` -} - -// CPR is a struct for custom partitioning and RAID -// If you don't want to bother writing the struct, just write the CPR conf to -// a string and then do -// -// var cpr CPR -// err := json.Unmarshal([]byte(cprString), &cpr) -// if err != nil { -// log.Fatal(err) -// } -type CPR struct { - Disks []struct { - Device string `json:"device"` - WipeTable bool `json:"wipeTable"` - Partitions []struct { - Label string `json:"label"` - Number int `json:"number"` - Size string `json:"size"` - } `json:"partitions"` - } `json:"disks"` - Raid []struct { - Devices []string `json:"devices"` - Level string `json:"level"` - Name string `json:"name"` - } `json:"raid,omitempty"` - Filesystems []struct { - Mount struct { - Device string `json:"device"` - Format string `json:"format"` - Point string `json:"point"` - Create struct { - Options []string `json:"options"` - } `json:"create"` - } `json:"mount"` - } `json:"filesystems"` -} - -// DeviceCreateRequest type used to create an Equinix Metal device -type DeviceCreateRequest struct { - Hostname string `json:"hostname,omitempty"` - Plan string `json:"plan"` - Facility []string `json:"facility,omitempty"` - Metro string `json:"metro,omitempty"` - OS string `json:"operating_system"` - BillingCycle string `json:"billing_cycle,omitempty"` - ProjectID string `json:"project_id"` - UserData string `json:"userdata,omitempty"` - Storage *CPR `json:"storage,omitempty"` - Tags []string `json:"tags"` - Description string `json:"description,omitempty"` - IPXEScriptURL string `json:"ipxe_script_url,omitempty"` - PublicIPv4SubnetSize int `json:"public_ipv4_subnet_size,omitempty"` - AlwaysPXE bool `json:"always_pxe,omitempty"` - HardwareReservationID string `json:"hardware_reservation_id,omitempty"` - SpotInstance bool `json:"spot_instance,omitempty"` - SpotPriceMax float64 `json:"spot_price_max,omitempty,string"` - TerminationTime *Timestamp `json:"termination_time,omitempty"` - CustomData string `json:"customdata,omitempty"` - // UserSSHKeys is a list of user UUIDs - essentially a list of - // collaborators. The users must be a collaborator in the same project - // where the device is created. The user's SSH keys then go to the - // device - UserSSHKeys []string `json:"user_ssh_keys,omitempty"` - // Project SSHKeys is a list of SSHKeys resource UUIDs. If this param - // is supplied, only the listed SSHKeys will go to the device. - // Any other Project SSHKeys and any User SSHKeys will not be present - // in the device. - ProjectSSHKeys []string `json:"project_ssh_keys,omitempty"` - Features map[string]string `json:"features,omitempty"` - IPAddresses []IPAddressCreateRequest `json:"ip_addresses,omitempty"` - NoSSHKeys bool `json:"no_ssh_keys,omitempty"` -} - -// DeviceUpdateRequest type used to update an Equinix Metal device -type DeviceUpdateRequest struct { - Hostname *string `json:"hostname,omitempty"` - Description *string `json:"description,omitempty"` - UserData *string `json:"userdata,omitempty"` - Locked *bool `json:"locked,omitempty"` - Tags *[]string `json:"tags,omitempty"` - AlwaysPXE *bool `json:"always_pxe,omitempty"` - IPXEScriptURL *string `json:"ipxe_script_url,omitempty"` - CustomData *string `json:"customdata,omitempty"` -} - -func (d DeviceCreateRequest) String() string { - return Stringify(d) -} - -// DeviceActionRequest type used to execute actions on devices -type DeviceActionRequest struct { - Type string `json:"type"` -} - -type DeviceDeleteRequest struct { - Force bool `json:"force_delete"` -} -type DeviceReinstallFields struct { - OperatingSystem string `json:"operating_system,omitempty"` - PreserveData bool `json:"preserve_data,omitempty"` - DeprovisionFast bool `json:"deprovision_fast,omitempty"` -} - -type DeviceReinstallRequest struct { - DeviceActionRequest - *DeviceReinstallFields -} - -func (d DeviceActionRequest) String() string { - return Stringify(d) -} - -// DeviceServiceOp implements DeviceService -type DeviceServiceOp struct { - client *Client -} - -// List returns devices on a project -// -// Regarding ListOptions.Search: The API documentation does not provide guidance -// on the fields that will be searched using this parameter, so this behavior is -// undefined and prone to change. -// -// As of 2020-10-20, ListOptions.Search will look for matches in the following -// Device properties: Hostname, Description, Tags, ID, ShortID, Network.Address, -// Plan.Name, Plan.Slug, Facility.Code, Facility.Name, OS.Name, OS.Slug, -// HardwareReservation.ID, HardwareReservation.ShortID -func (s *DeviceServiceOp) List(projectID string, opts *ListOptions) (devices []Device, resp *Response, err error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - opts = opts.Including("facility") - endpointPath := path.Join(projectBasePath, projectID, deviceBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - - for { - subset := new(devicesRoot) - - resp, err = s.client.DoRequest("GET", apiPathQuery, nil, subset) - if err != nil { - return nil, resp, err - } - - devices = append(devices, subset.Devices...) - - if apiPathQuery = nextPage(subset.Meta, opts); apiPathQuery != "" { - continue - } - - return - } -} - -// Get returns a device by id -func (s *DeviceServiceOp) Get(deviceID string, opts *GetOptions) (*Device, *Response, error) { - if validateErr := ValidateUUID(deviceID); validateErr != nil { - return nil, nil, validateErr - } - opts = opts.Including("facility") - endpointPath := path.Join(deviceBasePath, deviceID) - apiPathQuery := opts.WithQuery(endpointPath) - device := new(Device) - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, device) - if err != nil { - return nil, resp, err - } - return device, resp, err -} - -// Create creates a new device -func (s *DeviceServiceOp) Create(createRequest *DeviceCreateRequest) (*Device, *Response, error) { - apiPath := path.Join(projectBasePath, createRequest.ProjectID, deviceBasePath) - device := new(Device) - - resp, err := s.client.DoRequest("POST", apiPath, createRequest, device) - if err != nil { - return nil, resp, err - } - return device, resp, err -} - -// Update updates an existing device -func (s *DeviceServiceOp) Update(deviceID string, updateRequest *DeviceUpdateRequest) (*Device, *Response, error) { - if validateErr := ValidateUUID(deviceID); validateErr != nil { - return nil, nil, validateErr - } - opts := &GetOptions{} - opts = opts.Including("facility") - endpointPath := path.Join(deviceBasePath, deviceID) - apiPathQuery := opts.WithQuery(endpointPath) - device := new(Device) - - resp, err := s.client.DoRequest("PUT", apiPathQuery, updateRequest, device) - if err != nil { - return nil, resp, err - } - - return device, resp, err -} - -// Delete deletes a device -func (s *DeviceServiceOp) Delete(deviceID string, force bool) (*Response, error) { - if validateErr := ValidateUUID(deviceID); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(deviceBasePath, deviceID) - req := &DeviceDeleteRequest{Force: force} - - return s.client.DoRequest("DELETE", apiPath, req, nil) -} - -// Reboot reboots on a device -func (s *DeviceServiceOp) Reboot(deviceID string) (*Response, error) { - if validateErr := ValidateUUID(deviceID); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(deviceBasePath, deviceID, "actions") - action := &DeviceActionRequest{Type: "reboot"} - - return s.client.DoRequest("POST", apiPath, action, nil) -} - -// Reinstall reinstalls a device -func (s *DeviceServiceOp) Reinstall(deviceID string, fields *DeviceReinstallFields) (*Response, error) { - if validateErr := ValidateUUID(deviceID); validateErr != nil { - return nil, validateErr - } - path := fmt.Sprintf("%s/%s/actions", deviceBasePath, deviceID) - action := &DeviceReinstallRequest{DeviceActionRequest{Type: "reinstall"}, fields} - - return s.client.DoRequest("POST", path, action, nil) -} - -// PowerOff powers on a device -func (s *DeviceServiceOp) PowerOff(deviceID string) (*Response, error) { - if validateErr := ValidateUUID(deviceID); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(deviceBasePath, deviceID, "actions") - action := &DeviceActionRequest{Type: "power_off"} - - return s.client.DoRequest("POST", apiPath, action, nil) -} - -// PowerOn powers on a device -func (s *DeviceServiceOp) PowerOn(deviceID string) (*Response, error) { - if validateErr := ValidateUUID(deviceID); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(deviceBasePath, deviceID, "actions") - action := &DeviceActionRequest{Type: "power_on"} - - return s.client.DoRequest("POST", apiPath, action, nil) -} - -// Rescue boots a device into Rescue OS -func (s *DeviceServiceOp) Rescue(deviceID string) (*Response, error) { - if validateErr := ValidateUUID(deviceID); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(deviceBasePath, deviceID, "actions") - action := &DeviceActionRequest{Type: "rescue"} - - return s.client.DoRequest("POST", apiPath, action, nil) -} - -type lockType struct { - Locked bool `json:"locked"` -} - -// Lock sets a device to "locked" -func (s *DeviceServiceOp) Lock(deviceID string) (*Response, error) { - if validateErr := ValidateUUID(deviceID); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(deviceBasePath, deviceID) - action := lockType{Locked: true} - - return s.client.DoRequest("PATCH", apiPath, action, nil) -} - -// Unlock sets a device to "unlocked" -func (s *DeviceServiceOp) Unlock(deviceID string) (*Response, error) { - if validateErr := ValidateUUID(deviceID); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(deviceBasePath, deviceID) - action := lockType{Locked: false} - - return s.client.DoRequest("PATCH", apiPath, action, nil) -} - -func (s *DeviceServiceOp) ListBGPNeighbors(deviceID string, opts *ListOptions) ([]BGPNeighbor, *Response, error) { - if validateErr := ValidateUUID(deviceID); validateErr != nil { - return nil, nil, validateErr - } - root := new(bgpNeighborsRoot) - endpointPath := path.Join(deviceBasePath, deviceID, bgpNeighborsBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, root) - if err != nil { - return nil, resp, err - } - - return root.BGPNeighbors, resp, err -} - -// ListBGPSessions returns all BGP Sessions associated with the device -func (s *DeviceServiceOp) ListBGPSessions(deviceID string, opts *ListOptions) (bgpSessions []BGPSession, resp *Response, err error) { - if validateErr := ValidateUUID(deviceID); validateErr != nil { - return nil, nil, validateErr - } - - endpointPath := path.Join(deviceBasePath, deviceID, bgpSessionBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - - for { - subset := new(bgpSessionsRoot) - - resp, err = s.client.DoRequest("GET", apiPathQuery, nil, subset) - if err != nil { - return nil, resp, err - } - - bgpSessions = append(bgpSessions, subset.Sessions...) - - if apiPathQuery = nextPage(subset.Meta, opts); apiPathQuery != "" { - continue - } - return - } -} - -// ListEvents returns list of device events -func (s *DeviceServiceOp) ListEvents(deviceID string, opts *ListOptions) ([]Event, *Response, error) { - if validateErr := ValidateUUID(deviceID); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(deviceBasePath, deviceID, eventBasePath) - - return listEvents(s.client, apiPath, opts) -} diff --git a/vendor/github.com/packethost/packngo/doc.go b/vendor/github.com/packethost/packngo/doc.go deleted file mode 100644 index 52a192a0..00000000 --- a/vendor/github.com/packethost/packngo/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package packngo implements the Equinix Metal API -// documented at https://metal.equinix.com/developers/api. -package packngo diff --git a/vendor/github.com/packethost/packngo/email.go b/vendor/github.com/packethost/packngo/email.go deleted file mode 100644 index 375a4aa0..00000000 --- a/vendor/github.com/packethost/packngo/email.go +++ /dev/null @@ -1,98 +0,0 @@ -package packngo - -import ( - "path" -) - -const emailBasePath = "/emails" - -// EmailRequest type used to add an email address to the current user -type EmailRequest struct { - Address string `json:"address,omitempty"` - Default *bool `json:"default,omitempty"` -} - -// EmailService interface defines available email methods -type EmailService interface { - Get(string, *GetOptions) (*Email, *Response, error) - Create(*EmailRequest) (*Email, *Response, error) - Update(string, *EmailRequest) (*Email, *Response, error) - Delete(string) (*Response, error) -} - -// Email represents a user's email address -type Email struct { - ID string `json:"id"` - Address string `json:"address"` - Default bool `json:"default,omitempty"` - URL string `json:"href,omitempty"` -} - -func (e Email) String() string { - return Stringify(e) -} - -// EmailServiceOp implements EmailService -type EmailServiceOp struct { - client *Client -} - -// Get retrieves an email by id -func (s *EmailServiceOp) Get(emailID string, opts *GetOptions) (*Email, *Response, error) { - if validateErr := ValidateUUID(emailID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(emailBasePath, emailID) - apiPathQuery := opts.WithQuery(endpointPath) - email := new(Email) - - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, email) - if err != nil { - return nil, resp, err - } - - return email, resp, err -} - -// Create adds a new email address to the current user. -func (s *EmailServiceOp) Create(request *EmailRequest) (*Email, *Response, error) { - email := new(Email) - - resp, err := s.client.DoRequest("POST", emailBasePath, request, email) - if err != nil { - return nil, resp, err - } - - return email, resp, err -} - -// Delete removes the email address from the current user account -func (s *EmailServiceOp) Delete(emailID string) (*Response, error) { - if validateErr := ValidateUUID(emailID); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(emailBasePath, emailID) - - resp, err := s.client.DoRequest("DELETE", apiPath, nil, nil) - if err != nil { - return resp, err - } - - return resp, err -} - -// Update email parameters -func (s *EmailServiceOp) Update(emailID string, request *EmailRequest) (*Email, *Response, error) { - if validateErr := ValidateUUID(emailID); validateErr != nil { - return nil, nil, validateErr - } - email := new(Email) - apiPath := path.Join(emailBasePath, emailID) - - resp, err := s.client.DoRequest("PUT", apiPath, request, email) - if err != nil { - return nil, resp, err - } - - return email, resp, err -} diff --git a/vendor/github.com/packethost/packngo/events.go b/vendor/github.com/packethost/packngo/events.go deleted file mode 100644 index c8365436..00000000 --- a/vendor/github.com/packethost/packngo/events.go +++ /dev/null @@ -1,84 +0,0 @@ -package packngo - -import ( - "path" -) - -const eventBasePath = "/events" - -// Event struct -type Event struct { - ID string `json:"id,omitempty"` - State string `json:"state,omitempty"` - Type string `json:"type,omitempty"` - Body string `json:"body,omitempty"` - Relationships []Href `json:"relationships,omitempty"` - Interpolated string `json:"interpolated,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - Href string `json:"href,omitempty"` -} - -type eventsRoot struct { - Events []Event `json:"events,omitempty"` - Meta meta `json:"meta,omitempty"` -} - -// EventService interface defines available event functions -type EventService interface { - List(*ListOptions) ([]Event, *Response, error) - Get(string, *GetOptions) (*Event, *Response, error) -} - -// EventServiceOp implements EventService -type EventServiceOp struct { - client *Client -} - -// List returns all events -func (s *EventServiceOp) List(listOpt *ListOptions) ([]Event, *Response, error) { - return listEvents(s.client, eventBasePath, listOpt) -} - -// Get returns an event by ID -func (s *EventServiceOp) Get(eventID string, getOpt *GetOptions) (*Event, *Response, error) { - if validateErr := ValidateUUID(eventID); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(eventBasePath, eventID) - return get(s.client, apiPath, getOpt) -} - -// list helper function for all event functions -func listEvents(client requestDoer, endpointPath string, opts *ListOptions) (events []Event, resp *Response, err error) { - apiPathQuery := opts.WithQuery(endpointPath) - - for { - subset := new(eventsRoot) - - resp, err = client.DoRequest("GET", apiPathQuery, nil, subset) - if err != nil { - return nil, resp, err - } - - events = append(events, subset.Events...) - - if apiPathQuery = nextPage(subset.Meta, opts); apiPathQuery != "" { - continue - } - return - } - -} - -func get(client *Client, endpointPath string, opts *GetOptions) (*Event, *Response, error) { - event := new(Event) - - apiPathQuery := opts.WithQuery(endpointPath) - - resp, err := client.DoRequest("GET", apiPathQuery, nil, event) - if err != nil { - return nil, resp, err - } - - return event, resp, err -} diff --git a/vendor/github.com/packethost/packngo/fabric_service_tokens.go b/vendor/github.com/packethost/packngo/fabric_service_tokens.go deleted file mode 100644 index da4b9d7a..00000000 --- a/vendor/github.com/packethost/packngo/fabric_service_tokens.go +++ /dev/null @@ -1,42 +0,0 @@ -package packngo - -import "path" - -type FabricServiceTokenType string - -const ( - fabricServiceTokenBasePath = "/fabric-service-tokens" - FabricServiceTokenASide FabricServiceTokenType = "a_side" - FabricServiceTokenZSide FabricServiceTokenType = "z_side" -) - -// FabricServiceToken represents an Equinix Metal metro -type FabricServiceToken struct { - *Href `json:",inline"` - ExpiresAt *Timestamp `json:"expires_at,omitempty"` - ID string `json:"id"` - MaxAllowedSpeed uint64 `json:"max_allowed_speed,omitempty"` - Role ConnectionPortRole `json:"role,omitempty"` - ServiceTokenType FabricServiceTokenType `json:"service_token_type,omitempty"` - State string `json:"state,omitempty"` -} - -func (f FabricServiceToken) String() string { - return Stringify(f) -} - -// FabricServiceTokenServiceOp implements FabricServiceTokenService -type FabricServiceTokenServiceOp struct { - client *Client -} - -func (s *FabricServiceTokenServiceOp) Get(id string, opts *GetOptions) (*FabricServiceToken, *Response, error) { - endpointPath := path.Join(fabricServiceTokenBasePath, id) - apiPathQuery := opts.WithQuery(endpointPath) - fst := new(FabricServiceToken) - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, fst) - if err != nil { - return nil, resp, err - } - return fst, resp, err -} diff --git a/vendor/github.com/packethost/packngo/facilities.go b/vendor/github.com/packethost/packngo/facilities.go deleted file mode 100644 index 12d18aec..00000000 --- a/vendor/github.com/packethost/packngo/facilities.go +++ /dev/null @@ -1,67 +0,0 @@ -package packngo - -const facilityBasePath = "/facilities" - -// FacilityService interface defines available facility methods -type FacilityService interface { - List(*ListOptions) ([]Facility, *Response, error) -} - -type facilityRoot struct { - Facilities []Facility `json:"facilities"` -} - -// Facility represents an Equinix Metal facility -type Facility struct { - ID string `json:"id"` - Name string `json:"name,omitempty"` - Code string `json:"code,omitempty"` - Features []string `json:"features,omitempty"` - Address *Address `json:"address,omitempty"` - Metro *Metro `json:"metro,omitempty"` - URL string `json:"href,omitempty"` -} - -func (f Facility) String() string { - return Stringify(f) -} - -// Coordinates struct for Coordinates -type Coordinates struct { - Latitude *string `json:"latitude,omitempty"` - Longitude *string `json:"longitude,omitempty"` -} - -// Address - the physical address of the facility -type Address struct { - ID string `json:"id,omitempty"` - Address string `json:"address"` - Address2 *string `json:"address2,omitempty"` - City *string `json:"city,omitempty"` - State *string `json:"state,omitempty"` - ZipCode string `json:"zip_code"` - Country string `json:"country"` - Coordinates *Coordinates `json:"coordinates,omitempty"` -} - -func (a Address) String() string { - return Stringify(a) -} - -// FacilityServiceOp implements FacilityService -type FacilityServiceOp struct { - client *Client -} - -// List returns all facilities -func (s *FacilityServiceOp) List(opts *ListOptions) ([]Facility, *Response, error) { - root := new(facilityRoot) - apiPathQuery := opts.WithQuery(facilityBasePath) - - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, root) - if err != nil { - return nil, resp, err - } - - return root.Facilities, resp, err -} diff --git a/vendor/github.com/packethost/packngo/hardware_reservations.go b/vendor/github.com/packethost/packngo/hardware_reservations.go deleted file mode 100644 index da870a35..00000000 --- a/vendor/github.com/packethost/packngo/hardware_reservations.go +++ /dev/null @@ -1,104 +0,0 @@ -package packngo - -import ( - "path" -) - -const hardwareReservationBasePath = "/hardware-reservations" - -// HardwareReservationService interface defines available hardware reservation functions -type HardwareReservationService interface { - Get(hardwareReservationID string, getOpt *GetOptions) (*HardwareReservation, *Response, error) - List(projectID string, listOpt *ListOptions) ([]HardwareReservation, *Response, error) - Move(string, string) (*HardwareReservation, *Response, error) -} - -// HardwareReservationServiceOp implements HardwareReservationService -type HardwareReservationServiceOp struct { - client requestDoer -} - -// HardwareReservation struct -type HardwareReservation struct { - ID string `json:"id,omitempty"` - ShortID string `json:"short_id,omitempty"` - Facility Facility `json:"facility,omitempty"` - Plan Plan `json:"plan,omitempty"` - Provisionable bool `json:"provisionable,omitempty"` - Spare bool `json:"spare,omitempty"` - SwitchUUID string `json:"switch_uuid,omitempty"` - Intervals int `json:"intervals,omitempty"` - CurrentPeriod int `json:"current_period,omitempty"` - Href string `json:"href,omitempty"` - Project Project `json:"project,omitempty"` - Device *Device `json:"device,omitempty"` - CreatedAt Timestamp `json:"created_at,omitempty"` -} - -type hardwareReservationRoot struct { - HardwareReservations []HardwareReservation `json:"hardware_reservations"` - Meta meta `json:"meta"` -} - -// List returns all hardware reservations for a given project -func (s *HardwareReservationServiceOp) List(projectID string, opts *ListOptions) (reservations []HardwareReservation, resp *Response, err error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(projectBasePath, projectID, hardwareReservationBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - - for { - subset := new(hardwareReservationRoot) - - resp, err = s.client.DoRequest("GET", apiPathQuery, nil, subset) - if err != nil { - return nil, resp, err - } - - reservations = append(reservations, subset.HardwareReservations...) - if apiPathQuery = nextPage(subset.Meta, opts); apiPathQuery != "" { - continue - } - return - } -} - -// Get returns a single hardware reservation -func (s *HardwareReservationServiceOp) Get(hardwareReservationdID string, opts *GetOptions) (*HardwareReservation, *Response, error) { - if validateErr := ValidateUUID(hardwareReservationdID); validateErr != nil { - return nil, nil, validateErr - } - hardwareReservation := new(HardwareReservation) - - endpointPath := path.Join(hardwareReservationBasePath, hardwareReservationdID) - apiPathQuery := opts.WithQuery(endpointPath) - - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, hardwareReservation) - if err != nil { - return nil, resp, err - } - - return hardwareReservation, resp, err -} - -// Move a hardware reservation to another project -func (s *HardwareReservationServiceOp) Move(hardwareReservationdID, projectID string) (*HardwareReservation, *Response, error) { - if validateErr := ValidateUUID(hardwareReservationdID); validateErr != nil { - return nil, nil, validateErr - } - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - hardwareReservation := new(HardwareReservation) - apiPath := path.Join(hardwareReservationBasePath, hardwareReservationdID, "move") - body := map[string]string{} - body["project_id"] = projectID - - resp, err := s.client.DoRequest("POST", apiPath, body, hardwareReservation) - if err != nil { - return nil, resp, err - } - - return hardwareReservation, resp, err -} diff --git a/vendor/github.com/packethost/packngo/invitations.go b/vendor/github.com/packethost/packngo/invitations.go deleted file mode 100644 index ef39eea8..00000000 --- a/vendor/github.com/packethost/packngo/invitations.go +++ /dev/null @@ -1,155 +0,0 @@ -package packngo - -import ( - "path" -) - -const ( - invitationsBasePath = "/invitations" -) - -// InvitationService interface defines available invitation methods -type InvitationService interface { - Create(string, *InvitationCreateRequest, *GetOptions) (*Invitation, *Response, error) - List(string, *ListOptions) ([]Invitation, *Response, error) - Get(string, *GetOptions) (*Invitation, *Response, error) - Accept(string, *InvitationUpdateRequest) (*Invitation, *Response, error) - Resend(string) (*Invitation, *Response, error) - Delete(string) (*Response, error) -} - -type invitationsRoot struct { - Invitations []Invitation `json:"invitations"` - Meta meta `json:"meta"` -} - -// Invitation represents an Equinix Metal invitation -type Invitation struct { - *Href `json:",inline"` - ID string `json:"id,omitempty"` - Invitation Href `json:"invitation,omitempty"` - InvitedBy Href `json:"invited_by,omitempty"` - Invitee string `json:"invitee,omitempty"` - Nonce string `json:"nonce,omitempty"` - Organization Href `json:"organization,omitempty"` - Projects []Href `json:"projects,omitempty"` - Roles []string `json:"roles,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` -} - -// InvitationCreateRequest struct for InvitationService.Create -type InvitationCreateRequest struct { - // Invitee is the email address of the recipient - Invitee string `json:"invitee"` - Message string `json:"message,omitempty"` - ProjectsIDs []string `json:"projects_ids,omitempty"` - Roles []string `json:"roles,omitempty"` -} - -// InvitationUpdateRequest struct for InvitationService.Update -type InvitationUpdateRequest struct{} - -func (u Invitation) String() string { - return Stringify(u) -} - -// InvitationServiceOp implements InvitationService -type InvitationServiceOp struct { - client *Client -} - -var _ InvitationService = (*InvitationServiceOp)(nil) - -// Lists open invitations to the project -func (s *InvitationServiceOp) List(organizationID string, opts *ListOptions) (invitations []Invitation, resp *Response, err error) { - endpointPath := path.Join(organizationBasePath, organizationID, invitationsBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - - for { - subset := new(invitationsRoot) - - resp, err = s.client.DoRequest("GET", apiPathQuery, nil, subset) - if err != nil { - return nil, resp, err - } - - invitations = append(invitations, subset.Invitations...) - - if apiPathQuery = nextPage(subset.Meta, opts); apiPathQuery != "" { - continue - } - return - } -} - -// Create a Invitation with the given InvitationCreateRequest. New invitation VerificationStage -// will be AccountCreated, unless InvitationCreateRequest contains an valid -// InvitationID and Nonce in which case the VerificationStage will be Verified. -func (s *InvitationServiceOp) Create(organizationID string, createRequest *InvitationCreateRequest, opts *GetOptions) (*Invitation, *Response, error) { - endpointPath := path.Join(organizationBasePath, organizationID, invitationsBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - invitation := new(Invitation) - - resp, err := s.client.DoRequest("POST", apiPathQuery, createRequest, invitation) - if err != nil { - return nil, resp, err - } - - return invitation, resp, err -} - -func (s *InvitationServiceOp) Get(invitationID string, opts *GetOptions) (*Invitation, *Response, error) { - if validateErr := ValidateUUID(invitationID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(invitationsBasePath, invitationID) - apiPathQuery := opts.WithQuery(endpointPath) - invitation := new(Invitation) - - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, invitation) - if err != nil { - return nil, resp, err - } - - return invitation, resp, err -} - -// Update updates the current invitation -func (s *InvitationServiceOp) Delete(id string) (*Response, error) { - opts := &GetOptions{} - endpointPath := path.Join(invitationsBasePath, id) - apiPathQuery := opts.WithQuery(endpointPath) - - return s.client.DoRequest("DELETE", apiPathQuery, nil, nil) -} - -// Update updates the current invitation -func (s *InvitationServiceOp) Accept(id string, updateRequest *InvitationUpdateRequest) (*Invitation, *Response, error) { - opts := &GetOptions{} - endpointPath := path.Join(invitationsBasePath, id) - apiPathQuery := opts.WithQuery(endpointPath) - invitation := new(Invitation) - - resp, err := s.client.DoRequest("PUT", apiPathQuery, updateRequest, invitation) - if err != nil { - return nil, resp, err - } - - return invitation, resp, err -} - -// Update updates the current invitation -func (s *InvitationServiceOp) Resend(id string) (*Invitation, *Response, error) { - opts := &GetOptions{} - endpointPath := path.Join(invitationsBasePath, id) - apiPathQuery := opts.WithQuery(endpointPath) - invitation := new(Invitation) - - resp, err := s.client.DoRequest("POST", apiPathQuery, nil, invitation) - if err != nil { - return nil, resp, err - } - - return invitation, resp, err -} diff --git a/vendor/github.com/packethost/packngo/ip.go b/vendor/github.com/packethost/packngo/ip.go deleted file mode 100644 index 90a1a5c7..00000000 --- a/vendor/github.com/packethost/packngo/ip.go +++ /dev/null @@ -1,391 +0,0 @@ -package packngo - -import ( - "path" - "strconv" -) - -const ipBasePath = "/ips" - -const ( - // PublicIPv4 fixed string representation of public ipv4 - PublicIPv4 IPReservationType = "public_ipv4" - // PrivateIPv4 fixed string representation of private ipv4 - PrivateIPv4 IPReservationType = "private_ipv4" - // GlobalIPv4 fixed string representation of global ipv4 - GlobalIPv4 IPReservationType = "global_ipv4" - // PublicIPv6 fixed string representation of public ipv6 - PublicIPv6 IPReservationType = "public_ipv6" - // PrivateIPv6 fixed string representation of private ipv6 - PrivateIPv6 IPReservationType = "private_ipv6" - // GlobalIPv6 fixed string representation of global ipv6 - GlobalIPv6 IPReservationType = "global_ipv6" - // VRFIPRange fixed string representation of vrf (virtual routing and forwarding). This may be any VRF supported range, including public and RFC-1918 IPv4 and IPv6 ranges. - VRFIPRange IPReservationType = "vrf" -) - -type IPReservationType string - -// DeviceIPService handles assignment of addresses from reserved blocks to instances in a project. -type DeviceIPService interface { - Assign(deviceID string, assignRequest *AddressStruct) (*IPAddressAssignment, *Response, error) - Unassign(assignmentID string) (*Response, error) - Get(assignmentID string, getOpt *GetOptions) (*IPAddressAssignment, *Response, error) - List(deviceID string, opts *ListOptions) ([]IPAddressAssignment, *Response, error) -} - -// ProjectIPService handles reservation of IP address blocks for a project. -type ProjectIPService interface { - Get(reservationID string, getOpt *GetOptions) (*IPAddressReservation, *Response, error) - List(projectID string, opts *ListOptions) ([]IPAddressReservation, *Response, error) - // Deprecated Use Create instead of Request - Request(projectID string, ipReservationReq *IPReservationRequest) (*IPAddressReservation, *Response, error) - Create(projectID string, ipReservationReq *IPReservationCreateRequest) (*IPAddressReservation, *Response, error) - Delete(ipReservationID string) (*Response, error) - // Deprecated Use Delete instead of Remove - Remove(ipReservationID string) (*Response, error) - Update(assignmentID string, updateRequest *IPAddressUpdateRequest, opt *GetOptions) (*IPAddressReservation, *Response, error) - AvailableAddresses(ipReservationID string, r *AvailableRequest) ([]string, *Response, error) -} - -var ( - _ DeviceIPService = (*DeviceIPServiceOp)(nil) - _ ProjectIPService = (*ProjectIPServiceOp)(nil) -) - -type IpAddressCommon struct { //nolint:golint - ID string `json:"id"` - Address string `json:"address"` - Gateway string `json:"gateway"` - Network string `json:"network"` - AddressFamily int `json:"address_family"` - Netmask string `json:"netmask"` - Public bool `json:"public"` - CIDR int `json:"cidr"` - Created string `json:"created_at,omitempty"` - Updated string `json:"updated_at,omitempty"` - Href string `json:"href"` - Management bool `json:"management"` - Manageable bool `json:"manageable"` - Metro *Metro `json:"metro,omitempty"` - Project Href `json:"project"` - Global bool `json:"global_ip"` - Tags []string `json:"tags,omitempty"` - ParentBlock *ParentBlock `json:"parent_block,omitempty"` - CustomData interface{} `json:"customdata,omitempty"` - Type IPReservationType `json:"type"` - VRF *VRF `json:"vrf,omitempty"` -} - -// ParentBlock is the network block for the parent of an IP address -type ParentBlock struct { - Network string `json:"network"` - Netmask string `json:"netmask"` - CIDR int `json:"cidr"` - Href *string `json:"href,omitempty"` -} - -type IPReservationState string - -const ( - // IPReservationStatePending fixed string representation of pending - IPReservationStatePending IPReservationState = "pending" - - // IPReservationStateCreated fixed string representation of created - IPReservationStateCreated IPReservationState = "created" - - // IPReservationStateDenied fixed string representation of denied - IPReservationStateDenied IPReservationState = "denied" -) - -// IPAddressReservation is created when user sends IP reservation request for a project (considering it's within quota). -type IPAddressReservation struct { - IpAddressCommon - Assignments []*IPAddressAssignment `json:"assignments"` - Facility *Facility `json:"facility,omitempty"` - Available string `json:"available"` - Addon bool `json:"addon"` - Bill bool `json:"bill"` - State IPReservationState `json:"state"` - Description *string `json:"details"` - Enabled bool `json:"enabled"` - MetalGateway *MetalGatewayLite `json:"metal_gateway,omitempty"` - RequestedBy *UserLite `json:"requested_by,omitempty"` -} - -// AvailableResponse is a type for listing of available addresses from a reserved block. -type AvailableResponse struct { - Available []string `json:"available"` -} - -// AvailableRequest is a type for listing available addresses from a reserved block. -type AvailableRequest struct { - CIDR int `json:"cidr"` -} - -// IPAddressAssignment is created when an IP address from reservation block is assigned to a device. -type IPAddressAssignment struct { - IpAddressCommon - AssignedTo Href `json:"assigned_to"` -} - -// IPAddressUpdateRequest represents the body of an IPAddress patch -type IPAddressUpdateRequest struct { - Tags *[]string `json:"tags,omitempty"` - Description *string `json:"details,omitempty"` - CustomData interface{} `json:"customdata,omitempty"` -} - -// IPReservationRequest represents the body of an IP reservation request -// Deprecated: use IPReservationCreateRequest -type IPReservationRequest = IPReservationCreateRequest - -// IPReservationCreateRequest represents the body of an IP reservation request. -type IPReservationCreateRequest struct { - // Type of IP reservation. - Type IPReservationType `json:"type"` - Quantity int `json:"quantity"` - Description string `json:"details,omitempty"` - Facility *string `json:"facility,omitempty"` - Metro *string `json:"metro,omitempty"` - Tags []string `json:"tags,omitempty"` - CustomData interface{} `json:"customdata,omitempty"` - // FailOnApprovalRequired if the IP request cannot be approved - // automatically, rather than sending to the longer Equinix Metal approval - // process, fail immediately with a 422 error - FailOnApprovalRequired bool `json:"fail_on_approval_required,omitempty"` - - // Comments in support of the request for additional addresses when the - // request must be manually approved. - Comments string `json:"comments,omitempty"` - - // VRFID is the ID of the VRF to associate and draw the IP range from. - // * Required when Type is VRFIPRange, not valid otherwise - // * Network and CIDR are required when set - // * Metro and Facility are not required when set - VRFID string `json:"vrf_id,omitempty"` - - // Network an unreserved network address from an existing VRF ip_range. - // * Required when Type is VRFIPRange, not valid otherwise - Network string `json:"network,omitempty"` - - // CIDR the size of the network to reserve from an existing VRF ip_range. - // * Required when Type is VRFIPRange, not valid otherwise - // * Minimum range is 22-29, with 30-31 supported and necessary for virtual-circuits - CIDR int `json:"cidr,omitempty"` -} - -// AddressStruct is a helper type for request/response with dict like {"address": ... } -type AddressStruct struct { - Address string `json:"address"` -} - -func deleteFromIP(client *Client, resourceID string) (*Response, error) { - if validateErr := ValidateUUID(resourceID); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(ipBasePath, resourceID) - - return client.DoRequest("DELETE", apiPath, nil, nil) -} - -func (i IPAddressReservation) String() string { - return Stringify(i) -} - -func (i IPAddressAssignment) String() string { - return Stringify(i) -} - -// DeviceIPServiceOp is interface for IP-address assignment methods. -type DeviceIPServiceOp struct { - client *Client -} - -// Unassign unassigns an IP address from the device to which it is currently assigned. -// This will remove the relationship between an IP and the device and will make the IP -// address available to be assigned to another device. -func (i *DeviceIPServiceOp) Unassign(assignmentID string) (*Response, error) { - if validateErr := ValidateUUID(assignmentID); validateErr != nil { - return nil, validateErr - } - return deleteFromIP(i.client, assignmentID) -} - -// Assign assigns an IP address to a device. -// The IP address must be in one of the IP ranges assigned to the device’s project. -func (i *DeviceIPServiceOp) Assign(deviceID string, assignRequest *AddressStruct) (*IPAddressAssignment, *Response, error) { - if validateErr := ValidateUUID(deviceID); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(deviceBasePath, deviceID, ipBasePath) - ipa := new(IPAddressAssignment) - - resp, err := i.client.DoRequest("POST", apiPath, assignRequest, ipa) - if err != nil { - return nil, resp, err - } - - return ipa, resp, err -} - -// Get returns assignment by ID. -func (i *DeviceIPServiceOp) Get(assignmentID string, opts *GetOptions) (*IPAddressAssignment, *Response, error) { - if validateErr := ValidateUUID(assignmentID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(ipBasePath, assignmentID) - apiPathQuery := opts.WithQuery(endpointPath) - ipa := new(IPAddressAssignment) - - resp, err := i.client.DoRequest("GET", apiPathQuery, nil, ipa) - if err != nil { - return nil, resp, err - } - - return ipa, resp, err -} - -// List list all of the IP address assignments on a device -func (i *DeviceIPServiceOp) List(deviceID string, opts *ListOptions) ([]IPAddressAssignment, *Response, error) { - if validateErr := ValidateUUID(deviceID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(deviceBasePath, deviceID, ipBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - - // ipList represents collection of IP Address reservations - type ipList struct { - IPs []IPAddressAssignment `json:"ip_addresses,omitempty"` - } - - ips := new(ipList) - - resp, err := i.client.DoRequest("GET", apiPathQuery, nil, ips) - if err != nil { - return nil, resp, err - } - - return ips.IPs, resp, err -} - -// ProjectIPServiceOp is interface for IP assignment methods. -type ProjectIPServiceOp struct { - client *Client -} - -// Get returns reservation by ID. -func (i *ProjectIPServiceOp) Get(reservationID string, opts *GetOptions) (*IPAddressReservation, *Response, error) { - if validateErr := ValidateUUID(reservationID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(ipBasePath, reservationID) - apiPathQuery := opts.WithQuery(endpointPath) - ipr := new(IPAddressReservation) - - resp, err := i.client.DoRequest("GET", apiPathQuery, nil, ipr) - if err != nil { - return nil, resp, err - } - - return ipr, resp, err -} - -// List provides a list of IP resevations for a single project. -// opts be filtered to limit the type of reservations returned: -// opts.Filter("type", "vrf") -func (i *ProjectIPServiceOp) List(projectID string, opts *ListOptions) ([]IPAddressReservation, *Response, error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(projectBasePath, projectID, ipBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - reservations := new(struct { - Reservations []IPAddressReservation `json:"ip_addresses"` - }) - - resp, err := i.client.DoRequest("GET", apiPathQuery, nil, reservations) - if err != nil { - return nil, resp, err - } - return reservations.Reservations, resp, nil -} - -// Create creates a request for more IP space for a project in order to have -// additional IP addresses to assign to devices. -func (i *ProjectIPServiceOp) Create(projectID string, ipReservationReq *IPReservationCreateRequest) (*IPAddressReservation, *Response, error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(projectBasePath, projectID, ipBasePath) - ipr := new(IPAddressReservation) - - resp, err := i.client.DoRequest("POST", apiPath, ipReservationReq, ipr) - if err != nil { - return nil, resp, err - } - return ipr, resp, err -} - -// Request requests more IP space for a project in order to have additional IP -// addresses to assign to devices. -// -// Deprecated: Use Create instead. -func (i *ProjectIPServiceOp) Request(projectID string, ipReservationReq *IPReservationRequest) (*IPAddressReservation, *Response, error) { - return i.Create(projectID, ipReservationReq) -} - -// Update updates an existing IP reservation. -func (i *ProjectIPServiceOp) Update(reservationID string, updateRequest *IPAddressUpdateRequest, opts *GetOptions) (*IPAddressReservation, *Response, error) { - if validateErr := ValidateUUID(reservationID); validateErr != nil { - return nil, nil, validateErr - } - if opts == nil { - opts = &GetOptions{} - } - endpointPath := path.Join(ipBasePath, reservationID) - apiPathQuery := opts.WithQuery(endpointPath) - ipr := new(IPAddressReservation) - - resp, err := i.client.DoRequest("PATCH", apiPathQuery, updateRequest, ipr) - if err != nil { - return nil, resp, err - } - - return ipr, resp, err -} - -// Delete removes the requests for specific IP within a project -func (i *ProjectIPServiceOp) Delete(ipReservationID string) (*Response, error) { - if validateErr := ValidateUUID(ipReservationID); validateErr != nil { - return nil, validateErr - } - return deleteFromIP(i.client, ipReservationID) -} - -// Remove removes an IP reservation from the project. -// Deprecated: Use Delete instead. -func (i *ProjectIPServiceOp) Remove(ipReservationID string) (*Response, error) { - return i.Delete(ipReservationID) -} - -// AvailableAddresses lists addresses available from a reserved block -func (i *ProjectIPServiceOp) AvailableAddresses(ipReservationID string, r *AvailableRequest) ([]string, *Response, error) { - if validateErr := ValidateUUID(ipReservationID); validateErr != nil { - return nil, nil, validateErr - } - - opts := &GetOptions{} - opts = opts.Filter("cidr", strconv.Itoa(r.CIDR)) - - endpointPath := path.Join(ipBasePath, ipReservationID, "available") - apiPathQuery := opts.WithQuery(endpointPath) - - ar := new(AvailableResponse) - - resp, err := i.client.DoRequest("GET", apiPathQuery, r, ar) - if err != nil { - return nil, resp, err - } - return ar.Available, resp, nil -} diff --git a/vendor/github.com/packethost/packngo/members.go b/vendor/github.com/packethost/packngo/members.go deleted file mode 100644 index 6ce6c1c3..00000000 --- a/vendor/github.com/packethost/packngo/members.go +++ /dev/null @@ -1,66 +0,0 @@ -package packngo - -import "path" - -// API documentation https://metal.equinix.com/developers/api#tag/Memberships -const membersBasePath = "/members" - -// OrganizationService interface defines available organization methods -type MemberService interface { - List(string, *ListOptions) ([]Member, *Response, error) - Delete(string, string) (*Response, error) -} - -type membersRoot struct { - Members []Member `json:"members"` - Meta meta `json:"meta"` -} - -// Member is the returned from organization/id/members -type Member struct { - *Href `json:",inline"` - ID string `json:"id"` - Roles []string `json:"roles"` - ProjectsCount int `json:"projects_count"` - User User `json:"user"` - Organization Organization `json:"organization"` - Projects []Project `json:"projects"` -} - -// MemberServiceOp implements MemberService -type MemberServiceOp struct { - client *Client -} - -var _ MemberService = (*MemberServiceOp)(nil) - -// List returns the members in an organization -func (s *MemberServiceOp) List(organizationID string, opts *ListOptions) (orgs []Member, resp *Response, err error) { - subset := new(membersRoot) - endpointPath := path.Join(organizationBasePath, organizationID, membersBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - - for { - resp, err = s.client.DoRequest("GET", apiPathQuery, nil, subset) - if err != nil { - return nil, resp, err - } - - orgs = append(orgs, subset.Members...) - - if apiPathQuery = nextPage(subset.Meta, opts); apiPathQuery != "" { - continue - } - return - } -} - -// Delete removes the given member from the given organization -func (s *MemberServiceOp) Delete(organizationID, memberID string) (*Response, error) { - if validateErr := ValidateUUID(organizationID); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(organizationBasePath, organizationID, membersBasePath, memberID) - - return s.client.DoRequest("DELETE", apiPath, nil, nil) -} diff --git a/vendor/github.com/packethost/packngo/metal_gateway.go b/vendor/github.com/packethost/packngo/metal_gateway.go deleted file mode 100644 index b4851d22..00000000 --- a/vendor/github.com/packethost/packngo/metal_gateway.go +++ /dev/null @@ -1,136 +0,0 @@ -package packngo - -import ( - "path" -) - -type MetalGatewayState string - -const ( - metalGatewayBasePath = "/metal-gateways" - MetalGatewayActive MetalGatewayState = "active" - MetalGatewayReady MetalGatewayState = "ready" - MetalGatewayDeleting MetalGatewayState = "deleting" -) - -type MetalGatewayService interface { - List(projectID string, opts *ListOptions) ([]MetalGateway, *Response, error) - Create(projectID string, input *MetalGatewayCreateRequest) (*MetalGateway, *Response, error) - Get(metalGatewayID string, opts *GetOptions) (*MetalGateway, *Response, error) - Delete(metalGatewayID string) (*Response, error) -} - -type MetalGateway struct { - ID string `json:"id"` - State MetalGatewayState `json:"state"` - Project *Project `json:"project,omitempty"` - VirtualNetwork *VirtualNetwork `json:"virtual_network,omitempty"` - IPReservation *IPAddressReservation `json:"ip_reservation,omitempty"` - Href string `json:"href"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` - VRF *VRF `json:"vrf,omitempty"` -} - -// MetalGatewayLite struct representation of a Metal Gateway -type MetalGatewayLite struct { - ID string `json:"id,omitempty"` - // The current state of the Metal Gateway. 'Ready' indicates the gateway record has been configured, but is currently not active on the network. 'Active' indicates the gateway has been configured on the network. 'Deleting' is a temporary state used to indicate that the gateway is in the process of being un-configured from the network, after which the gateway record will be deleted. - State string `json:"state,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - // The gateway address with subnet CIDR value for this Metal Gateway. For example, a Metal Gateway using an IP reservation with block 10.1.2.0/27 would have a gateway address of 10.1.2.1/27. - GatewayAddress string `json:"gateway_address,omitempty"` - // The VLAN id of the Virtual Network record associated to this Metal Gateway. Example: 1001. - VLAN int `json:"vlan,omitempty"` - Href string `json:"href,omitempty"` -} - -type MetalGatewayServiceOp struct { - client *Client -} - -func (s *MetalGatewayServiceOp) List(projectID string, opts *ListOptions) (metalGateways []MetalGateway, resp *Response, err error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - type metalGatewaysRoot struct { - MetalGateways []MetalGateway `json:"metal_gateways"` - Meta meta `json:"meta"` - } - - endpointPath := path.Join(projectBasePath, projectID, metalGatewayBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - - for { - subset := new(metalGatewaysRoot) - - resp, err = s.client.DoRequest("GET", apiPathQuery, nil, subset) - if err != nil { - return nil, resp, err - } - - metalGateways = append(metalGateways, subset.MetalGateways...) - - if apiPathQuery = nextPage(subset.Meta, opts); apiPathQuery != "" { - continue - } - return - } -} - -type MetalGatewayCreateRequest struct { - // VirtualNetworkID virtual network UUID. - VirtualNetworkID string `json:"virtual_network_id"` - - // IPReservationID (optional) IP Reservation UUID (Public or VRF). Required for VRF. - IPReservationID string `json:"ip_reservation_id,omitempty"` - - // PrivateIPv4SubnetSize (optional) Power of 2 between 8 and 128 (8, 16, 32, 64, 128). Invalid for VRF. - PrivateIPv4SubnetSize int `json:"private_ipv4_subnet_size,omitempty"` -} - -func (s *MetalGatewayServiceOp) Get(metalGatewayID string, opts *GetOptions) (*MetalGateway, *Response, error) { - if validateErr := ValidateUUID(metalGatewayID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(metalGatewayBasePath, metalGatewayID) - apiPathQuery := opts.WithQuery(endpointPath) - metalGateway := new(MetalGateway) - - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, metalGateway) - if err != nil { - return nil, resp, err - } - - return metalGateway, resp, err -} - -func (s *MetalGatewayServiceOp) Create(projectID string, input *MetalGatewayCreateRequest) (*MetalGateway, *Response, error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(projectBasePath, projectID, metalGatewayBasePath) - output := new(MetalGateway) - - resp, err := s.client.DoRequest("POST", apiPath, input, output) - if err != nil { - return nil, nil, err - } - - return output, resp, nil -} - -func (s *MetalGatewayServiceOp) Delete(metalGatewayID string) (*Response, error) { - if validateErr := ValidateUUID(metalGatewayID); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(metalGatewayBasePath, metalGatewayID) - - resp, err := s.client.DoRequest("DELETE", apiPath, nil, nil) - if err != nil { - return nil, err - } - - return resp, nil -} diff --git a/vendor/github.com/packethost/packngo/metros.go b/vendor/github.com/packethost/packngo/metros.go deleted file mode 100644 index 2a3924dc..00000000 --- a/vendor/github.com/packethost/packngo/metros.go +++ /dev/null @@ -1,42 +0,0 @@ -package packngo - -const metroBasePath = "/locations/metros" - -// MetroService interface defines available metro methods -type MetroService interface { - List(*ListOptions) ([]Metro, *Response, error) -} - -type metroRoot struct { - Metros []Metro `json:"metros"` -} - -// Metro represents an Equinix Metal metro -type Metro struct { - ID string `json:"id"` - Name string `json:"name,omitempty"` - Code string `json:"code,omitempty"` - Country string `json:"country,omitempty"` -} - -func (f Metro) String() string { - return Stringify(f) -} - -// MetroServiceOp implements MetroService -type MetroServiceOp struct { - client *Client -} - -// List returns all metros -func (s *MetroServiceOp) List(opts *ListOptions) ([]Metro, *Response, error) { - root := new(metroRoot) - apiPathQuery := opts.WithQuery(metroBasePath) - - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, root) - if err != nil { - return nil, resp, err - } - - return root.Metros, resp, err -} diff --git a/vendor/github.com/packethost/packngo/notifications.go b/vendor/github.com/packethost/packngo/notifications.go deleted file mode 100644 index bdefa1bd..00000000 --- a/vendor/github.com/packethost/packngo/notifications.go +++ /dev/null @@ -1,100 +0,0 @@ -package packngo - -import ( - "path" -) - -const notificationBasePath = "/notifications" - -// Notification struct -type Notification struct { - ID string `json:"id,omitempty"` - Type string `json:"type,omitempty"` - Body string `json:"body,omitempty"` - Severity string `json:"severity,omitempty"` - Read bool `json:"read,omitempty"` - Context string `json:"context,omitempty"` - CreatedAt Timestamp `json:"created_at,omitempty"` - UpdatedAt Timestamp `json:"updated_at,omitempty"` - User Href `json:"user,omitempty"` - Href string `json:"href,omitempty"` -} - -type notificationsRoot struct { - Notifications []Notification `json:"notifications,omitempty"` - Meta meta `json:"meta,omitempty"` -} - -// NotificationService interface defines available event functions -type NotificationService interface { - List(*ListOptions) ([]Notification, *Response, error) - Get(string, *GetOptions) (*Notification, *Response, error) - MarkAsRead(string) (*Notification, *Response, error) -} - -// NotificationServiceOp implements NotificationService -type NotificationServiceOp struct { - client *Client -} - -// List returns all notifications -func (s *NotificationServiceOp) List(listOpt *ListOptions) ([]Notification, *Response, error) { - return listNotifications(s.client, notificationBasePath, listOpt) -} - -// Get returns a notification by ID -func (s *NotificationServiceOp) Get(notificationID string, opts *GetOptions) (*Notification, *Response, error) { - if validateErr := ValidateUUID(notificationID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(notificationBasePath, notificationID) - apiPathQuery := opts.WithQuery(endpointPath) - return getNotifications(s.client, apiPathQuery) -} - -// Marks notification as read by ID -func (s *NotificationServiceOp) MarkAsRead(notificationID string) (*Notification, *Response, error) { - if validateErr := ValidateUUID(notificationID); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(notificationBasePath, notificationID) - return markAsRead(s.client, apiPath) -} - -// list helper function for all notification functions -func listNotifications(client *Client, endpointPath string, opts *ListOptions) ([]Notification, *Response, error) { - root := new(notificationsRoot) - - apiPathQuery := opts.WithQuery(endpointPath) - - resp, err := client.DoRequest("GET", apiPathQuery, nil, root) - if err != nil { - return nil, resp, err - } - - return root.Notifications, resp, err -} - -func getNotifications(client *Client, apiPath string) (*Notification, *Response, error) { - - notification := new(Notification) - - resp, err := client.DoRequest("GET", apiPath, nil, notification) - if err != nil { - return nil, resp, err - } - - return notification, resp, err -} - -func markAsRead(client *Client, apiPath string) (*Notification, *Response, error) { - - notification := new(Notification) - - resp, err := client.DoRequest("PUT", apiPath, nil, notification) - if err != nil { - return nil, resp, err - } - - return notification, resp, err -} diff --git a/vendor/github.com/packethost/packngo/operatingsystems.go b/vendor/github.com/packethost/packngo/operatingsystems.go deleted file mode 100644 index 087fba6c..00000000 --- a/vendor/github.com/packethost/packngo/operatingsystems.go +++ /dev/null @@ -1,42 +0,0 @@ -package packngo - -const osBasePath = "/operating-systems" - -// OSService interface defines available operating_systems methods -type OSService interface { - List() ([]OS, *Response, error) -} - -type osRoot struct { - OperatingSystems []OS `json:"operating_systems"` -} - -// OS represents an Equinix Metal operating system -type OS struct { - Name string `json:"name"` - Slug string `json:"slug"` - Distro string `json:"distro"` - Version string `json:"version"` - ProvisionableOn []string `json:"provisionable_on"` -} - -func (o OS) String() string { - return Stringify(o) -} - -// OSServiceOp implements OSService -type OSServiceOp struct { - client *Client -} - -// List returns all available operating systems -func (s *OSServiceOp) List() ([]OS, *Response, error) { - root := new(osRoot) - - resp, err := s.client.DoRequest("GET", osBasePath, nil, root) - if err != nil { - return nil, resp, err - } - - return root.OperatingSystems, resp, err -} diff --git a/vendor/github.com/packethost/packngo/organizations.go b/vendor/github.com/packethost/packngo/organizations.go deleted file mode 100644 index c4e2c77f..00000000 --- a/vendor/github.com/packethost/packngo/organizations.go +++ /dev/null @@ -1,186 +0,0 @@ -package packngo - -import ( - "path" -) - -// API documentation https://metal.equinix.com/developers/api/organizations/ -const organizationBasePath = "/organizations" - -// OrganizationService interface defines available organization methods -type OrganizationService interface { - List(*ListOptions) ([]Organization, *Response, error) - Get(string, *GetOptions) (*Organization, *Response, error) - Create(*OrganizationCreateRequest) (*Organization, *Response, error) - Update(string, *OrganizationUpdateRequest) (*Organization, *Response, error) - Delete(string) (*Response, error) - ListPaymentMethods(string) ([]PaymentMethod, *Response, error) - ListEvents(string, *ListOptions) ([]Event, *Response, error) -} - -type organizationsRoot struct { - Organizations []Organization `json:"organizations"` - Meta meta `json:"meta"` -} - -// Organization represents an Equinix Metal organization -type Organization struct { - ID string `json:"id"` - Name string `json:"name,omitempty"` - Description string `json:"description,omitempty"` - Website string `json:"website,omitempty"` - Twitter string `json:"twitter,omitempty"` - Created string `json:"created_at,omitempty"` - Updated string `json:"updated_at,omitempty"` - Address Address `json:"address,omitempty"` - TaxID string `json:"tax_id,omitempty"` - MainPhone string `json:"main_phone,omitempty"` - BillingPhone string `json:"billing_phone,omitempty"` - CreditAmount float64 `json:"credit_amount,omitempty"` - Logo string `json:"logo,omitempty"` - LogoThumb string `json:"logo_thumb,omitempty"` - Projects []Project `json:"projects,omitempty"` - URL string `json:"href,omitempty"` - Members []Member `json:"members,omitempty"` - Owners []User `json:"owners,omitempty"` - PrimaryOwner User `json:"primary_owner,omitempty"` -} - -func (o Organization) String() string { - return Stringify(o) -} - -// OrganizationCreateRequest type used to create an Equinix Metal organization -type OrganizationCreateRequest struct { - Name string `json:"name"` - Description string `json:"description,omitempty"` - Website string `json:"website,omitempty"` - Twitter string `json:"twitter,omitempty"` - Logo string `json:"logo,omitempty"` - Address Address `json:"address,omitempty"` -} - -func (o OrganizationCreateRequest) String() string { - return Stringify(o) -} - -// OrganizationUpdateRequest type used to update an Equinix Metal organization -type OrganizationUpdateRequest struct { - Name *string `json:"name,omitempty"` - Description *string `json:"description,omitempty"` - Website *string `json:"website,omitempty"` - Twitter *string `json:"twitter,omitempty"` - Logo *string `json:"logo,omitempty"` - Address *Address `json:"address,omitempty"` -} - -func (o OrganizationUpdateRequest) String() string { - return Stringify(o) -} - -// OrganizationServiceOp implements OrganizationService -type OrganizationServiceOp struct { - client *Client -} - -// List returns the user's organizations -func (s *OrganizationServiceOp) List(opts *ListOptions) (orgs []Organization, resp *Response, err error) { - subset := new(organizationsRoot) - - apiPathQuery := opts.WithQuery(organizationBasePath) - - for { - resp, err = s.client.DoRequest("GET", apiPathQuery, nil, subset) - if err != nil { - return nil, resp, err - } - - orgs = append(orgs, subset.Organizations...) - - if apiPathQuery = nextPage(subset.Meta, opts); apiPathQuery != "" { - continue - } - return - } -} - -// Get returns a organization by id -func (s *OrganizationServiceOp) Get(organizationID string, opts *GetOptions) (*Organization, *Response, error) { - if validateErr := ValidateUUID(organizationID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(organizationBasePath, organizationID) - apiPathQuery := opts.WithQuery(endpointPath) - organization := new(Organization) - - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, organization) - if err != nil { - return nil, resp, err - } - - return organization, resp, err -} - -// Create creates a new organization -func (s *OrganizationServiceOp) Create(createRequest *OrganizationCreateRequest) (*Organization, *Response, error) { - organization := new(Organization) - - resp, err := s.client.DoRequest("POST", organizationBasePath, createRequest, organization) - if err != nil { - return nil, resp, err - } - - return organization, resp, err -} - -// Update updates an organization -func (s *OrganizationServiceOp) Update(id string, updateRequest *OrganizationUpdateRequest) (*Organization, *Response, error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(organizationBasePath, id) - organization := new(Organization) - - resp, err := s.client.DoRequest("PATCH", apiPath, updateRequest, organization) - if err != nil { - return nil, resp, err - } - - return organization, resp, err -} - -// Delete deletes an organizationID -func (s *OrganizationServiceOp) Delete(organizationID string) (*Response, error) { - if validateErr := ValidateUUID(organizationID); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(organizationBasePath, organizationID) - - return s.client.DoRequest("DELETE", apiPath, nil, nil) -} - -// ListPaymentMethods returns PaymentMethods for an organization -func (s *OrganizationServiceOp) ListPaymentMethods(organizationID string) ([]PaymentMethod, *Response, error) { - if validateErr := ValidateUUID(organizationID); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(organizationBasePath, organizationID, paymentMethodBasePath) - root := new(paymentMethodsRoot) - - resp, err := s.client.DoRequest("GET", apiPath, nil, root) - if err != nil { - return nil, resp, err - } - - return root.PaymentMethods, resp, err -} - -// ListEvents returns list of organization events -func (s *OrganizationServiceOp) ListEvents(organizationID string, listOpt *ListOptions) ([]Event, *Response, error) { - if validateErr := ValidateUUID(organizationID); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(organizationBasePath, organizationID, eventBasePath) - - return listEvents(s.client, apiPath, listOpt) -} diff --git a/vendor/github.com/packethost/packngo/packngo.go b/vendor/github.com/packethost/packngo/packngo.go deleted file mode 100644 index 25c9c331..00000000 --- a/vendor/github.com/packethost/packngo/packngo.go +++ /dev/null @@ -1,468 +0,0 @@ -package packngo - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "log" - "net/http" - "net/http/httputil" - "net/url" - "os" - "regexp" - "strconv" - "strings" - "time" -) - -const ( - authTokenEnvVar = "PACKET_AUTH_TOKEN" - baseURL = "https://api.equinix.com/metal/v1/" - mediaType = "application/json" - debugEnvVar = "PACKNGO_DEBUG" - - headerRateLimit = "X-RateLimit-Limit" - headerRateRemaining = "X-RateLimit-Remaining" - headerRateReset = "X-RateLimit-Reset" - expectedAPIContentTypePrefix = "application/json" -) - -// meta contains pagination information -type meta struct { - Self *Href `json:"self"` - First *Href `json:"first"` - Last *Href `json:"last"` - Previous *Href `json:"previous,omitempty"` - Next *Href `json:"next,omitempty"` - Total int `json:"total"` - CurrentPageNum int `json:"current_page"` - LastPageNum int `json:"last_page"` -} - -// Response is the http response from api calls -type Response struct { - *http.Response - Rate -} - -// Href is an API link -type Href struct { - Href string `json:"href"` -} - -func (r *Response) populateRate() { - // parse the rate limit headers and populate Response.Rate - if limit := r.Header.Get(headerRateLimit); limit != "" { - r.Rate.RequestLimit, _ = strconv.Atoi(limit) - } - if remaining := r.Header.Get(headerRateRemaining); remaining != "" { - r.Rate.RequestsRemaining, _ = strconv.Atoi(remaining) - } - if reset := r.Header.Get(headerRateReset); reset != "" { - if v, _ := strconv.ParseInt(reset, 10, 64); v != 0 { - r.Rate.Reset = Timestamp{time.Unix(v, 0)} - } - } -} - -// ErrorResponse is the http response used on errors -type ErrorResponse struct { - Response *http.Response - Errors []string `json:"errors"` - SingleError string `json:"error"` -} - -func (r *ErrorResponse) Error() string { - return fmt.Sprintf("%v %v: %d %v %v", - r.Response.Request.Method, r.Response.Request.URL, r.Response.StatusCode, strings.Join(r.Errors, ", "), r.SingleError) -} - -// Client is the base API Client -type Client struct { - client *http.Client - debug bool - - BaseURL *url.URL - - UserAgent string - ConsumerToken string - APIKey string - apiKeySet bool - header http.Header - - RateLimit Rate - - // Equinix Metal Api Objects - APIKeys APIKeyService - BGPConfig BGPConfigService - BGPSessions BGPSessionService - Batches BatchService - CapacityService CapacityService - Connections ConnectionService - DeviceIPs DeviceIPService - Devices DeviceService - Emails EmailService - Events EventService - Facilities FacilityService - HardwareReservations HardwareReservationService - Invitations InvitationService - Members MemberService - Metros MetroService - Notifications NotificationService - OperatingSystems OSService - Organizations OrganizationService - Plans PlanService - Ports PortService - ProjectIPs ProjectIPService - ProjectVirtualNetworks ProjectVirtualNetworkService - Projects ProjectService - SSHKeys SSHKeyService - SpotMarket SpotMarketService - SpotMarketRequests SpotMarketRequestService - MetalGateways MetalGatewayService - TwoFactorAuth TwoFactorAuthService - Users UserService - VirtualCircuits VirtualCircuitService - VLANAssignments VLANAssignmentService - VolumeAttachments VolumeAttachmentService - Volumes VolumeService - VRFs VRFService - - // DevicePorts - // - // Deprecated: Use Client.Ports or Device methods - DevicePorts DevicePortService -} - -// requestDoer provides methods for making HTTP requests and receiving the -// response, errors, and a structured result -// -// This interface is used in *ServiceOp as a mockable alternative to a full -// Client object. -type requestDoer interface { - NewRequest(method, path string, body interface{}) (*http.Request, error) - Do(req *http.Request, v interface{}) (*Response, error) - DoRequest(method, path string, body, v interface{}) (*Response, error) - DoRequestWithHeader(method string, headers map[string]string, path string, body, v interface{}) (*Response, error) -} - -// NewRequest inits a new http request with the proper headers -func (c *Client) NewRequest(method, path string, body interface{}) (*http.Request, error) { - // relative path to append to the endpoint url, no leading slash please - if path[0] == '/' { - path = path[1:] - } - rel, err := url.Parse(path) - if err != nil { - return nil, err - } - - u := c.BaseURL.ResolveReference(rel) - - // json encode the request body, if any - buf := new(bytes.Buffer) - if body != nil { - err := json.NewEncoder(buf).Encode(body) - if err != nil { - return nil, err - } - } - - req, err := http.NewRequest(method, u.String(), buf) - if err != nil { - return nil, err - } - - req.Close = true - - req.Header = c.header.Clone() - req.Header.Set("X-Auth-Token", c.APIKey) - req.Header.Set("X-Consumer-Token", c.ConsumerToken) - req.Header.Set("User-Agent", c.UserAgent) - - return req, nil -} - -// Do executes the http request -func (c *Client) Do(req *http.Request, v interface{}) (*Response, error) { - resp, err := c.client.Do(req) - if err != nil { - return nil, err - } - - defer resp.Body.Close() - - response := Response{Response: resp} - response.populateRate() - if c.debug { - dumpResponse(response.Response) - } - dumpDeprecation(response.Response) - c.RateLimit = response.Rate - - err = checkResponse(resp) - // if the response is an error, return the ErrorResponse - if err != nil { - return &response, err - } - - if v != nil { - // if v implements the io.Writer interface, return the raw response - if w, ok := v.(io.Writer); ok { - _, err = io.Copy(w, resp.Body) - if err != nil { - return &response, err - } - } else { - err = json.NewDecoder(resp.Body).Decode(v) - if err != nil { - return &response, err - } - } - } - - return &response, err -} - -// dumpDeprecation logs headers defined by -// https://tools.ietf.org/html/rfc8594 -func dumpDeprecation(resp *http.Response) { - uri := "" - if resp.Request != nil { - uri = resp.Request.Method + " " + resp.Request.URL.Path - } - - deprecation := resp.Header.Get("Deprecation") - if deprecation != "" { - if deprecation == "true" { - deprecation = "" - } else { - deprecation = " on " + deprecation - } - log.Printf("WARNING: %q reported deprecation%s", uri, deprecation) - } - - sunset := resp.Header.Get("Sunset") - if sunset != "" { - log.Printf("WARNING: %q reported sunsetting on %s", uri, sunset) - } - - links := resp.Header.Values("Link") - - for _, s := range links { - for _, ss := range strings.Split(s, ",") { - if strings.Contains(ss, "rel=\"sunset\"") { - link := strings.Split(ss, ";")[0] - log.Printf("WARNING: See %s for sunset details", link) - } else if strings.Contains(ss, "rel=\"deprecation\"") { - link := strings.Split(ss, ";")[0] - log.Printf("WARNING: See %s for deprecation details", link) - } - } - } -} - -// from terraform-plugin-sdk/v2/helper/logging/transport.go -func prettyPrintJsonLines(b []byte) string { - parts := strings.Split(string(b), "\n") - for i, p := range parts { - if b := []byte(p); json.Valid(b) { - var out bytes.Buffer - _ = json.Indent(&out, b, "", " ") - parts[i] = out.String() - } - } - return strings.Join(parts, "\n") -} - -func dumpResponse(resp *http.Response) { - o, _ := httputil.DumpResponse(resp, true) - strResp := prettyPrintJsonLines(o) - reg, _ := regexp.Compile(`"token":(.+?),`) - reMatches := reg.FindStringSubmatch(strResp) - if len(reMatches) == 2 { - strResp = strings.Replace(strResp, reMatches[1], strings.Repeat("-", len(reMatches[1])), 1) - } - log.Printf("\n=======[RESPONSE]============\n%s\n\n", strResp) -} - -func dumpRequest(req *http.Request) { - r := req.Clone(context.TODO()) - r.Body, _ = req.GetBody() - h := r.Header - if len(h.Get("X-Auth-Token")) != 0 { - h.Set("X-Auth-Token", "**REDACTED**") - } - defer r.Body.Close() - - o, _ := httputil.DumpRequestOut(r, false) - bbs, _ := ioutil.ReadAll(r.Body) - reqBodyStr := prettyPrintJsonLines(bbs) - strReq := prettyPrintJsonLines(o) - log.Printf("\n=======[REQUEST]=============\n%s%s\n", string(strReq), reqBodyStr) -} - -// DoRequest is a convenience method, it calls NewRequest followed by Do -// v is the interface to unmarshal the response JSON into -func (c *Client) DoRequest(method, path string, body, v interface{}) (*Response, error) { - req, err := c.NewRequest(method, path, body) - if c.debug { - dumpRequest(req) - } - if err != nil { - return nil, err - } - return c.Do(req, v) -} - -// DoRequestWithHeader same as DoRequest -func (c *Client) DoRequestWithHeader(method string, headers map[string]string, path string, body, v interface{}) (*Response, error) { - req, err := c.NewRequest(method, path, body) - for k, v := range headers { - req.Header.Add(k, v) - } - - if c.debug { - dumpRequest(req) - } - if err != nil { - return nil, err - } - return c.Do(req, v) -} - -// NewClientWithAuth initializes and returns a Client, use this to get an API Client to operate on -// N.B.: Equinix Metal's API certificate requires Go 1.5+ to successfully parse. If you are using -// an older version of Go, pass in a custom http.Client with a custom TLS configuration -// that sets "InsecureSkipVerify" to "true" -func NewClientWithAuth(consumerToken string, apiKey string, httpClient *http.Client) *Client { - client, _ := NewClientWithBaseURL(consumerToken, apiKey, httpClient, baseURL) - return client -} - -// NewClientWithBaseURL returns a Client pointing to nonstandard API URL, e.g. -// for mocking the remote API -func NewClientWithBaseURL(consumerToken string, apiKey string, httpClient *http.Client, apiBaseURL string) (*Client, error) { - if httpClient == nil { - httpClient = http.DefaultClient - } - - return NewClient(WithAuth(consumerToken, apiKey), WithHTTPClient(httpClient), WithBaseURL(apiBaseURL)) -} - -// NewClient initializes and returns a Client. The opts are functions such as WithAuth, -// WithHTTPClient, etc. -// -// An example: -// -// c, err := NewClient() -// -// An alternative example, which avoids reading PACKET_AUTH_TOKEN environment variable: -// -// c, err := NewClient(WithAuth("packngo lib", packetAuthToken)) -func NewClient(opts ...ClientOpt) (*Client, error) { - // set defaults, then let caller override them - c := &Client{ - client: http.DefaultClient, - UserAgent: UserAgent, - ConsumerToken: "packngo lib", - header: http.Header{}, - } - - c.header.Set("Content-Type", mediaType) - c.header.Set("Accept", mediaType) - - var err error - c.BaseURL, err = url.Parse(baseURL) - if err != nil { - return nil, err - } - - c.APIKeys = &APIKeyServiceOp{client: c} - c.BGPConfig = &BGPConfigServiceOp{client: c} - c.BGPSessions = &BGPSessionServiceOp{client: c} - c.Batches = &BatchServiceOp{client: c} - c.CapacityService = &CapacityServiceOp{client: c} - c.Connections = &ConnectionServiceOp{client: c} - c.DeviceIPs = &DeviceIPServiceOp{client: c} - c.DevicePorts = &DevicePortServiceOp{client: c} - c.Devices = &DeviceServiceOp{client: c} - c.Emails = &EmailServiceOp{client: c} - c.Events = &EventServiceOp{client: c} - c.Facilities = &FacilityServiceOp{client: c} - c.HardwareReservations = &HardwareReservationServiceOp{client: c} - c.Invitations = &InvitationServiceOp{client: c} - c.Members = &MemberServiceOp{client: c} - c.Metros = &MetroServiceOp{client: c} - c.Notifications = &NotificationServiceOp{client: c} - c.OperatingSystems = &OSServiceOp{client: c} - c.Organizations = &OrganizationServiceOp{client: c} - c.Plans = &PlanServiceOp{client: c} - c.Ports = &PortServiceOp{client: c} - c.ProjectIPs = &ProjectIPServiceOp{client: c} - c.ProjectVirtualNetworks = &ProjectVirtualNetworkServiceOp{client: c} - c.Projects = &ProjectServiceOp{client: c} - c.SSHKeys = &SSHKeyServiceOp{client: c} - c.SpotMarket = &SpotMarketServiceOp{client: c} - c.SpotMarketRequests = &SpotMarketRequestServiceOp{client: c} - c.MetalGateways = &MetalGatewayServiceOp{client: c} - c.TwoFactorAuth = &TwoFactorAuthServiceOp{client: c} - c.Users = &UserServiceOp{client: c} - c.VirtualCircuits = &VirtualCircuitServiceOp{client: c} - c.VolumeAttachments = &VolumeAttachmentServiceOp{client: c} - c.Volumes = &VolumeServiceOp{client: c} - c.VRFs = &VRFServiceOp{client: c} - c.VLANAssignments = &VLANAssignmentServiceOp{client: c} - c.debug = os.Getenv(debugEnvVar) != "" - - for _, fn := range opts { - err := fn(c) - if err != nil { - return nil, err - } - } - - if !c.apiKeySet { - c.APIKey = os.Getenv(authTokenEnvVar) - - if c.APIKey == "" { - return nil, fmt.Errorf("you must export %s", authTokenEnvVar) - } - - c.apiKeySet = true - } - - return c, nil -} - -func checkResponse(r *http.Response) error { - if s := r.StatusCode; s >= 200 && s <= 299 { - // response is good, return - return nil - } - - errorResponse := &ErrorResponse{Response: r} - data, err := ioutil.ReadAll(r.Body) - // if the response has a body, populate the message in errorResponse - if err != nil { - return err - } - - ct := r.Header.Get("Content-Type") - if !strings.HasPrefix(ct, expectedAPIContentTypePrefix) { - errorResponse.SingleError = fmt.Sprintf("Unexpected Content-Type %s with status %s", ct, r.Status) - return errorResponse - } - - if len(data) > 0 { - err = json.Unmarshal(data, errorResponse) - if err != nil { - return err - } - } - - return errorResponse -} diff --git a/vendor/github.com/packethost/packngo/payment_methods.go b/vendor/github.com/packethost/packngo/payment_methods.go deleted file mode 100644 index 8f9840f0..00000000 --- a/vendor/github.com/packethost/packngo/payment_methods.go +++ /dev/null @@ -1,71 +0,0 @@ -package packngo - -// API documentation https://metal.equinix.com/developers/api/paymentmethods/ -const paymentMethodBasePath = "/payment-methods" - -// ProjectService interface defines available project methods -type PaymentMethodService interface { - List() ([]PaymentMethod, *Response, error) - Get(string) (*PaymentMethod, *Response, error) - Create(*PaymentMethodCreateRequest) (*PaymentMethod, *Response, error) - Update(string, *PaymentMethodUpdateRequest) (*PaymentMethod, *Response, error) - Delete(string) (*Response, error) -} - -type paymentMethodsRoot struct { - PaymentMethods []PaymentMethod `json:"payment_methods"` -} - -// PaymentMethod represents an Equinix Metal payment method of an organization -type PaymentMethod struct { - ID string `json:"id"` - Name string `json:"name,omitempty"` - Created string `json:"created_at,omitempty"` - Updated string `json:"updated_at,omitempty"` - Nonce string `json:"nonce,omitempty"` - Default bool `json:"default,omitempty"` - Organization Organization `json:"organization,omitempty"` - Projects []Project `json:"projects,omitempty"` - Type string `json:"type,omitempty"` - CardholderName string `json:"cardholder_name,omitempty"` - ExpMonth string `json:"expiration_month,omitempty"` - ExpYear string `json:"expiration_year,omitempty"` - Last4 string `json:"last_4,omitempty"` - BillingAddress BillingAddress `json:"billing_address,omitempty"` - URL string `json:"href,omitempty"` -} - -func (pm PaymentMethod) String() string { - return Stringify(pm) -} - -// PaymentMethodCreateRequest type used to create an Equinix Metal payment method of an organization -type PaymentMethodCreateRequest struct { - Name string `json:"name"` - Nonce string `json:"nonce"` - CardholderName string `json:"cardholder_name,omitempty"` - ExpMonth string `json:"expiration_month,omitempty"` - ExpYear string `json:"expiration_year,omitempty"` - BillingAddress string `json:"billing_address,omitempty"` -} - -func (pm PaymentMethodCreateRequest) String() string { - return Stringify(pm) -} - -// PaymentMethodUpdateRequest type used to update an Equinix Metal payment method of an organization -type PaymentMethodUpdateRequest struct { - Name *string `json:"name,omitempty"` - CardholderName *string `json:"cardholder_name,omitempty"` - ExpMonth *string `json:"expiration_month,omitempty"` - ExpYear *string `json:"expiration_year,omitempty"` - BillingAddress *string `json:"billing_address,omitempty"` -} - -func (pm PaymentMethodUpdateRequest) String() string { - return Stringify(pm) -} - -// PaymentMethodServiceOp implements PaymentMethodService -type PaymentMethodServiceOp struct { -} diff --git a/vendor/github.com/packethost/packngo/plans.go b/vendor/github.com/packethost/packngo/plans.go deleted file mode 100644 index 8b815c44..00000000 --- a/vendor/github.com/packethost/packngo/plans.go +++ /dev/null @@ -1,201 +0,0 @@ -package packngo - -import ( - "encoding/json" - "path" -) - -const planBasePath = "/plans" - -// PlanService interface defines available plan methods -type PlanService interface { - List(*ListOptions) ([]Plan, *Response, error) - ProjectList(string, *ListOptions) ([]Plan, *Response, error) - OrganizationList(string, *ListOptions) ([]Plan, *Response, error) -} - -type planRoot struct { - Plans []Plan `json:"plans"` -} - -// Plan represents an Equinix Metal service plan -type Plan struct { - ID string `json:"id"` - Slug string `json:"slug,omitempty"` - Name string `json:"name,omitempty"` - Description string `json:"description,omitempty"` - Line string `json:"line,omitempty"` - Legacy bool `json:"legacy,omitempty"` - Specs *Specs `json:"specs,omitempty"` - Pricing *Pricing `json:"pricing,omitempty"` - DeploymentTypes []string `json:"deployment_types"` - Class string `json:"class"` - AvailableIn []Facility `json:"available_in"` - AvailableInMetros []Metro `json:"available_in_metros"` - ReservationPricing *ReservationPricing `json:"reservation_pricing,omitempty"` - - Href string `json:"href,omitempty"` -} - -func (p Plan) String() string { - return Stringify(p) -} - -type MetroPricing map[string]AnnualReservationPricing - -// ReservationPricing - The reserved pricing for a plan -type ReservationPricing struct { - AnnualReservationPricing - Metros MetroPricing -} - -func (r ReservationPricing) String() string { - return Stringify(r) -} - -// UnmarshalJSON - Custom unmarshal function to set up the ReservationPricing object -func (r *ReservationPricing) UnmarshalJSON(data []byte) error { - var a AnnualReservationPricing - var m MetroPricing - - // Leverage the built in unmarshalling to sort out all the fields - err := json.Unmarshal(data, &a) - if err != nil { - return err - } - err = json.Unmarshal(data, &m) - if err != nil { - return err - } - // Remove three_year and one_year from the metropricing object - delete(m, "three_year") - delete(m, "one_year") - - // Pass the objects to the parent - r.Metros = m - r.AnnualReservationPricing = a - - return nil -} - -type AnnualReservationPricing struct { - OneYear *Pricing `json:"one_year"` - ThreeYear *Pricing `json:"three_year"` -} - -func (m AnnualReservationPricing) String() string { - return Stringify(m) -} - -// Specs - the server specs for a plan -type Specs struct { - Cpus []*Cpus `json:"cpus,omitempty"` - Memory *Memory `json:"memory,omitempty"` - Drives []*Drives `json:"drives,omitempty"` - Nics []*Nics `json:"nics,omitempty"` - Features *Features `json:"features,omitempty"` -} - -func (s Specs) String() string { - return Stringify(s) -} - -// Cpus - the CPU config details for specs on a plan -type Cpus struct { - Count int `json:"count,omitempty"` - Type string `json:"type,omitempty"` -} - -func (c Cpus) String() string { - return Stringify(c) -} - -// Memory - the RAM config details for specs on a plan -type Memory struct { - Total string `json:"total,omitempty"` -} - -func (m Memory) String() string { - return Stringify(m) -} - -// Drives - the storage config details for specs on a plan -type Drives struct { - Count int `json:"count,omitempty"` - Size string `json:"size,omitempty"` - Type string `json:"type,omitempty"` -} - -func (d Drives) String() string { - return Stringify(d) -} - -// Nics - the network hardware details for specs on a plan -type Nics struct { - Count int `json:"count,omitempty"` - Type string `json:"type,omitempty"` -} - -func (n Nics) String() string { - return Stringify(n) -} - -// Features - other features in the specs for a plan -type Features struct { - Raid bool `json:"raid,omitempty"` - Txt bool `json:"txt,omitempty"` -} - -func (f Features) String() string { - return Stringify(f) -} - -// Pricing - the pricing options on a plan -type Pricing struct { - Hour float32 `json:"hour,omitempty"` - Month float32 `json:"month,omitempty"` -} - -func (p Pricing) String() string { - return Stringify(p) -} - -// PlanServiceOp implements PlanService -type PlanServiceOp struct { - client *Client -} - -func planList(c *Client, apiPath string, opts *ListOptions) ([]Plan, *Response, error) { - root := new(planRoot) - apiPathQuery := opts.WithQuery(apiPath) - - resp, err := c.DoRequest("GET", apiPathQuery, nil, root) - if err != nil { - return nil, resp, err - } - - return root.Plans, resp, err - -} - -// List method returns all available plans -func (s *PlanServiceOp) List(opts *ListOptions) ([]Plan, *Response, error) { - return planList(s.client, planBasePath, opts) - -} - -// ProjectList method returns plans available in a project -func (s *PlanServiceOp) ProjectList(projectID string, opts *ListOptions) ([]Plan, *Response, error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - return planList(s.client, path.Join(projectBasePath, projectID, planBasePath), opts) -} - -// OrganizationList method returns plans available in an organization -func (s *PlanServiceOp) OrganizationList(organizationID string, opts *ListOptions) ([]Plan, *Response, error) { - if validateErr := ValidateUUID(organizationID); validateErr != nil { - return nil, nil, validateErr - } - return planList(s.client, path.Join(organizationBasePath, organizationID, planBasePath), opts) -} diff --git a/vendor/github.com/packethost/packngo/ports.go b/vendor/github.com/packethost/packngo/ports.go deleted file mode 100644 index 286f70ed..00000000 --- a/vendor/github.com/packethost/packngo/ports.go +++ /dev/null @@ -1,248 +0,0 @@ -package packngo - -import ( - "path" -) - -// PortService handles operations on a port -type PortService interface { - Assign(string, string) (*Port, *Response, error) - Unassign(string, string) (*Port, *Response, error) - AssignNative(string, string) (*Port, *Response, error) - UnassignNative(string) (*Port, *Response, error) - Bond(string, bool) (*Port, *Response, error) - Disbond(string, bool) (*Port, *Response, error) - ConvertToLayerTwo(string) (*Port, *Response, error) - ConvertToLayerThree(string, []AddressRequest) (*Port, *Response, error) - Get(string, *GetOptions) (*Port, *Response, error) -} - -type PortServiceOp struct { - client requestDoer -} - -var _ PortService = (*PortServiceOp)(nil) - -type PortData struct { - // MAC address is set for NetworkPort ports - MAC string `json:"mac,omitempty"` - - // Bonded is true for NetworkPort ports in a bond and NetworkBondPort ports - // that are active - Bonded bool `json:"bonded"` -} - -type BondData struct { - // ID is the Port.ID of the bonding port - ID string `json:"id"` - - // Name of the port interface for the bond ("bond0") - Name string `json:"name"` -} - -// Port is a hardware port associated with a reserved or instantiated hardware -// device. -type Port struct { - *Href `json:",inline"` - - // ID of the Port - ID string `json:"id"` - - // Type is either "NetworkBondPort" for bond ports or "NetworkPort" for - // bondable ethernet ports - Type string `json:"type"` - - // Name of the interface for this port (such as "bond0" or "eth0") - Name string `json:"name"` - - // Data about the port - Data PortData `json:"data,omitempty"` - - // Indicates whether or not the bond can be broken on the port (when applicable). - DisbondOperationSupported bool `json:"disbond_operation_supported,omitempty"` - - // NetworkType is either of layer2-bonded, layer2-individual, layer3, - // hybrid, hybrid-bonded - NetworkType string `json:"network_type,omitempty"` - - // NativeVirtualNetwork is the Native VLAN attached to the port - // - NativeVirtualNetwork *VirtualNetwork `json:"native_virtual_network,omitempty"` - - // VLANs attached to the port - AttachedVirtualNetworks []VirtualNetwork `json:"virtual_networks,omitempty"` - - // Bond details for ports with a NetworkPort type - Bond *BondData `json:"bond,omitempty"` -} - -type AddressRequest struct { - AddressFamily int `json:"address_family"` - Public bool `json:"public"` -} - -type BackToL3Request struct { - RequestIPs []AddressRequest `json:"request_ips"` -} - -type PortAssignRequest struct { - // PortID of the Port - // - // Deprecated: this is redundant to the portID parameter in request - // functions. This is kept for use by deprecated DevicePortServiceOps - // methods. - PortID string `json:"id,omitempty"` - - VirtualNetworkID string `json:"vnid"` -} - -type BondRequest struct { - BulkEnable bool `json:"bulk_enable"` -} - -type DisbondRequest struct { - BulkDisable bool `json:"bulk_disable"` -} - -// Assign adds a VLAN to a port -func (i *PortServiceOp) Assign(portID, vlanID string) (*Port, *Response, error) { - if validateErr := ValidateUUID(portID); validateErr != nil { - return nil, nil, validateErr - } - if validateErr := ValidateUUID(vlanID); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(portBasePath, portID, "assign") - par := &PortAssignRequest{VirtualNetworkID: vlanID} - - return i.portAction(apiPath, par) -} - -// AssignNative assigns a virtual network to the port as a "native VLAN" -// The VLAN being assigned MUST first be added as a vlan using Assign() before -// you may assign it as the native VLAN -func (i *PortServiceOp) AssignNative(portID, vlanID string) (*Port, *Response, error) { - if validateErr := ValidateUUID(portID); validateErr != nil { - return nil, nil, validateErr - } - if validateErr := ValidateUUID(vlanID); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(portBasePath, portID, "native-vlan") - par := &PortAssignRequest{VirtualNetworkID: vlanID} - return i.portAction(apiPath, par) -} - -// UnassignNative removes native VLAN from the supplied port -func (i *PortServiceOp) UnassignNative(portID string) (*Port, *Response, error) { - if validateErr := ValidateUUID(portID); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(portBasePath, portID, "native-vlan") - port := new(Port) - - resp, err := i.client.DoRequest("DELETE", apiPath, nil, port) - if err != nil { - return nil, resp, err - } - - return port, resp, err -} - -// Unassign removes a VLAN from the port -func (i *PortServiceOp) Unassign(portID, vlanID string) (*Port, *Response, error) { - if validateErr := ValidateUUID(portID); validateErr != nil { - return nil, nil, validateErr - } - if validateErr := ValidateUUID(vlanID); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(portBasePath, portID, "unassign") - par := &PortAssignRequest{VirtualNetworkID: vlanID} - - return i.portAction(apiPath, par) -} - -// Bond enables bonding for one or all ports -func (i *PortServiceOp) Bond(portID string, bulkEnable bool) (*Port, *Response, error) { - if validateErr := ValidateUUID(portID); validateErr != nil { - return nil, nil, validateErr - } - br := &BondRequest{BulkEnable: bulkEnable} - apiPath := path.Join(portBasePath, portID, "bond") - return i.portAction(apiPath, br) -} - -// Disbond disables bonding for one or all ports -func (i *PortServiceOp) Disbond(portID string, bulkEnable bool) (*Port, *Response, error) { - if validateErr := ValidateUUID(portID); validateErr != nil { - return nil, nil, validateErr - } - dr := &DisbondRequest{BulkDisable: bulkEnable} - apiPath := path.Join(portBasePath, portID, "disbond") - return i.portAction(apiPath, dr) -} - -func (i *PortServiceOp) portAction(apiPath string, req interface{}) (*Port, *Response, error) { - port := new(Port) - - resp, err := i.client.DoRequest("POST", apiPath, req, port) - if err != nil { - return nil, resp, err - } - - return port, resp, err -} - -// ConvertToLayerTwo converts a bond port to Layer 2. IP assignments of the port will be removed. -// -// portID is the UUID of a Bonding Port -func (i *PortServiceOp) ConvertToLayerTwo(portID string) (*Port, *Response, error) { - if validateErr := ValidateUUID(portID); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(portBasePath, portID, "convert", "layer-2") - port := new(Port) - - resp, err := i.client.DoRequest("POST", apiPath, nil, port) - if err != nil { - return nil, resp, err - } - - return port, resp, err -} - -// ConvertToLayerThree converts a bond port to Layer 3. VLANs must first be unassigned. -func (i *PortServiceOp) ConvertToLayerThree(portID string, ips []AddressRequest) (*Port, *Response, error) { - if validateErr := ValidateUUID(portID); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(portBasePath, portID, "convert", "layer-3") - port := new(Port) - - req := BackToL3Request{ - RequestIPs: ips, - } - - resp, err := i.client.DoRequest("POST", apiPath, &req, port) - if err != nil { - return nil, resp, err - } - - return port, resp, err -} - -// Get returns a port by id -func (s *PortServiceOp) Get(portID string, opts *GetOptions) (*Port, *Response, error) { - if validateErr := ValidateUUID(portID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(portBasePath, portID) - apiPathQuery := opts.WithQuery(endpointPath) - port := new(Port) - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, port) - if err != nil { - return nil, resp, err - } - return port, resp, err -} diff --git a/vendor/github.com/packethost/packngo/projects.go b/vendor/github.com/packethost/packngo/projects.go deleted file mode 100644 index 720c3b28..00000000 --- a/vendor/github.com/packethost/packngo/projects.go +++ /dev/null @@ -1,222 +0,0 @@ -package packngo - -import ( - "path" -) - -const projectBasePath = "/projects" - -// ProjectService interface defines available project methods -type ProjectService interface { - List(listOpt *ListOptions) ([]Project, *Response, error) - Get(string, *GetOptions) (*Project, *Response, error) - Create(*ProjectCreateRequest) (*Project, *Response, error) - Update(string, *ProjectUpdateRequest) (*Project, *Response, error) - Delete(string) (*Response, error) - ListBGPSessions(projectID string, listOpt *ListOptions) ([]BGPSession, *Response, error) - DiscoverBGPSessions(projectID string, getOpt *GetOptions) (*BGPDiscoverResponse, *Response, error) - ListEvents(string, *ListOptions) ([]Event, *Response, error) - ListSSHKeys(projectID string, searchOpt *SearchOptions) ([]SSHKey, *Response, error) -} - -type projectsRoot struct { - Projects []Project `json:"projects"` - Meta meta `json:"meta"` -} - -// Project represents an Equinix Metal project -type Project struct { - ID string `json:"id"` - Name string `json:"name,omitempty"` - Organization Organization `json:"organization,omitempty"` - Created string `json:"created_at,omitempty"` - Updated string `json:"updated_at,omitempty"` - Users []User `json:"members,omitempty"` - Devices []Device `json:"devices,omitempty"` - SSHKeys []SSHKey `json:"ssh_keys,omitempty"` - URL string `json:"href,omitempty"` - PaymentMethod PaymentMethod `json:"payment_method,omitempty"` - BackendTransfer bool `json:"backend_transfer_enabled"` -} - -// BGPDiscoverResponse struct is returned from the bgp/discover endpoint -type BGPDiscoverResponse struct { - UpdatedAt Timestamp `json:"updated_at"` -} - -func (p Project) String() string { - return Stringify(p) -} - -// ProjectCreateRequest type used to create an Equinix Metal project -type ProjectCreateRequest struct { - Name string `json:"name"` - PaymentMethodID string `json:"payment_method_id,omitempty"` - OrganizationID string `json:"organization_id,omitempty"` -} - -func (p ProjectCreateRequest) String() string { - return Stringify(p) -} - -// ProjectUpdateRequest type used to update an Equinix Metal project -type ProjectUpdateRequest struct { - Name *string `json:"name,omitempty"` - PaymentMethodID *string `json:"payment_method_id,omitempty"` - BackendTransfer *bool `json:"backend_transfer_enabled,omitempty"` -} - -func (p ProjectUpdateRequest) String() string { - return Stringify(p) -} - -// ProjectServiceOp implements ProjectService -type ProjectServiceOp struct { - client requestDoer -} - -// List returns the user's projects -func (s *ProjectServiceOp) List(opts *ListOptions) (projects []Project, resp *Response, err error) { - apiPathQuery := opts.WithQuery(projectBasePath) - - for { - subset := new(projectsRoot) - - resp, err = s.client.DoRequest("GET", apiPathQuery, nil, subset) - if err != nil { - return nil, resp, err - } - - projects = append(projects, subset.Projects...) - - if apiPathQuery = nextPage(subset.Meta, opts); apiPathQuery != "" { - continue - } - - return - } -} - -// Get returns a project by id -func (s *ProjectServiceOp) Get(projectID string, opts *GetOptions) (*Project, *Response, error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(projectBasePath, projectID) - apiPathQuery := opts.WithQuery(endpointPath) - project := new(Project) - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, project) - if err != nil { - return nil, resp, err - } - return project, resp, err -} - -// Create creates a new project -func (s *ProjectServiceOp) Create(createRequest *ProjectCreateRequest) (*Project, *Response, error) { - project := new(Project) - - resp, err := s.client.DoRequest("POST", projectBasePath, createRequest, project) - if err != nil { - return nil, resp, err - } - - return project, resp, err -} - -// Update updates a project -func (s *ProjectServiceOp) Update(id string, updateRequest *ProjectUpdateRequest) (*Project, *Response, error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(projectBasePath, id) - project := new(Project) - - resp, err := s.client.DoRequest("PATCH", apiPath, updateRequest, project) - if err != nil { - return nil, resp, err - } - - return project, resp, err -} - -// Delete deletes a project -func (s *ProjectServiceOp) Delete(projectID string) (*Response, error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(projectBasePath, projectID) - - return s.client.DoRequest("DELETE", apiPath, nil, nil) -} - -// ListBGPSessions returns all BGP Sessions associated with the project -func (s *ProjectServiceOp) ListBGPSessions(projectID string, opts *ListOptions) (bgpSessions []BGPSession, resp *Response, err error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(projectBasePath, projectID, bgpSessionBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - - for { - subset := new(bgpSessionsRoot) - - resp, err = s.client.DoRequest("GET", apiPathQuery, nil, subset) - if err != nil { - return nil, resp, err - } - - bgpSessions = append(bgpSessions, subset.Sessions...) - if apiPathQuery = nextPage(subset.Meta, opts); apiPathQuery != "" { - continue - } - return - } -} - -// ListSSHKeys returns all SSH Keys associated with the project -func (s *ProjectServiceOp) ListSSHKeys(projectID string, opts *SearchOptions) (sshKeys []SSHKey, resp *Response, err error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - - endpointPath := path.Join(projectBasePath, projectID, sshKeyBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - - subset := new(sshKeyRoot) - - resp, err = s.client.DoRequest("GET", apiPathQuery, nil, subset) - if err != nil { - return nil, resp, err - } - - sshKeys = append(sshKeys, subset.SSHKeys...) - - return -} - -// ListEvents returns list of project events -func (s *ProjectServiceOp) ListEvents(projectID string, listOpt *ListOptions) ([]Event, *Response, error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(projectBasePath, projectID, eventBasePath) - - return listEvents(s.client, apiPath, listOpt) -} - -// Discover refreshes BGP session status -func (p *ProjectServiceOp) DiscoverBGPSessions(projectID string, opts *GetOptions) (*BGPDiscoverResponse, *Response, error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(bgpDiscoverBasePath, projectID) - apiPathQuery := opts.WithQuery(endpointPath) - discovery := new(BGPDiscoverResponse) - response, err := p.client.DoRequest("POST", apiPathQuery, nil, discovery) - if err != nil { - return nil, response, err - } - - return discovery, response, err -} diff --git a/vendor/github.com/packethost/packngo/rate.go b/vendor/github.com/packethost/packngo/rate.go deleted file mode 100644 index 965967d4..00000000 --- a/vendor/github.com/packethost/packngo/rate.go +++ /dev/null @@ -1,12 +0,0 @@ -package packngo - -// Rate provides the API request rate limit details -type Rate struct { - RequestLimit int `json:"request_limit"` - RequestsRemaining int `json:"requests_remaining"` - Reset Timestamp `json:"rate_reset"` -} - -func (r Rate) String() string { - return Stringify(r) -} diff --git a/vendor/github.com/packethost/packngo/renovate.json b/vendor/github.com/packethost/packngo/renovate.json deleted file mode 100644 index 39a2b6e9..00000000 --- a/vendor/github.com/packethost/packngo/renovate.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "$schema": "https://docs.renovatebot.com/renovate-schema.json", - "extends": [ - "config:base" - ] -} diff --git a/vendor/github.com/packethost/packngo/spotmarket.go b/vendor/github.com/packethost/packngo/spotmarket.go deleted file mode 100644 index 3c1ee943..00000000 --- a/vendor/github.com/packethost/packngo/spotmarket.go +++ /dev/null @@ -1,92 +0,0 @@ -package packngo - -import "path" - -const ( - spotMarketBasePath = "/market/spot/prices" - - spotMarketMetrosPath = "metros" -) - -// SpotMarketService expooses Spot Market methods -type SpotMarketService interface { - // Prices gets current spot market prices by facility. - // - // Deprecated: Use PricesByFacility - Prices() (PriceMap, *Response, error) - - // PricesByFacility gets current spot market prices by facility. The map is - // indexed by facility code and then plan name. - PricesByFacility() (PriceMap, *Response, error) - - // PricesByMetro gets current spot market prices by metro. The map is - // indexed by metro code and then plan name. - PricesByMetro() (PriceMap, *Response, error) -} - -// SpotMarketServiceOp implements SpotMarketService -type SpotMarketServiceOp struct { - client *Client -} - -// PriceMap is a map of [location][plan]-> float Price -type PriceMap map[string]map[string]float64 - -// Prices gets current spot market prices by facility. -// -// Deprecated: Use PricesByFacility which this function thinly wraps. -func (s *SpotMarketServiceOp) Prices() (PriceMap, *Response, error) { - return s.PricesByFacility() -} - -// PricesByFacility gets current spot market prices by facility. The map is -// indexed by facility code and then plan name. -// -// price := client.SpotMarket.PricesByFacility()["ny5"]["c3.medium.x86"] -func (s *SpotMarketServiceOp) PricesByFacility() (PriceMap, *Response, error) { - root := new(struct { - SMPs map[string]map[string]struct { - Price float64 `json:"price"` - } `json:"spot_market_prices"` - }) - - resp, err := s.client.DoRequest("GET", spotMarketBasePath, nil, root) - if err != nil { - return nil, resp, err - } - - prices := make(PriceMap) - for facility, planMap := range root.SMPs { - prices[facility] = map[string]float64{} - for plan, v := range planMap { - prices[facility][plan] = v.Price - } - } - return prices, resp, err -} - -// PricesByMetro gets current spot market prices by metro. The map is -// indexed by metro code and then plan name. -// -// price := client.SpotMarket.PricesByMetro()["sv"]["c3.medium.x86"] -func (s *SpotMarketServiceOp) PricesByMetro() (PriceMap, *Response, error) { - root := new(struct { - SMPs map[string]map[string]struct { - Price float64 `json:"price"` - } `json:"spot_market_prices"` - }) - - resp, err := s.client.DoRequest("GET", path.Join(spotMarketBasePath, spotMarketMetrosPath), nil, root) - if err != nil { - return nil, resp, err - } - - prices := make(PriceMap) - for metro, planMap := range root.SMPs { - prices[metro] = map[string]float64{} - for plan, v := range planMap { - prices[metro][plan] = v.Price - } - } - return prices, resp, err -} diff --git a/vendor/github.com/packethost/packngo/spotmarketrequest.go b/vendor/github.com/packethost/packngo/spotmarketrequest.go deleted file mode 100644 index 38894d23..00000000 --- a/vendor/github.com/packethost/packngo/spotmarketrequest.go +++ /dev/null @@ -1,132 +0,0 @@ -package packngo - -import ( - "math" - "path" -) - -const spotMarketRequestBasePath = "/spot-market-requests" - -type SpotMarketRequestService interface { - List(string, *ListOptions) ([]SpotMarketRequest, *Response, error) - Create(*SpotMarketRequestCreateRequest, string) (*SpotMarketRequest, *Response, error) - Delete(string, bool) (*Response, error) - Get(string, *GetOptions) (*SpotMarketRequest, *Response, error) -} - -type SpotMarketRequestCreateRequest struct { - DevicesMax int `json:"devices_max"` - DevicesMin int `json:"devices_min"` - EndAt *Timestamp `json:"end_at,omitempty"` - FacilityIDs []string `json:"facilities,omitempty"` - Metro string `json:"metro,omitempty"` - MaxBidPrice float64 `json:"max_bid_price"` - - Parameters SpotMarketRequestInstanceParameters `json:"instance_parameters"` -} - -type SpotMarketRequest struct { - SpotMarketRequestCreateRequest - ID string `json:"id"` - Devices []Device `json:"devices"` - Facilities []Facility `json:"facilities,omitempty"` - Metro *Metro `json:"metro,omitempty"` - Project Project `json:"project"` - Href string `json:"href"` - Plan Plan `json:"plan"` -} - -type SpotMarketRequestInstanceParameters struct { - AlwaysPXE bool `json:"always_pxe,omitempty"` - IPXEScriptURL string `json:"ipxe_script_url,omitempty"` - BillingCycle string `json:"billing_cycle"` - CustomData string `json:"customdata,omitempty"` - Description string `json:"description,omitempty"` - Features []string `json:"features,omitempty"` - Hostname string `json:"hostname,omitempty"` - Hostnames []string `json:"hostnames,omitempty"` - Locked bool `json:"locked,omitempty"` - OperatingSystem string `json:"operating_system"` - Plan string `json:"plan"` - ProjectSSHKeys []string `json:"project_ssh_keys,omitempty"` - Tags []string `json:"tags"` - TerminationTime *Timestamp `json:"termination_time,omitempty"` - UserSSHKeys []string `json:"user_ssh_keys,omitempty"` - UserData string `json:"userdata"` -} - -type SpotMarketRequestServiceOp struct { - client *Client -} - -func roundPlus(f float64, places int) float64 { - shift := math.Pow(10, float64(places)) - return math.Floor(f*shift+.5) / shift -} - -func (s *SpotMarketRequestServiceOp) Create(cr *SpotMarketRequestCreateRequest, pID string) (*SpotMarketRequest, *Response, error) { - if validateErr := ValidateUUID(pID); validateErr != nil { - return nil, nil, validateErr - } - opts := (&GetOptions{}).Including("devices", "project", "plan") - endpointPath := path.Join(projectBasePath, pID, spotMarketRequestBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - - cr.MaxBidPrice = roundPlus(cr.MaxBidPrice, 2) - smr := new(SpotMarketRequest) - - resp, err := s.client.DoRequest("POST", apiPathQuery, cr, smr) - if err != nil { - return nil, resp, err - } - - return smr, resp, err -} - -func (s *SpotMarketRequestServiceOp) List(pID string, opts *ListOptions) ([]SpotMarketRequest, *Response, error) { - if validateErr := ValidateUUID(pID); validateErr != nil { - return nil, nil, validateErr - } - type smrRoot struct { - SMRs []SpotMarketRequest `json:"spot_market_requests"` - } - - endpointPath := path.Join(projectBasePath, pID, spotMarketRequestBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - output := new(smrRoot) - - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, output) - if err != nil { - return nil, nil, err - } - - return output.SMRs, resp, nil -} - -func (s *SpotMarketRequestServiceOp) Get(id string, opts *GetOptions) (*SpotMarketRequest, *Response, error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(spotMarketRequestBasePath, id) - apiPathQuery := opts.WithQuery(endpointPath) - smr := new(SpotMarketRequest) - - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, &smr) - if err != nil { - return nil, resp, err - } - - return smr, resp, err -} - -func (s *SpotMarketRequestServiceOp) Delete(id string, forceDelete bool) (*Response, error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(spotMarketRequestBasePath, id) - var params *map[string]bool - if forceDelete { - params = &map[string]bool{"force_termination": true} - } - return s.client.DoRequest("DELETE", apiPath, params, nil) -} diff --git a/vendor/github.com/packethost/packngo/sshkeys.go b/vendor/github.com/packethost/packngo/sshkeys.go deleted file mode 100644 index 8f0934fb..00000000 --- a/vendor/github.com/packethost/packngo/sshkeys.go +++ /dev/null @@ -1,155 +0,0 @@ -package packngo - -import ( - "fmt" - "path" -) - -const ( - sshKeyBasePath = "/ssh-keys" -) - -// SSHKeyService interface defines available device methods -type SSHKeyService interface { - List() ([]SSHKey, *Response, error) - ProjectList(string) ([]SSHKey, *Response, error) - Get(string, *GetOptions) (*SSHKey, *Response, error) - Create(*SSHKeyCreateRequest) (*SSHKey, *Response, error) - Update(string, *SSHKeyUpdateRequest) (*SSHKey, *Response, error) - Delete(string) (*Response, error) -} - -type sshKeyRoot struct { - SSHKeys []SSHKey `json:"ssh_keys"` -} - -// SSHKey represents a user's ssh key -type SSHKey struct { - ID string `json:"id"` - Label string `json:"label"` - Key string `json:"key"` - FingerPrint string `json:"fingerprint"` - Created string `json:"created_at"` - Updated string `json:"updated_at"` - Owner Href - URL string `json:"href,omitempty"` -} - -func (s SSHKey) String() string { - return Stringify(s) -} - -// SSHKeyCreateRequest type used to create an ssh key -type SSHKeyCreateRequest struct { - Label string `json:"label"` - Key string `json:"key"` - ProjectID string `json:"-"` -} - -func (s SSHKeyCreateRequest) String() string { - return Stringify(s) -} - -// SSHKeyUpdateRequest type used to update an ssh key -type SSHKeyUpdateRequest struct { - Label *string `json:"label,omitempty"` - Key *string `json:"key,omitempty"` -} - -func (s SSHKeyUpdateRequest) String() string { - return Stringify(s) -} - -// SSHKeyServiceOp implements SSHKeyService -type SSHKeyServiceOp struct { - client *Client -} - -func (s *SSHKeyServiceOp) list(url string) ([]SSHKey, *Response, error) { - root := new(sshKeyRoot) - - resp, err := s.client.DoRequest("GET", url, nil, root) - if err != nil { - return nil, resp, err - } - - return root.SSHKeys, resp, err -} - -// ProjectList lists ssh keys of a project -// Deprecated: Use ProjectServiceOp.ListSSHKeys -func (s *SSHKeyServiceOp) ProjectList(projectID string) ([]SSHKey, *Response, error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - return s.list(path.Join(projectBasePath, projectID, sshKeyBasePath)) - -} - -// List returns a user's ssh keys -func (s *SSHKeyServiceOp) List() ([]SSHKey, *Response, error) { - return s.list(sshKeyBasePath) -} - -// Get returns an ssh key by id -func (s *SSHKeyServiceOp) Get(sshKeyID string, opts *GetOptions) (*SSHKey, *Response, error) { - if validateErr := ValidateUUID(sshKeyID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(sshKeyBasePath, sshKeyID) - apiPathQuery := opts.WithQuery(endpointPath) - sshKey := new(SSHKey) - - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, sshKey) - if err != nil { - return nil, resp, err - } - - return sshKey, resp, err -} - -// Create creates a new ssh key -func (s *SSHKeyServiceOp) Create(createRequest *SSHKeyCreateRequest) (*SSHKey, *Response, error) { - urlPath := sshKeyBasePath - if createRequest.ProjectID != "" { - urlPath = path.Join(projectBasePath, createRequest.ProjectID, sshKeyBasePath) - } - sshKey := new(SSHKey) - - resp, err := s.client.DoRequest("POST", urlPath, createRequest, sshKey) - if err != nil { - return nil, resp, err - } - - return sshKey, resp, err -} - -// Update updates an ssh key -func (s *SSHKeyServiceOp) Update(id string, updateRequest *SSHKeyUpdateRequest) (*SSHKey, *Response, error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, nil, validateErr - } - if updateRequest.Label == nil && updateRequest.Key == nil { - return nil, nil, fmt.Errorf("You must set either Label or Key string for SSH Key update") - } - apiPath := path.Join(sshKeyBasePath, id) - - sshKey := new(SSHKey) - - resp, err := s.client.DoRequest("PATCH", apiPath, updateRequest, sshKey) - if err != nil { - return nil, resp, err - } - - return sshKey, resp, err -} - -// Delete deletes an ssh key -func (s *SSHKeyServiceOp) Delete(sshKeyID string) (*Response, error) { - if validateErr := ValidateUUID(sshKeyID); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(sshKeyBasePath, sshKeyID) - - return s.client.DoRequest("DELETE", apiPath, nil, nil) -} diff --git a/vendor/github.com/packethost/packngo/timestamp.go b/vendor/github.com/packethost/packngo/timestamp.go deleted file mode 100644 index ee3d780d..00000000 --- a/vendor/github.com/packethost/packngo/timestamp.go +++ /dev/null @@ -1,38 +0,0 @@ -package packngo - -import ( - "strconv" - "strings" - "time" -) - -// Timestamp represents a time that can be unmarshalled from a JSON string -// formatted as either an RFC3339 or Unix timestamp. All -// exported methods of time.Time can be called on Timestamp. -type Timestamp struct { - time.Time -} - -func (t Timestamp) String() string { - return t.Time.String() -} - -// UnmarshalJSON implements the json.Unmarshaler interface. -// Time is expected in RFC3339 or Unix format. -func (t *Timestamp) UnmarshalJSON(data []byte) (err error) { - str := string(data) - i, err := strconv.ParseInt(str, 10, 64) - if err == nil { - t.Time = time.Unix(i, 0).UTC() - } else { - if t.Time, err = time.ParseInLocation(time.RFC3339, strings.Trim(str, `"`), time.UTC); err != nil { - return err - } - } - return -} - -// Equal reports whether t and u are equal based on time.Equal -func (t Timestamp) Equal(u Timestamp) bool { - return t.Time.Equal(u.Time) -} diff --git a/vendor/github.com/packethost/packngo/two_factor_auth.go b/vendor/github.com/packethost/packngo/two_factor_auth.go deleted file mode 100644 index 5064b09f..00000000 --- a/vendor/github.com/packethost/packngo/two_factor_auth.go +++ /dev/null @@ -1,56 +0,0 @@ -package packngo - -const twoFactorAuthAppPath = "/user/otp/app" -const twoFactorAuthSmsPath = "/user/otp/sms" - -// TwoFactorAuthService interface defines available two factor authentication functions -type TwoFactorAuthService interface { - EnableApp(string) (*Response, error) - DisableApp(string) (*Response, error) - EnableSms(string) (*Response, error) - DisableSms(string) (*Response, error) - ReceiveSms() (*Response, error) - SeedApp() (string, *Response, error) -} - -// TwoFactorAuthServiceOp implements TwoFactorAuthService -type TwoFactorAuthServiceOp struct { - client *Client -} - -// EnableApp function enables two factor auth using authenticatior app -func (s *TwoFactorAuthServiceOp) EnableApp(token string) (resp *Response, err error) { - headers := map[string]string{"x-otp-token": token} - return s.client.DoRequestWithHeader("POST", headers, twoFactorAuthAppPath, nil, nil) -} - -// EnableSms function enables two factor auth using sms -func (s *TwoFactorAuthServiceOp) EnableSms(token string) (resp *Response, err error) { - headers := map[string]string{"x-otp-token": token} - return s.client.DoRequestWithHeader("POST", headers, twoFactorAuthSmsPath, nil, nil) -} - -// ReceiveSms orders the auth service to issue an SMS token -func (s *TwoFactorAuthServiceOp) ReceiveSms() (resp *Response, err error) { - return s.client.DoRequest("POST", twoFactorAuthSmsPath+"/receive", nil, nil) -} - -// DisableApp function disables two factor auth using -func (s *TwoFactorAuthServiceOp) DisableApp(token string) (resp *Response, err error) { - headers := map[string]string{"x-otp-token": token} - return s.client.DoRequestWithHeader("DELETE", headers, twoFactorAuthAppPath, nil, nil) -} - -// DisableSms function disables two factor auth using -func (s *TwoFactorAuthServiceOp) DisableSms(token string) (resp *Response, err error) { - headers := map[string]string{"x-otp-token": token} - return s.client.DoRequestWithHeader("DELETE", headers, twoFactorAuthSmsPath, nil, nil) -} - -// SeedApp orders the auth service to issue a token via google authenticator -func (s *TwoFactorAuthServiceOp) SeedApp() (otpURI string, resp *Response, err error) { - ret := &map[string]string{} - resp, err = s.client.DoRequest("POST", twoFactorAuthAppPath+"/receive", nil, ret) - - return (*ret)["otp_uri"], resp, err -} diff --git a/vendor/github.com/packethost/packngo/user.go b/vendor/github.com/packethost/packngo/user.go deleted file mode 100644 index 5b2a4390..00000000 --- a/vendor/github.com/packethost/packngo/user.go +++ /dev/null @@ -1,199 +0,0 @@ -package packngo - -import ( - "path" -) - -const ( - usersBasePath = "/users" - userBasePath = "/user" -) - -// UserService interface defines available user methods -type UserService interface { - Create(*UserCreateRequest) (*User, *Response, error) - Current() (*User, *Response, error) - List(*ListOptions) ([]User, *Response, error) - Get(string, *GetOptions) (*User, *Response, error) - Update(*UserUpdateRequest) (*User, *Response, error) -} - -type usersRoot struct { - Users []User `json:"users"` - Meta meta `json:"meta"` -} - -// SocialAccounts are social usernames or urls -type SocialAccounts struct { - GitHub string `json:"github,omitempty"` - LinkedIn string `json:"linkedin,omitempty"` - Twitter string `json:"twitter,omitempty"` - Gravatar string `json:"gravatar,omitempty"` - Keybase string `json:"keybase,omitempty"` -} - -// User represents an Equinix Metal user -type User struct { - ID string `json:"id"` - ShortID string `json:"short_id"` - FirstName string `json:"first_name,omitempty"` - LastName string `json:"last_name,omitempty"` - FullName string `json:"full_name,omitempty"` - Email string `json:"email,omitempty"` - SocialAccounts *SocialAccounts `json:"social_accounts,omitempty"` - CustomData interface{} `json:"customdata,omitempty"` - OptIn *bool `json:"opt_in,omitempty"` - OptInUpdatedAt string `json:"opt_in_updated_at,omitempty"` - DefaultProjectID *string `json:"default_project_id,omitempty"` - NumberOfSSHKeys int `json:"number_of_ssh_keys,omitempty"` - Language *string `json:"language,omitempty"` - // MailingAddress TODO: format - VerificationStage string `json:"verification_stage,omitempty"` - MaxProjects *int `json:"max_projects,omitempty"` - LastLogin string `json:"last_login_at,omitempty"` - - // Features effect the behavior of the API and UI - Features []string `json:"features,omitempty"` - - // TwoFactorAuth is the form of two factor auth, "app" or "sms" - // Renamed from TwoFactor in packngo v0.16 to match API - TwoFactorAuth string `json:"two_factor_auth,omitempty"` - DefaultOrganizationID string `json:"default_organization_id,omitempty"` - AvatarURL string `json:"avatar_url,omitempty"` - AvatarThumbURL string `json:"avatar_thumb_url,omitempty"` - Created string `json:"created_at,omitempty"` - Updated string `json:"updated_at,omitempty"` - TimeZone string `json:"timezone,omitempty"` - Emails []Email `json:"emails,omitempty"` - PhoneNumber string `json:"phone_number,omitempty"` - URL string `json:"href,omitempty"` - Restricted bool `json:"restricted,omitempty"` - Staff bool `json:"staff,omitempty"` -} - -// UserLite is an abbreviated listing of an Equinix Metal user -type UserLite struct { - *Href `json:",inline"` - ID string `json:"id"` - ShortID string `json:"short_id"` - FirstName string `json:"first_name,omitempty"` - LastName string `json:"last_name,omitempty"` - FullName string `json:"full_name,omitempty"` - Email string `json:"email,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - Level string `json:"level,omitempty"` - AvatarThumbURL string `json:"avatar_thumb_url,omitempty"` -} - -// UserCreateRequest struct for UserService.Create -type UserCreateRequest struct { - InvitationID string `json:"invitation_id,omitempty"` - Nonce string `json:"nonce,omitempty"` - FirstName string `json:"first_name,omitempty"` - LastName string `json:"last_name,omitempty"` - Password string `json:"password,omitempty"` - Customdata *interface{} `json:"customdata,omitempty"` - Emails []EmailRequest `json:"emails,omitempty"` -} - -// UserUpdateRequest struct for UserService.Update -type UserUpdateRequest struct { - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - PhoneNumber *string `json:"phone_number,omitempty"` - Timezone *string `json:"timezone,omitempty"` - Password *string `json:"password,omitempty"` - Avatar *string `json:"avatar,omitempty"` - Customdata *interface{} `json:"customdata,omitempty"` -} - -func (u User) String() string { - return Stringify(u) -} - -// UserServiceOp implements UserService -type UserServiceOp struct { - client *Client -} - -// Get method gets a user by userID -func (s *UserServiceOp) List(opts *ListOptions) (users []User, resp *Response, err error) { - apiPathQuery := opts.WithQuery(usersBasePath) - - for { - subset := new(usersRoot) - - resp, err = s.client.DoRequest("GET", apiPathQuery, nil, subset) - if err != nil { - return nil, resp, err - } - - users = append(users, subset.Users...) - - if apiPathQuery = nextPage(subset.Meta, opts); apiPathQuery != "" { - continue - } - return - } -} - -// Create a User with the given UserCreateRequest. New user VerificationStage -// will be AccountCreated, unless UserCreateRequest contains an valid -// InvitationID and Nonce in which case the VerificationStage will be Verified. -func (s *UserServiceOp) Create(createRequest *UserCreateRequest) (*User, *Response, error) { - opts := &GetOptions{} - endpointPath := path.Join(usersBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - user := new(User) - - resp, err := s.client.DoRequest("POST", apiPathQuery, createRequest, user) - if err != nil { - return nil, resp, err - } - - return user, resp, err -} - -// Returns the user object for the currently logged-in user. -func (s *UserServiceOp) Current() (*User, *Response, error) { - user := new(User) - - resp, err := s.client.DoRequest("GET", userBasePath, nil, user) - if err != nil { - return nil, resp, err - } - - return user, resp, err -} - -func (s *UserServiceOp) Get(userID string, opts *GetOptions) (*User, *Response, error) { - if validateErr := ValidateUUID(userID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(usersBasePath, userID) - apiPathQuery := opts.WithQuery(endpointPath) - user := new(User) - - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, user) - if err != nil { - return nil, resp, err - } - - return user, resp, err -} - -// Update updates the current user -func (s *UserServiceOp) Update(updateRequest *UserUpdateRequest) (*User, *Response, error) { - opts := &GetOptions{} - endpointPath := path.Join(userBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - user := new(User) - - resp, err := s.client.DoRequest("PUT", apiPathQuery, updateRequest, user) - if err != nil { - return nil, resp, err - } - - return user, resp, err -} diff --git a/vendor/github.com/packethost/packngo/utils.go b/vendor/github.com/packethost/packngo/utils.go deleted file mode 100644 index 02ed7499..00000000 --- a/vendor/github.com/packethost/packngo/utils.go +++ /dev/null @@ -1,166 +0,0 @@ -package packngo - -import ( - "bytes" - "fmt" - "io" - "reflect" - "regexp" -) - -var ( - timestampType = reflect.TypeOf(Timestamp{}) - - // Facilities DEPRECATED Use Facilities.List - Facilities = []string{ - "yyz1", "nrt1", "atl1", "mrs1", "hkg1", "ams1", - "ewr1", "sin1", "dfw1", "lax1", "syd1", "sjc1", - "ord1", "iad1", "fra1", "sea1", "dfw2"} - - // FacilityFeatures DEPRECATED Use Facilities.List - FacilityFeatures = []string{ - "baremetal", "layer_2", "backend_transfer", "storage", "global_ipv4"} - - // UtilizationLevels DEPRECATED - UtilizationLevels = []string{"unavailable", "critical", "limited", "normal"} - - // DevicePlans DEPRECATED Use Plans.List - DevicePlans = []string{"c2.medium.x86", "g2.large.x86", - "m2.xlarge.x86", "x2.xlarge.x86", "baremetal_2a", "baremetal_2a2", - "baremetal_1", "baremetal_3", "baremetal_2", "baremetal_s", - "baremetal_0", "baremetal_1e", - } -) - -// Stringify creates a string representation of the provided message -// DEPRECATED This is used internally and should not be exported by packngo -func Stringify(message interface{}) string { - var buf bytes.Buffer - v := reflect.ValueOf(message) - // TODO(displague) errors here are not reported - _ = stringifyValue(&buf, v) - return buf.String() -} - -// StreamToString converts a reader to a string -// DEPRECATED This is unused and should not be exported by packngo -func StreamToString(stream io.Reader) (string, error) { - buf := new(bytes.Buffer) - if _, err := buf.ReadFrom(stream); err != nil { - return "", err - } - return buf.String(), nil -} - -// contains tells whether a contains x. -func contains(a []string, x string) bool { - for _, n := range a { - if x == n { - return true - } - } - return false -} - -// stringifyValue was graciously cargoculted from the goprotubuf library -func stringifyValue(w io.Writer, val reflect.Value) error { - if val.Kind() == reflect.Ptr && val.IsNil() { - _, err := w.Write([]byte("")) - return err - } - - v := reflect.Indirect(val) - - switch v.Kind() { - case reflect.String: - if _, err := fmt.Fprintf(w, `"%s"`, v); err != nil { - return err - } - case reflect.Slice: - if _, err := w.Write([]byte{'['}); err != nil { - return err - } - for i := 0; i < v.Len(); i++ { - if i > 0 { - if _, err := w.Write([]byte{' '}); err != nil { - return err - } - } - - if err := stringifyValue(w, v.Index(i)); err != nil { - return err - } - } - - if _, err := w.Write([]byte{']'}); err != nil { - return err - } - return nil - case reflect.Struct: - if v.Type().Name() != "" { - if _, err := w.Write([]byte(v.Type().String())); err != nil { - return err - } - } - - // special handling of Timestamp values - if v.Type() == timestampType { - _, err := fmt.Fprintf(w, "{%s}", v.Interface()) - return err - } - - if _, err := w.Write([]byte{'{'}); err != nil { - return err - } - - var sep bool - for i := 0; i < v.NumField(); i++ { - fv := v.Field(i) - if fv.Kind() == reflect.Ptr && fv.IsNil() { - continue - } - if fv.Kind() == reflect.Slice && fv.IsNil() { - continue - } - - if sep { - if _, err := w.Write([]byte(", ")); err != nil { - return err - } - } else { - sep = true - } - - if _, err := w.Write([]byte(v.Type().Field(i).Name)); err != nil { - return err - } - if _, err := w.Write([]byte{':'}); err != nil { - return err - } - - if err := stringifyValue(w, fv); err != nil { - return err - } - } - - if _, err := w.Write([]byte{'}'}); err != nil { - return err - } - default: - if v.CanInterface() { - if _, err := fmt.Fprint(w, v.Interface()); err != nil { - return err - } - } - } - return nil -} - -// validate UUID -func ValidateUUID(uuid string) error { - r := regexp.MustCompile("^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$") - if !r.MatchString(uuid) { - return fmt.Errorf("%s is not a valid UUID", uuid) - } - return nil -} diff --git a/vendor/github.com/packethost/packngo/version.go b/vendor/github.com/packethost/packngo/version.go deleted file mode 100644 index 384479c7..00000000 --- a/vendor/github.com/packethost/packngo/version.go +++ /dev/null @@ -1,36 +0,0 @@ -package packngo - -import "runtime/debug" - -var ( - // Version of the packngo package. Version will be updated at runtime. - Version = "(devel)" - - // UserAgent is the default HTTP User-Agent Header value that will be used by NewClient. - // init() will update the version to match the built version of packngo. - UserAgent = "packngo/(devel)" -) - -const packagePath = "github.com/packethost/packngo" - -// init finds packngo in the dependency so the package Version can be properly -// reflected in API UserAgent headers and client introspection -func init() { - bi, ok := debug.ReadBuildInfo() - if !ok { - return - } - for _, d := range bi.Deps { - if d.Path == packagePath { - Version = d.Version - if d.Replace != nil { - v := d.Replace.Version - if v != "" { - Version = v - } - } - UserAgent = "packngo/" + Version - break - } - } -} diff --git a/vendor/github.com/packethost/packngo/virtualcircuits.go b/vendor/github.com/packethost/packngo/virtualcircuits.go deleted file mode 100644 index 9ca0dd36..00000000 --- a/vendor/github.com/packethost/packngo/virtualcircuits.go +++ /dev/null @@ -1,186 +0,0 @@ -package packngo - -import "path" - -type VCStatus string - -const ( - virtualCircuitBasePath = "/virtual-circuits" - - // VC is being create but not ready yet - VCStatusPending VCStatus = "pending" - - // VC is ready with a VLAN - VCStatusActive VCStatus = "active" - - // VC is ready without a VLAN - VCStatusWaiting VCStatus = "waiting_on_customer_vlan" - - // VC is being deleted - VCStatusDeleting VCStatus = "deleting" - - // not sure what the following states mean, or whether they exist - // someone from the API side could check - VCStatusActivating VCStatus = "activating" - VCStatusDeactivating VCStatus = "deactivating" - VCStatusActivationFailed VCStatus = "activation_failed" - VCStatusDeactivationFailed VCStatus = "dactivation_failed" -) - -type VirtualCircuitService interface { - Create(string, string, string, *VCCreateRequest, *GetOptions) (*VirtualCircuit, *Response, error) - Get(string, *GetOptions) (*VirtualCircuit, *Response, error) - Events(string, *GetOptions) ([]Event, *Response, error) - Delete(string) (*Response, error) - Update(string, *VCUpdateRequest, *GetOptions) (*VirtualCircuit, *Response, error) -} - -type VCUpdateRequest struct { - Name *string `json:"name,omitempty"` - Tags *[]string `json:"tags,omitempty"` - Description *string `json:"description,omitempty"` - VirtualNetworkID *string `json:"vnid,omitempty"` - - // Speed is a bps representation of the VirtualCircuit throughput. This is informational only, the field is a user-controlled description of the speed. It may be presented as a whole number with a bps, mpbs, or gbps suffix (or the respective initial). - Speed string `json:"speed,omitempty"` -} - -type VCCreateRequest struct { - // VirtualNetworkID of the Virtual Network to connect to the Virtual Circuit (required when VRFID is not specified) - VirtualNetworkID string `json:"vnid,omitempty"` - // VRFID of the VRF to connect to the Virtual Circuit (required when VirtualNetworkID is not specified) - VRFID string `json:"vrf_id,omitempty"` - // PeerASN (optional, required with VRFID) The BGP ASN of the device the switch will peer with. Can be the used across several VCs, but cannot be the same as the local_asn. - PeerASN int `json:"peer_asn,omitempty"` - // Subnet (Required for VRF) A subnet from one of the IP blocks associated with the VRF that we - // will help create an IP reservation for. Can only be either a /30 or /31. - // * For a /31 block, it will only have two IP addresses, which will be used for the metal_ip and customer_ip. - // * For a /30 block, it will have four IP - // addresses, but the first and last IP addresses are not usable. We will - // default to the first usable IP address for the metal_ip. - Subnet string `json:"subnet,omitempty"` - // MetalIP (optional, required with VRFID) The IP address that’s set as “our” IP that is - // configured on the rack_local_vlan SVI. Will default to the first usable - // IP in the subnet. - MetalIP string `json:"metal_ip,omitempty"` - // CustomerIP (optional, requires VRFID) The IP address set as the customer IP which the CSR - // switch will peer with. Will default to the other usable IP in the subnet. - CustomerIP string `json:"customer_ip,omitempty"` - // MD5 (optional, requires VRFID) The password that can be set for the VRF BGP peer - MD5 string `json:"md5,omitempty"` - NniVLAN int `json:"nni_vlan,omitempty"` - Name string `json:"name,omitempty"` - Description string `json:"description,omitempty"` - Tags []string `json:"tags,omitempty"` - - // Speed is a bps representation of the VirtualCircuit throughput. This is informational only, the field is a user-controlled description of the speed. It may be presented as a whole number with a bps, mpbs, or gbps suffix (or the respective initial). - Speed string `json:"speed,omitempty"` -} - -type VirtualCircuitServiceOp struct { - client *Client -} - -type virtualCircuitsRoot struct { - VirtualCircuits []VirtualCircuit `json:"virtual_circuits"` - Meta meta `json:"meta"` -} - -type VirtualCircuit struct { - ID string `json:"id"` - Name string `json:"name,omitempty"` - Description string `json:"description,omitempty"` - // Speed of the VirtualCircuit in bps - Speed int `json:"speed,omitempty"` - Status VCStatus `json:"status,omitempty"` - VNID int `json:"vnid,omitempty"` - NniVNID int `json:"nni_vnid,omitempty"` - NniVLAN int `json:"nni_vlan,omitempty"` - Project *Project `json:"project,omitempty"` - Port *ConnectionPort `json:"port,omitempty"` - VirtualNetwork *VirtualNetwork `json:"virtual_network,omitempty"` - Tags []string `json:"tags,omitempty"` - // VRF connected to the Virtual Circuit - VRF *VRF `json:"vrf,omitempty"` - - // PeerASN (optional, required with VRFID) The BGP ASN of the device the switch will peer with. Can be the used across several VCs, but cannot be the same as the local_asn. - PeerASN int `json:"peer_asn,omitempty"` - - // Subnet (returned with VRF) A subnet from one of the IP blocks associated with the VRF that we - // will help create an IP reservation for. Can only be either a /30 or /31. - // * For a /31 block, it will only have two IP addresses, which will be used for the metal_ip and customer_ip. - // * For a /30 block, it will have four IP - // addresses, but the first and last IP addresses are not usable. We will - // default to the first usable IP address for the metal_ip. - Subnet string `json:"subnet,omitempty"` - - // MetalIP (returned with VRF) The IP address that’s set as “our” IP that is - // configured on the rack_local_vlan SVI. Will default to the first usable - // IP in the subnet. - MetalIP string `json:"metal_ip,omitempty"` - - // CustomerIP (returned with VRF) The IP address set as the customer IP which the CSR - // switch will peer with. Will default to the other usable IP in the subnet. - CustomerIP string `json:"customer_ip,omitempty"` - - // MD5 (returned with VRF) The password that can be set for the VRF BGP peer - MD5 string `json:"md5,omitempty"` -} - -func (s *VirtualCircuitServiceOp) do(method, apiPathQuery string, req interface{}) (*VirtualCircuit, *Response, error) { - vc := new(VirtualCircuit) - resp, err := s.client.DoRequest(method, apiPathQuery, req, vc) - if err != nil { - return nil, resp, err - } - return vc, resp, err -} - -func (s *VirtualCircuitServiceOp) Update(vcID string, req *VCUpdateRequest, opts *GetOptions) (*VirtualCircuit, *Response, error) { - if validateErr := ValidateUUID(vcID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(virtualCircuitBasePath, vcID) - apiPathQuery := opts.WithQuery(endpointPath) - return s.do("PUT", apiPathQuery, req) -} - -func (s *VirtualCircuitServiceOp) Events(id string, opts *GetOptions) ([]Event, *Response, error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(virtualCircuitBasePath, id, eventBasePath) - return listEvents(s.client, apiPath, opts) -} - -func (s *VirtualCircuitServiceOp) Get(id string, opts *GetOptions) (*VirtualCircuit, *Response, error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(virtualCircuitBasePath, id) - apiPathQuery := opts.WithQuery(endpointPath) - return s.do("GET", apiPathQuery, nil) -} - -func (s *VirtualCircuitServiceOp) Delete(id string) (*Response, error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(virtualCircuitBasePath, id) - return s.client.DoRequest("DELETE", apiPath, nil, nil) -} - -func (s *VirtualCircuitServiceOp) Create(projectID, connID, portID string, request *VCCreateRequest, opts *GetOptions) (*VirtualCircuit, *Response, error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - if validateErr := ValidateUUID(connID); validateErr != nil { - return nil, nil, validateErr - } - if validateErr := ValidateUUID(portID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(projectBasePath, projectID, connectionBasePath, connID, portBasePath, portID, virtualCircuitBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - return s.do("POST", apiPathQuery, request) -} diff --git a/vendor/github.com/packethost/packngo/virtualnetworks.go b/vendor/github.com/packethost/packngo/virtualnetworks.go deleted file mode 100644 index 48aceb4a..00000000 --- a/vendor/github.com/packethost/packngo/virtualnetworks.go +++ /dev/null @@ -1,117 +0,0 @@ -package packngo - -import ( - "path" -) - -const virtualNetworkBasePath = "/virtual-networks" - -// DevicePortService handles operations on a port which belongs to a particular device -type ProjectVirtualNetworkService interface { - List(projectID string, opts *ListOptions) (*VirtualNetworkListResponse, *Response, error) - Create(*VirtualNetworkCreateRequest) (*VirtualNetwork, *Response, error) - Get(string, *GetOptions) (*VirtualNetwork, *Response, error) - Delete(virtualNetworkID string) (*Response, error) -} - -type VirtualNetwork struct { - ID string `json:"id"` - Description string `json:"description,omitempty"` // TODO: field can be null - VXLAN int `json:"vxlan,omitempty"` - FacilityCode string `json:"facility_code,omitempty"` - MetroCode string `json:"metro_code,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - Href string `json:"href"` - Project *Project `json:"assigned_to,omitempty"` - Facility *Facility `json:"facility,omitempty"` - Metro *Metro `json:"metro,omitempty"` - Instances []*Device `json:"instances,omitempty"` -} - -type ProjectVirtualNetworkServiceOp struct { - client *Client -} - -type VirtualNetworkListResponse struct { - VirtualNetworks []VirtualNetwork `json:"virtual_networks"` -} - -func (i *ProjectVirtualNetworkServiceOp) List(projectID string, opts *ListOptions) (*VirtualNetworkListResponse, *Response, error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(projectBasePath, projectID, virtualNetworkBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - output := new(VirtualNetworkListResponse) - - resp, err := i.client.DoRequest("GET", apiPathQuery, nil, output) - if err != nil { - return nil, nil, err - } - - return output, resp, nil -} - -type VirtualNetworkCreateRequest struct { - // ProjectID of the project where the VLAN will be made available. - ProjectID string `json:"project_id"` - - // Description is a user supplied description of the VLAN. - Description string `json:"description"` - - // TODO: default Description is null when not specified. Permitting *string here would require changing VirtualNetwork.Description to *string too. - - // Facility in which to create the VLAN. Mutually exclusive with Metro. - Facility string `json:"facility,omitempty"` - - // Metro in which to create the VLAN. Mutually exclusive with Facility. - Metro string `json:"metro,omitempty"` - - // VXLAN is the VLAN ID. VXLAN may be specified when Metro is defined. It is remotely incremented otherwise. Must be unique per Metro. - VXLAN int `json:"vxlan,omitempty"` -} - -func (i *ProjectVirtualNetworkServiceOp) Get(vlanID string, opts *GetOptions) (*VirtualNetwork, *Response, error) { - if validateErr := ValidateUUID(vlanID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(virtualNetworkBasePath, vlanID) - apiPathQuery := opts.WithQuery(endpointPath) - vlan := new(VirtualNetwork) - - resp, err := i.client.DoRequest("GET", apiPathQuery, nil, vlan) - if err != nil { - return nil, resp, err - } - - return vlan, resp, err -} - -func (i *ProjectVirtualNetworkServiceOp) Create(input *VirtualNetworkCreateRequest) (*VirtualNetwork, *Response, error) { - // TODO: May need to add timestamp to output from 'post' request - // for the 'created_at' attribute of VirtualNetwork struct since - // API response doesn't include it - apiPath := path.Join(projectBasePath, input.ProjectID, virtualNetworkBasePath) - output := new(VirtualNetwork) - - resp, err := i.client.DoRequest("POST", apiPath, input, output) - if err != nil { - return nil, nil, err - } - - return output, resp, nil -} - -func (i *ProjectVirtualNetworkServiceOp) Delete(virtualNetworkID string) (*Response, error) { - if validateErr := ValidateUUID(virtualNetworkID); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(virtualNetworkBasePath, virtualNetworkID) - - resp, err := i.client.DoRequest("DELETE", apiPath, nil, nil) - if err != nil { - return nil, err - } - - return resp, nil -} diff --git a/vendor/github.com/packethost/packngo/vlan_assignments.go b/vendor/github.com/packethost/packngo/vlan_assignments.go deleted file mode 100644 index 211b9857..00000000 --- a/vendor/github.com/packethost/packngo/vlan_assignments.go +++ /dev/null @@ -1,215 +0,0 @@ -package packngo - -import ( - "path" -) - -const ( - portVLANAssignmentsPath = "vlan-assignments" - portVLANAssignmentsBatchPath = "batches" -) - -type vlanAssignmentsRoot struct { - VLANAssignments []VLANAssignment `json:"vlan_assignments"` - Meta meta `json:"meta"` -} - -type vlanAssignmentBatchesRoot struct { - VLANAssignmentBatches []VLANAssignmentBatch `json:"batches"` - Meta meta `json:"meta"` -} - -// VLANAssignmentService handles operations on a VLANAssignment -type VLANAssignmentService interface { - Get(string, string, *GetOptions) (*VLANAssignment, *Response, error) - List(string, *ListOptions) ([]VLANAssignment, *Response, error) - - GetBatch(string, string, *GetOptions) (*VLANAssignmentBatch, *Response, error) - ListBatch(string, *ListOptions) ([]VLANAssignmentBatch, *Response, error) - CreateBatch(string, *VLANAssignmentBatchCreateRequest, *GetOptions) (*VLANAssignmentBatch, *Response, error) -} - -type VLANAssignmentServiceOp struct { - client requestDoer -} - -var _ VLANAssignmentService = (*VLANAssignmentServiceOp)(nil) - -type VLANAssignmentBatchState string - -const ( - VLANAssignmentBatchQueued VLANAssignmentBatchState = "queued" - VLANAssignmentBatchInProgress VLANAssignmentBatchState = "in_progress" - VLANAssignmentBatchCompleted VLANAssignmentBatchState = "completed" - VLANAssignmentBatchFailed VLANAssignmentBatchState = "failed" -) - -type VLANAssignmentState string - -const ( - VLANAssignmentAssigned VLANAssignmentState = "assigned" - VLANAssignmentUnassigned VLANAssignmentState = "unassigned" -) - -// VLANAssignment struct for VLANAssignmentService.Get represents a port VLAN assignment that has been enacted -type VLANAssignment struct { - // ID of the assignment - ID string `json:"id,omitempty"` - - CreatedAt Timestamp `json:"created_at,omitempty"` - UpdatedAt Timestamp `json:"updated_at,omitempty"` - - // Native indicates the VLAN is the native VLAN on the port and packets for this vlan will be untagged - Native bool `json:"native,omitempty"` - - // State of the assignment - State VLANAssignmentState `json:"state,omitempty"` - - // VLAN is the VirtualNetwork.VXLAN of the VLAN the assignment was made to - VLAN int `json:"vlan,omitempty"` - - // Port is a reference to the Port the assignment was made on - Port *Port `json:"port,omitempty"` - - // VirtualNetwork is a reference to the VLAN the assignment was made to - VirtualNetwork *VirtualNetwork `json:"virtual_network,omitempty"` -} - -// BatchedVLANAssignment represents the data requested in the batch before being processed. ID represents the VLAN ID, not the VLAN Assignment ID. -type BatchedVLANAssignment struct { - // VirtualNetworkID is the VirtualNetwork.ID of the VLAN the assignment was made to - VirtualNetworkID string `json:"id,omitempty"` - - // Native indicates the VLAN is the native VLAN on the port and packets for this vlan will be untagged - Native bool `json:"native,omitempty"` - - // State of the assignment - State VLANAssignmentState `json:"state,omitempty"` - - // VLAN is the VirtualNetwork.VXLAN of the VLAN the assignment was made to - VLAN int `json:"vlan,omitempty"` -} - -// VLANAssignmentBatch struct for VLANAssignmentBatch -type VLANAssignmentBatch struct { - ID string `json:"id,omitempty"` - ErrorMessages []string `json:"error_messages,omitempty"` - Quantity int `json:"quantity,omitempty"` - State VLANAssignmentBatchState `json:"state,omitempty"` - CreatedAt Timestamp `json:"created_at,omitempty"` - UpdatedAt Timestamp `json:"updated_at,omitempty"` - Port *Port `json:"port,omitempty"` - Project *Project `json:"project,omitempty"` - VLANAssignments []BatchedVLANAssignment `json:"vlan_assignments,omitempty"` -} - -// VLANAssignmentBatchCreateRequest struct for VLANAssignmentBatch Create -type VLANAssignmentBatchCreateRequest struct { - VLANAssignments []VLANAssignmentCreateRequest `json:"vlan_assignments"` -} - -// VLANAssignmentCreateRequest struct for VLANAssignmentBatchCreateRequest -type VLANAssignmentCreateRequest struct { - VLAN string `json:"vlan,omitempty"` - State VLANAssignmentState `json:"state,omitempty"` - Native *bool `json:"native,omitempty"` -} - -// List returns VLANAssignmentBatches -func (s *VLANAssignmentServiceOp) ListBatch(portID string, opts *ListOptions) (results []VLANAssignmentBatch, resp *Response, err error) { - if validateErr := ValidateUUID(portID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(portBasePath, portID, portVLANAssignmentsPath, portVLANAssignmentsBatchPath) - apiPathQuery := opts.WithQuery(endpointPath) - - for { - subset := new(vlanAssignmentBatchesRoot) - - resp, err = s.client.DoRequest("GET", apiPathQuery, nil, subset) - if err != nil { - return nil, resp, err - } - - results = append(results, subset.VLANAssignmentBatches...) - if apiPathQuery = nextPage(subset.Meta, opts); apiPathQuery != "" { - continue - } - return - } -} - -// Get returns a VLANAssignmentBatch by id -func (s *VLANAssignmentServiceOp) GetBatch(portID, batchID string, opts *GetOptions) (*VLANAssignmentBatch, *Response, error) { - if validateErr := ValidateUUID(portID); validateErr != nil { - return nil, nil, validateErr - } - if validateErr := ValidateUUID(batchID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(portBasePath, portID, portVLANAssignmentsPath, portVLANAssignmentsBatchPath, batchID) - apiPathQuery := opts.WithQuery(endpointPath) - batch := new(VLANAssignmentBatch) - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, batch) - if err != nil { - return nil, resp, err - } - return batch, resp, err -} - -// Create creates VLANAssignmentBatch objects -func (s *VLANAssignmentServiceOp) CreateBatch(portID string, request *VLANAssignmentBatchCreateRequest, opts *GetOptions) (*VLANAssignmentBatch, *Response, error) { - if validateErr := ValidateUUID(portID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(portBasePath, portID, portVLANAssignmentsPath, portVLANAssignmentsBatchPath) - apiPathQuery := opts.WithQuery(endpointPath) - batch := new(VLANAssignmentBatch) - resp, err := s.client.DoRequest("POST", apiPathQuery, request, batch) - if err != nil { - return nil, resp, err - } - return batch, resp, err -} - -// List returns VLANAssignment -func (s *VLANAssignmentServiceOp) List(portID string, opts *ListOptions) (results []VLANAssignment, resp *Response, err error) { - if validateErr := ValidateUUID(portID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(portBasePath, portID, portVLANAssignmentsPath) - apiPathQuery := opts.WithQuery(endpointPath) - - for { - subset := new(vlanAssignmentsRoot) - - resp, err = s.client.DoRequest("GET", apiPathQuery, nil, subset) - if err != nil { - return nil, resp, err - } - - results = append(results, subset.VLANAssignments...) - if apiPathQuery = nextPage(subset.Meta, opts); apiPathQuery != "" { - continue - } - return - } -} - -// Get returns a VLANAssignment by id -func (s *VLANAssignmentServiceOp) Get(portID, assignmentID string, opts *GetOptions) (*VLANAssignment, *Response, error) { - if validateErr := ValidateUUID(portID); validateErr != nil { - return nil, nil, validateErr - } - if validateErr := ValidateUUID(assignmentID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(portBasePath, portID, portVLANAssignmentsPath, assignmentID) - apiPathQuery := opts.WithQuery(endpointPath) - VLANAssignment := new(VLANAssignment) - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, VLANAssignment) - if err != nil { - return nil, resp, err - } - return VLANAssignment, resp, err -} diff --git a/vendor/github.com/packethost/packngo/volumes.go b/vendor/github.com/packethost/packngo/volumes.go deleted file mode 100644 index bc6f7993..00000000 --- a/vendor/github.com/packethost/packngo/volumes.go +++ /dev/null @@ -1,264 +0,0 @@ -package packngo - -import ( - "path" -) - -const ( - volumeBasePath = "/storage" - attachmentsBasePath = "/attachments" -) - -// VolumeService interface defines available Volume methods -type VolumeService interface { - List(string, *ListOptions) ([]Volume, *Response, error) - Get(string, *GetOptions) (*Volume, *Response, error) - Update(string, *VolumeUpdateRequest) (*Volume, *Response, error) - Delete(string) (*Response, error) - Create(*VolumeCreateRequest, string) (*Volume, *Response, error) - Lock(string) (*Response, error) - Unlock(string) (*Response, error) -} - -// VolumeAttachmentService defines attachment methdods -type VolumeAttachmentService interface { - Get(string, *GetOptions) (*VolumeAttachment, *Response, error) - Create(string, string) (*VolumeAttachment, *Response, error) - Delete(string) (*Response, error) -} - -type volumesRoot struct { - Volumes []Volume `json:"volumes"` - Meta meta `json:"meta"` -} - -// Volume represents a volume -type Volume struct { - Attachments []*VolumeAttachment `json:"attachments,omitempty"` - BillingCycle string `json:"billing_cycle,omitempty"` - Created string `json:"created_at,omitempty"` - Description string `json:"description,omitempty"` - Facility *Facility `json:"facility,omitempty"` - Href string `json:"href,omitempty"` - ID string `json:"id"` - Locked bool `json:"locked,omitempty"` - Name string `json:"name,omitempty"` - Plan *Plan `json:"plan,omitempty"` - Project *Project `json:"project,omitempty"` - Size int `json:"size,omitempty"` - SnapshotPolicies []*SnapshotPolicy `json:"snapshot_policies,omitempty"` - State string `json:"state,omitempty"` - Updated string `json:"updated_at,omitempty"` -} - -// SnapshotPolicy used to execute actions on volume -type SnapshotPolicy struct { - ID string `json:"id"` - Href string `json:"href"` - SnapshotFrequency string `json:"snapshot_frequency,omitempty"` - SnapshotCount int `json:"snapshot_count,omitempty"` -} - -func (v Volume) String() string { - return Stringify(v) -} - -// VolumeCreateRequest type used to create an Equinix Metal volume -type VolumeCreateRequest struct { - BillingCycle string `json:"billing_cycle"` - Description string `json:"description,omitempty"` - Locked bool `json:"locked,omitempty"` - Size int `json:"size"` - PlanID string `json:"plan_id"` - FacilityID string `json:"facility_id"` - SnapshotPolicies []*SnapshotPolicy `json:"snapshot_policies,omitempty"` -} - -func (v VolumeCreateRequest) String() string { - return Stringify(v) -} - -// VolumeUpdateRequest type used to update an Equinix Metal volume -type VolumeUpdateRequest struct { - Description *string `json:"description,omitempty"` - PlanID *string `json:"plan_id,omitempty"` - Size *int `json:"size,omitempty"` - BillingCycle *string `json:"billing_cycle,omitempty"` -} - -// VolumeAttachment is a type from Equinix Metal API -type VolumeAttachment struct { - Href string `json:"href"` - ID string `json:"id"` - Volume Volume `json:"volume"` - Device Device `json:"device"` -} - -func (v VolumeUpdateRequest) String() string { - return Stringify(v) -} - -// VolumeAttachmentServiceOp implements VolumeService -type VolumeAttachmentServiceOp struct { - client *Client -} - -// VolumeServiceOp implements VolumeService -type VolumeServiceOp struct { - client *Client -} - -// List returns the volumes for a project -func (v *VolumeServiceOp) List(projectID string, opts *ListOptions) (volumes []Volume, resp *Response, err error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(projectBasePath, projectID, volumeBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - for { - subset := new(volumesRoot) - - resp, err = v.client.DoRequest("GET", apiPathQuery, nil, subset) - if err != nil { - return nil, resp, err - } - - volumes = append(volumes, subset.Volumes...) - - if apiPathQuery = nextPage(subset.Meta, opts); apiPathQuery != "" { - continue - } - return - } -} - -// Get returns a volume by id -func (v *VolumeServiceOp) Get(volumeID string, opts *GetOptions) (*Volume, *Response, error) { - if validateErr := ValidateUUID(volumeID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(volumeBasePath, volumeID) - apiPathQuery := opts.WithQuery(endpointPath) - volume := new(Volume) - - resp, err := v.client.DoRequest("GET", apiPathQuery, nil, volume) - if err != nil { - return nil, resp, err - } - - return volume, resp, err -} - -// Update updates a volume -func (v *VolumeServiceOp) Update(id string, updateRequest *VolumeUpdateRequest) (*Volume, *Response, error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(volumeBasePath, id) - volume := new(Volume) - - resp, err := v.client.DoRequest("PATCH", apiPath, updateRequest, volume) - if err != nil { - return nil, resp, err - } - - return volume, resp, err -} - -// Delete deletes a volume -func (v *VolumeServiceOp) Delete(volumeID string) (*Response, error) { - if validateErr := ValidateUUID(volumeID); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(volumeBasePath, volumeID) - - return v.client.DoRequest("DELETE", apiPath, nil, nil) -} - -// Create creates a new volume for a project -func (v *VolumeServiceOp) Create(createRequest *VolumeCreateRequest, projectID string) (*Volume, *Response, error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - url := path.Join(projectBasePath, projectID, volumeBasePath) - volume := new(Volume) - - resp, err := v.client.DoRequest("POST", url, createRequest, volume) - if err != nil { - return nil, resp, err - } - - return volume, resp, err -} - -// Attachments - -// Create Attachment, i.e. attach volume to a device -func (v *VolumeAttachmentServiceOp) Create(volumeID, deviceID string) (*VolumeAttachment, *Response, error) { - if validateErr := ValidateUUID(volumeID); validateErr != nil { - return nil, nil, validateErr - } - if validateErr := ValidateUUID(deviceID); validateErr != nil { - return nil, nil, validateErr - } - url := path.Join(volumeBasePath, volumeID, attachmentsBasePath) - volAttachParam := map[string]string{ - "device_id": deviceID, - } - volumeAttachment := new(VolumeAttachment) - - resp, err := v.client.DoRequest("POST", url, volAttachParam, volumeAttachment) - if err != nil { - return nil, resp, err - } - return volumeAttachment, resp, nil -} - -// Get gets attachment by id -func (v *VolumeAttachmentServiceOp) Get(attachmentID string, opts *GetOptions) (*VolumeAttachment, *Response, error) { - if validateErr := ValidateUUID(attachmentID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(volumeBasePath, attachmentsBasePath, attachmentID) - apiPathQuery := opts.WithQuery(endpointPath) - volumeAttachment := new(VolumeAttachment) - - resp, err := v.client.DoRequest("GET", apiPathQuery, nil, volumeAttachment) - if err != nil { - return nil, resp, err - } - - return volumeAttachment, resp, nil -} - -// Delete deletes attachment by id -func (v *VolumeAttachmentServiceOp) Delete(attachmentID string) (*Response, error) { - if validateErr := ValidateUUID(attachmentID); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(volumeBasePath, attachmentsBasePath, attachmentID) - - return v.client.DoRequest("DELETE", apiPath, nil, nil) -} - -// Lock sets a volume to "locked" -func (v *VolumeServiceOp) Lock(id string) (*Response, error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(volumeBasePath, id) - action := lockType{Locked: true} - - return v.client.DoRequest("PATCH", apiPath, action, nil) -} - -// Unlock sets a volume to "unlocked" -func (v *VolumeServiceOp) Unlock(id string) (*Response, error) { - if validateErr := ValidateUUID(id); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(volumeBasePath, id) - action := lockType{Locked: false} - - return v.client.DoRequest("PATCH", apiPath, action, nil) -} diff --git a/vendor/github.com/packethost/packngo/vrf.go b/vendor/github.com/packethost/packngo/vrf.go deleted file mode 100644 index 23b1e030..00000000 --- a/vendor/github.com/packethost/packngo/vrf.go +++ /dev/null @@ -1,187 +0,0 @@ -package packngo - -import ( - "path" -) - -const ( - vrfBasePath = "/vrfs" -) - -type VRFService interface { - List(projectID string, opts *ListOptions) ([]VRF, *Response, error) - Create(projectID string, input *VRFCreateRequest) (*VRF, *Response, error) - Update(vrfID string, update *VRFUpdateRequest) (*VRF, *Response, error) - Get(vrfID string, opts *GetOptions) (*VRF, *Response, error) - ListIPs(vrfID string, opts *GetOptions) ([]IPAddressReservation, *Response, error) - Delete(vrfID string) (*Response, error) -} - -type VRF struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - LocalASN int `json:"local_asn,omitempty"` - IPRanges []string `json:"ip_ranges,omitempty"` - Project *Project `json:"project,omitempty"` - Metro *Metro `json:"metro,omitempty"` - Href string `json:"href"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -type VRFCreateRequest struct { - // Metro id or code - Metro string `json:"metro"` - - // Name is the name of the VRF. It must be unique per project. - Name string `json:"name"` - - // Description of the VRF to be created. - Description string `json:"description"` - - // LocalASN is the ASN of the local network. - LocalASN int `json:"local_asn,omitempty"` - - // IPRanges is a list of all IPv4 and IPv6 Ranges that will be available to - // BGP Peers. IPv4 addresses must be /8 or smaller with a minimum size of - // /29. IPv6 must be /56 or smaller with a minimum size of /64. Ranges must - // not overlap other ranges within the VRF. - IPRanges []string `json:"ip_ranges,omitempty"` -} - -type VRFUpdateRequest struct { - // Name is the name of the VRF. It must be unique per project. - Name *string `json:"name,omitempty"` - - // Description of the VRF to be created. - Description *string `json:"description,omitempty"` - - // LocalASN is the ASN of the local network. - LocalASN *int `json:"local_asn,omitempty"` - - // IPRanges is a list of all IPv4 and IPv6 Ranges that will be available to - // BGP Peers. IPv4 addresses must be /8 or smaller with a minimum size of - // /29. IPv6 must be /56 or smaller with a minimum size of /64. Ranges must - // not overlap other ranges within the VRF. - IPRanges *[]string `json:"ip_ranges,omitempty"` -} - -type VRFServiceOp struct { - client *Client -} - -func (s *VRFServiceOp) List(projectID string, opts *ListOptions) (vrfs []VRF, resp *Response, err error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - type vrfsRoot struct { - VRFs []VRF `json:"vrfs"` - Meta meta `json:"meta"` - } - - endpointPath := path.Join(projectBasePath, projectID, vrfBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - - for { - subset := new(vrfsRoot) - - resp, err = s.client.DoRequest("GET", apiPathQuery, nil, subset) - if err != nil { - return nil, resp, err - } - - vrfs = append(vrfs, subset.VRFs...) - - if apiPathQuery = nextPage(subset.Meta, opts); apiPathQuery != "" { - continue - } - return - } -} - -func (s *VRFServiceOp) ListIPs(vrfID string, opts *ListOptions) (ips []IPAddressReservation, resp *Response, err error) { - if validateErr := ValidateUUID(vrfID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(vrfBasePath, vrfID, ipBasePath) - apiPathQuery := opts.WithQuery(endpointPath) - - // ipList represents collection of IP Address reservations - type ipList struct { - IPs []IPAddressReservation `json:"ip_addresses,omitempty"` - } - - results := new(ipList) - - resp, err = s.client.DoRequest("GET", apiPathQuery, nil, results) - if err != nil { - return nil, resp, err - } - - return results.IPs, resp, err -} - -func (s *VRFServiceOp) Get(vrfID string, opts *GetOptions) (*VRF, *Response, error) { - if validateErr := ValidateUUID(vrfID); validateErr != nil { - return nil, nil, validateErr - } - endpointPath := path.Join(vrfBasePath, vrfID) - apiPathQuery := opts.WithQuery(endpointPath) - metalGateway := new(VRF) - - resp, err := s.client.DoRequest("GET", apiPathQuery, nil, metalGateway) - if err != nil { - return nil, resp, err - } - - return metalGateway, resp, err -} - -func (s *VRFServiceOp) Create(projectID string, input *VRFCreateRequest) (*VRF, *Response, error) { - if validateErr := ValidateUUID(projectID); validateErr != nil { - return nil, nil, validateErr - } - apiPath := path.Join(projectBasePath, projectID, vrfBasePath) - output := new(VRF) - - resp, err := s.client.DoRequest("POST", apiPath, input, output) - if err != nil { - return nil, nil, err - } - - return output, resp, nil -} - -// Update updates an existing VRF -func (s *VRFServiceOp) Update(vrfID string, updateRequest *VRFUpdateRequest) (*VRF, *Response, error) { - if validateErr := ValidateUUID(vrfID); validateErr != nil { - return nil, nil, validateErr - } - opts := &GetOptions{} - endpointPath := path.Join(vrfBasePath, vrfID) - apiPathQuery := opts.WithQuery(endpointPath) - - vrf := new(VRF) - - resp, err := s.client.DoRequest("PUT", apiPathQuery, updateRequest, vrf) - if err != nil { - return nil, resp, err - } - - return vrf, resp, err -} - -func (s *VRFServiceOp) Delete(vrfID string) (*Response, error) { - if validateErr := ValidateUUID(vrfID); validateErr != nil { - return nil, validateErr - } - apiPath := path.Join(vrfBasePath, vrfID) - - resp, err := s.client.DoRequest("DELETE", apiPath, nil, nil) - if err != nil { - return nil, err - } - - return resp, nil -} diff --git a/vendor/github.com/spf13/cobra/.golangci.yml b/vendor/github.com/spf13/cobra/.golangci.yml index a618ec24..2c8f4808 100644 --- a/vendor/github.com/spf13/cobra/.golangci.yml +++ b/vendor/github.com/spf13/cobra/.golangci.yml @@ -26,33 +26,28 @@ linters: - errcheck #- exhaustive #- funlen - - gas #- gochecknoinits - goconst - #- gocritic + - gocritic #- gocyclo - #- gofmt + - gofmt - goimports - - golint #- gomnd #- goprintffuncname - #- gosec - #- gosimple + - gosec + - gosimple - govet - ineffassign - - interfacer #- lll - - maligned - - megacheck - #- misspell + - misspell #- nakedret #- noctx - #- nolintlint + - nolintlint #- rowserrcheck #- scopelint - #- staticcheck + - staticcheck #- structcheck ! deprecated since v1.49.0; replaced by 'unused' - #- stylecheck + - stylecheck #- typecheck - unconvert #- unparam diff --git a/vendor/github.com/spf13/cobra/active_help.go b/vendor/github.com/spf13/cobra/active_help.go index 5f965e05..25c30e3c 100644 --- a/vendor/github.com/spf13/cobra/active_help.go +++ b/vendor/github.com/spf13/cobra/active_help.go @@ -17,21 +17,17 @@ package cobra import ( "fmt" "os" - "regexp" - "strings" ) const ( activeHelpMarker = "_activeHelp_ " // The below values should not be changed: programs will be using them explicitly // in their user documentation, and users will be using them explicitly. - activeHelpEnvVarSuffix = "_ACTIVE_HELP" - activeHelpGlobalEnvVar = "COBRA_ACTIVE_HELP" + activeHelpEnvVarSuffix = "ACTIVE_HELP" + activeHelpGlobalEnvVar = configEnvVarGlobalPrefix + "_" + activeHelpEnvVarSuffix activeHelpGlobalDisable = "0" ) -var activeHelpEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`) - // AppendActiveHelp adds the specified string to the specified array to be used as ActiveHelp. // Such strings will be processed by the completion script and will be shown as ActiveHelp // to the user. @@ -60,8 +56,5 @@ func GetActiveHelpConfig(cmd *Command) string { // variable. It has the format _ACTIVE_HELP where is the name of the // root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`. func activeHelpEnvVar(name string) string { - // This format should not be changed: users will be using it explicitly. - activeHelpEnvVar := strings.ToUpper(fmt.Sprintf("%s%s", name, activeHelpEnvVarSuffix)) - activeHelpEnvVar = activeHelpEnvVarPrefixSubstRegexp.ReplaceAllString(activeHelpEnvVar, "_") - return activeHelpEnvVar + return configEnvVar(name, activeHelpEnvVarSuffix) } diff --git a/vendor/github.com/spf13/cobra/args.go b/vendor/github.com/spf13/cobra/args.go index e79ec33a..ed1e70ce 100644 --- a/vendor/github.com/spf13/cobra/args.go +++ b/vendor/github.com/spf13/cobra/args.go @@ -52,9 +52,9 @@ func OnlyValidArgs(cmd *Command, args []string) error { if len(cmd.ValidArgs) > 0 { // Remove any description that may be included in ValidArgs. // A description is following a tab character. - var validArgs []string + validArgs := make([]string, 0, len(cmd.ValidArgs)) for _, v := range cmd.ValidArgs { - validArgs = append(validArgs, strings.Split(v, "\t")[0]) + validArgs = append(validArgs, strings.SplitN(v, "\t", 2)[0]) } for _, v := range args { if !stringInSlice(v, validArgs) { diff --git a/vendor/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go index 8a531518..f4d198cb 100644 --- a/vendor/github.com/spf13/cobra/bash_completions.go +++ b/vendor/github.com/spf13/cobra/bash_completions.go @@ -597,19 +597,16 @@ func writeRequiredFlag(buf io.StringWriter, cmd *Command) { if nonCompletableFlag(flag) { return } - for key := range flag.Annotations { - switch key { - case BashCompOneRequiredFlag: - format := " must_have_one_flag+=(\"--%s" - if flag.Value.Type() != "bool" { - format += "=" - } - format += cbn - WriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name)) - - if len(flag.Shorthand) > 0 { - WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand)) - } + if _, ok := flag.Annotations[BashCompOneRequiredFlag]; ok { + format := " must_have_one_flag+=(\"--%s" + if flag.Value.Type() != "bool" { + format += "=" + } + format += cbn + WriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name)) + + if len(flag.Shorthand) > 0 { + WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand)) } } }) @@ -621,7 +618,7 @@ func writeRequiredNouns(buf io.StringWriter, cmd *Command) { for _, value := range cmd.ValidArgs { // Remove any description that may be included following a tab character. // Descriptions are not supported by bash completion. - value = strings.Split(value, "\t")[0] + value = strings.SplitN(value, "\t", 2)[0] WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_noun+=(%q)\n", value)) } if cmd.ValidArgsFunction != nil { diff --git a/vendor/github.com/spf13/cobra/cobra.go b/vendor/github.com/spf13/cobra/cobra.go index a6b160ce..e0b0947b 100644 --- a/vendor/github.com/spf13/cobra/cobra.go +++ b/vendor/github.com/spf13/cobra/cobra.go @@ -193,8 +193,6 @@ func ld(s, t string, ignoreCase bool) int { d := make([][]int, len(s)+1) for i := range d { d[i] = make([]int, len(t)+1) - } - for i := range d { d[i][0] = i } for j := range d[0] { diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go index 2fbe6c13..54748fc6 100644 --- a/vendor/github.com/spf13/cobra/command.go +++ b/vendor/github.com/spf13/cobra/command.go @@ -154,8 +154,10 @@ type Command struct { // pflags contains persistent flags. pflags *flag.FlagSet // lflags contains local flags. + // This field does not represent internal state, it's used as a cache to optimise LocalFlags function call lflags *flag.FlagSet // iflags contains inherited flags. + // This field does not represent internal state, it's used as a cache to optimise InheritedFlags function call iflags *flag.FlagSet // parentsPflags is all persistent flags of cmd's parents. parentsPflags *flag.FlagSet @@ -706,7 +708,7 @@ Loop: // This is not a flag or a flag value. Check to see if it matches what we're looking for, and if so, // return the args, excluding the one at this position. if s == x { - ret := []string{} + ret := make([]string, 0, len(args)-1) ret = append(ret, args[:pos]...) ret = append(ret, args[pos+1:]...) return ret @@ -754,14 +756,14 @@ func (c *Command) findSuggestions(arg string) string { if c.SuggestionsMinimumDistance <= 0 { c.SuggestionsMinimumDistance = 2 } - suggestionsString := "" + var sb strings.Builder if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 { - suggestionsString += "\n\nDid you mean this?\n" + sb.WriteString("\n\nDid you mean this?\n") for _, s := range suggestions { - suggestionsString += fmt.Sprintf("\t%v\n", s) + _, _ = fmt.Fprintf(&sb, "\t%v\n", s) } } - return suggestionsString + return sb.String() } func (c *Command) findNext(next string) *Command { @@ -873,7 +875,7 @@ func (c *Command) ArgsLenAtDash() int { func (c *Command) execute(a []string) (err error) { if c == nil { - return fmt.Errorf("Called Execute() on a nil Command") + return fmt.Errorf("called Execute() on a nil Command") } if len(c.Deprecated) > 0 { @@ -1187,10 +1189,11 @@ func (c *Command) InitDefaultHelpFlag() { c.mergePersistentFlags() if c.Flags().Lookup("help") == nil { usage := "help for " - if c.Name() == "" { + name := c.displayName() + if name == "" { usage += "this command" } else { - usage += c.Name() + usage += name } c.Flags().BoolP("help", "h", false, usage) _ = c.Flags().SetAnnotation("help", FlagSetByCobraAnnotation, []string{"true"}) @@ -1236,7 +1239,7 @@ func (c *Command) InitDefaultHelpCmd() { Use: "help [command]", Short: "Help about any command", Long: `Help provides help for any command in the application. -Simply type ` + c.Name() + ` help [path to command] for full details.`, +Simply type ` + c.displayName() + ` help [path to command] for full details.`, ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]string, ShellCompDirective) { var completions []string cmd, _, e := c.Root().Find(args) @@ -1427,6 +1430,10 @@ func (c *Command) CommandPath() string { if c.HasParent() { return c.Parent().CommandPath() + " " + c.Name() } + return c.displayName() +} + +func (c *Command) displayName() string { if displayName, ok := c.Annotations[CommandDisplayNameAnnotation]; ok { return displayName } @@ -1436,10 +1443,11 @@ func (c *Command) CommandPath() string { // UseLine puts out the full usage for a given command (including parents). func (c *Command) UseLine() string { var useline string + use := strings.Replace(c.Use, c.Name(), c.displayName(), 1) if c.HasParent() { - useline = c.parent.CommandPath() + " " + c.Use + useline = c.parent.CommandPath() + " " + use } else { - useline = c.Use + useline = use } if c.DisableFlagsInUseLine { return useline @@ -1452,7 +1460,6 @@ func (c *Command) UseLine() string { // DebugFlags used to determine which flags have been assigned to which commands // and which persist. -// nolint:goconst func (c *Command) DebugFlags() { c.Println("DebugFlags called on", c.Name()) var debugflags func(*Command) @@ -1642,7 +1649,7 @@ func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) f // to this command (local and persistent declared here and by all parents). func (c *Command) Flags() *flag.FlagSet { if c.flags == nil { - c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) + c.flags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) if c.flagErrorBuf == nil { c.flagErrorBuf = new(bytes.Buffer) } @@ -1653,10 +1660,11 @@ func (c *Command) Flags() *flag.FlagSet { } // LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands. +// This function does not modify the flags of the current command, it's purpose is to return the current state. func (c *Command) LocalNonPersistentFlags() *flag.FlagSet { persistentFlags := c.PersistentFlags() - out := flag.NewFlagSet(c.Name(), flag.ContinueOnError) + out := flag.NewFlagSet(c.displayName(), flag.ContinueOnError) c.LocalFlags().VisitAll(func(f *flag.Flag) { if persistentFlags.Lookup(f.Name) == nil { out.AddFlag(f) @@ -1666,11 +1674,12 @@ func (c *Command) LocalNonPersistentFlags() *flag.FlagSet { } // LocalFlags returns the local FlagSet specifically set in the current command. +// This function does not modify the flags of the current command, it's purpose is to return the current state. func (c *Command) LocalFlags() *flag.FlagSet { c.mergePersistentFlags() if c.lflags == nil { - c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) + c.lflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) if c.flagErrorBuf == nil { c.flagErrorBuf = new(bytes.Buffer) } @@ -1693,11 +1702,12 @@ func (c *Command) LocalFlags() *flag.FlagSet { } // InheritedFlags returns all flags which were inherited from parent commands. +// This function does not modify the flags of the current command, it's purpose is to return the current state. func (c *Command) InheritedFlags() *flag.FlagSet { c.mergePersistentFlags() if c.iflags == nil { - c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) + c.iflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) if c.flagErrorBuf == nil { c.flagErrorBuf = new(bytes.Buffer) } @@ -1718,6 +1728,7 @@ func (c *Command) InheritedFlags() *flag.FlagSet { } // NonInheritedFlags returns all flags which were not inherited from parent commands. +// This function does not modify the flags of the current command, it's purpose is to return the current state. func (c *Command) NonInheritedFlags() *flag.FlagSet { return c.LocalFlags() } @@ -1725,7 +1736,7 @@ func (c *Command) NonInheritedFlags() *flag.FlagSet { // PersistentFlags returns the persistent FlagSet specifically set in the current command. func (c *Command) PersistentFlags() *flag.FlagSet { if c.pflags == nil { - c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) + c.pflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) if c.flagErrorBuf == nil { c.flagErrorBuf = new(bytes.Buffer) } @@ -1738,9 +1749,9 @@ func (c *Command) PersistentFlags() *flag.FlagSet { func (c *Command) ResetFlags() { c.flagErrorBuf = new(bytes.Buffer) c.flagErrorBuf.Reset() - c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) + c.flags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) c.flags.SetOutput(c.flagErrorBuf) - c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) + c.pflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) c.pflags.SetOutput(c.flagErrorBuf) c.lflags = nil @@ -1857,7 +1868,7 @@ func (c *Command) mergePersistentFlags() { // If c.parentsPflags == nil, it makes new. func (c *Command) updateParentsPflags() { if c.parentsPflags == nil { - c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) + c.parentsPflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) c.parentsPflags.SetOutput(c.flagErrorBuf) c.parentsPflags.SortFlags = false } diff --git a/vendor/github.com/spf13/cobra/completions.go b/vendor/github.com/spf13/cobra/completions.go index b60f6b20..c0c08b05 100644 --- a/vendor/github.com/spf13/cobra/completions.go +++ b/vendor/github.com/spf13/cobra/completions.go @@ -17,6 +17,8 @@ package cobra import ( "fmt" "os" + "regexp" + "strconv" "strings" "sync" @@ -211,24 +213,29 @@ func (c *Command) initCompleteCmd(args []string) { // 2- Even without completions, we need to print the directive } - noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd) + noDescriptions := cmd.CalledAs() == ShellCompNoDescRequestCmd + if !noDescriptions { + if doDescriptions, err := strconv.ParseBool(getEnvConfig(cmd, configEnvVarSuffixDescriptions)); err == nil { + noDescriptions = !doDescriptions + } + } + noActiveHelp := GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable + out := finalCmd.OutOrStdout() for _, comp := range completions { - if GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable { - // Remove all activeHelp entries in this case - if strings.HasPrefix(comp, activeHelpMarker) { - continue - } + if noActiveHelp && strings.HasPrefix(comp, activeHelpMarker) { + // Remove all activeHelp entries if it's disabled. + continue } if noDescriptions { // Remove any description that may be included following a tab character. - comp = strings.Split(comp, "\t")[0] + comp = strings.SplitN(comp, "\t", 2)[0] } // Make sure we only write the first line to the output. // This is needed if a description contains a linebreak. // Otherwise the shell scripts will interpret the other lines as new flags // and could therefore provide a wrong completion. - comp = strings.Split(comp, "\n")[0] + comp = strings.SplitN(comp, "\n", 2)[0] // Finally trim the completion. This is especially important to get rid // of a trailing tab when there are no description following it. @@ -237,14 +244,14 @@ func (c *Command) initCompleteCmd(args []string) { // although there is no description). comp = strings.TrimSpace(comp) - // Print each possible completion to stdout for the completion script to consume. - fmt.Fprintln(finalCmd.OutOrStdout(), comp) + // Print each possible completion to the output for the completion script to consume. + fmt.Fprintln(out, comp) } // As the last printout, print the completion directive for the completion script to parse. // The directive integer must be that last character following a single colon (:). // The completion script expects : - fmt.Fprintf(finalCmd.OutOrStdout(), ":%d\n", directive) + fmt.Fprintf(out, ":%d\n", directive) // Print some helpful info to stderr for the user to understand. // Output from stderr must be ignored by the completion script. @@ -291,7 +298,7 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi } if err != nil { // Unable to find the real command. E.g., someInvalidCmd - return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs) + return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("unable to find a command for arguments: %v", trimmedArgs) } finalCmd.ctx = c.ctx @@ -899,3 +906,34 @@ func CompError(msg string) { func CompErrorln(msg string) { CompError(fmt.Sprintf("%s\n", msg)) } + +// These values should not be changed: users will be using them explicitly. +const ( + configEnvVarGlobalPrefix = "COBRA" + configEnvVarSuffixDescriptions = "COMPLETION_DESCRIPTIONS" +) + +var configEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`) + +// configEnvVar returns the name of the program-specific configuration environment +// variable. It has the format _ where is the name of the +// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`. +func configEnvVar(name, suffix string) string { + // This format should not be changed: users will be using it explicitly. + v := strings.ToUpper(fmt.Sprintf("%s_%s", name, suffix)) + v = configEnvVarPrefixSubstRegexp.ReplaceAllString(v, "_") + return v +} + +// getEnvConfig returns the value of the configuration environment variable +// _ where is the name of the root command in upper +// case, with all non-ASCII-alphanumeric characters replaced by `_`. +// If the value is empty or not set, the value of the environment variable +// COBRA_ is returned instead. +func getEnvConfig(cmd *Command, suffix string) string { + v := os.Getenv(configEnvVar(cmd.Root().Name(), suffix)) + if v == "" { + v = os.Getenv(configEnvVar(configEnvVarGlobalPrefix, suffix)) + } + return v +} diff --git a/vendor/github.com/spf13/cobra/flag_groups.go b/vendor/github.com/spf13/cobra/flag_groups.go index 0671ec5f..560612fd 100644 --- a/vendor/github.com/spf13/cobra/flag_groups.go +++ b/vendor/github.com/spf13/cobra/flag_groups.go @@ -23,9 +23,9 @@ import ( ) const ( - requiredAsGroup = "cobra_annotation_required_if_others_set" - oneRequired = "cobra_annotation_one_required" - mutuallyExclusive = "cobra_annotation_mutually_exclusive" + requiredAsGroupAnnotation = "cobra_annotation_required_if_others_set" + oneRequiredAnnotation = "cobra_annotation_one_required" + mutuallyExclusiveAnnotation = "cobra_annotation_mutually_exclusive" ) // MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors @@ -37,7 +37,7 @@ func (c *Command) MarkFlagsRequiredTogether(flagNames ...string) { if f == nil { panic(fmt.Sprintf("Failed to find flag %q and mark it as being required in a flag group", v)) } - if err := c.Flags().SetAnnotation(v, requiredAsGroup, append(f.Annotations[requiredAsGroup], strings.Join(flagNames, " "))); err != nil { + if err := c.Flags().SetAnnotation(v, requiredAsGroupAnnotation, append(f.Annotations[requiredAsGroupAnnotation], strings.Join(flagNames, " "))); err != nil { // Only errs if the flag isn't found. panic(err) } @@ -53,7 +53,7 @@ func (c *Command) MarkFlagsOneRequired(flagNames ...string) { if f == nil { panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a one-required flag group", v)) } - if err := c.Flags().SetAnnotation(v, oneRequired, append(f.Annotations[oneRequired], strings.Join(flagNames, " "))); err != nil { + if err := c.Flags().SetAnnotation(v, oneRequiredAnnotation, append(f.Annotations[oneRequiredAnnotation], strings.Join(flagNames, " "))); err != nil { // Only errs if the flag isn't found. panic(err) } @@ -70,7 +70,7 @@ func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) { panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a mutually exclusive flag group", v)) } // Each time this is called is a single new entry; this allows it to be a member of multiple groups if needed. - if err := c.Flags().SetAnnotation(v, mutuallyExclusive, append(f.Annotations[mutuallyExclusive], strings.Join(flagNames, " "))); err != nil { + if err := c.Flags().SetAnnotation(v, mutuallyExclusiveAnnotation, append(f.Annotations[mutuallyExclusiveAnnotation], strings.Join(flagNames, " "))); err != nil { panic(err) } } @@ -91,9 +91,9 @@ func (c *Command) ValidateFlagGroups() error { oneRequiredGroupStatus := map[string]map[string]bool{} mutuallyExclusiveGroupStatus := map[string]map[string]bool{} flags.VisitAll(func(pflag *flag.Flag) { - processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus) - processFlagForGroupAnnotation(flags, pflag, oneRequired, oneRequiredGroupStatus) - processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus) + processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus) + processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus) + processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus) }) if err := validateRequiredFlagGroups(groupStatus); err != nil { @@ -130,7 +130,7 @@ func processFlagForGroupAnnotation(flags *flag.FlagSet, pflag *flag.Flag, annota continue } - groupStatus[group] = map[string]bool{} + groupStatus[group] = make(map[string]bool, len(flagnames)) for _, name := range flagnames { groupStatus[group][name] = false } @@ -232,9 +232,9 @@ func (c *Command) enforceFlagGroupsForCompletion() { oneRequiredGroupStatus := map[string]map[string]bool{} mutuallyExclusiveGroupStatus := map[string]map[string]bool{} c.Flags().VisitAll(func(pflag *flag.Flag) { - processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus) - processFlagForGroupAnnotation(flags, pflag, oneRequired, oneRequiredGroupStatus) - processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus) + processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus) + processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus) + processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus) }) // If a flag that is part of a group is present, we make all the other flags @@ -253,17 +253,17 @@ func (c *Command) enforceFlagGroupsForCompletion() { // If none of the flags of a one-required group are present, we make all the flags // of that group required so that the shell completion suggests them automatically for flagList, flagnameAndStatus := range oneRequiredGroupStatus { - set := 0 + isSet := false - for _, isSet := range flagnameAndStatus { + for _, isSet = range flagnameAndStatus { if isSet { - set++ + break } } // None of the flags of the group are set, mark all flags in the group // as required - if set == 0 { + if !isSet { for _, fName := range strings.Split(flagList, " ") { _ = c.MarkFlagRequired(fName) } diff --git a/vendor/github.com/spf13/cobra/powershell_completions.go b/vendor/github.com/spf13/cobra/powershell_completions.go index 55195193..a830b7bc 100644 --- a/vendor/github.com/spf13/cobra/powershell_completions.go +++ b/vendor/github.com/spf13/cobra/powershell_completions.go @@ -28,8 +28,8 @@ import ( func genPowerShellComp(buf io.StringWriter, name string, includeDesc bool) { // Variables should not contain a '-' or ':' character nameForVar := name - nameForVar = strings.Replace(nameForVar, "-", "_", -1) - nameForVar = strings.Replace(nameForVar, ":", "_", -1) + nameForVar = strings.ReplaceAll(nameForVar, "-", "_") + nameForVar = strings.ReplaceAll(nameForVar, ":", "_") compCmd := ShellCompRequestCmd if !includeDesc { diff --git a/vendor/modules.txt b/vendor/modules.txt index a6b6e76e..a378ef81 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -223,8 +223,8 @@ github.com/hetznercloud/hcloud-go/hcloud/schema # github.com/inconshreveable/mousetrap v1.1.0 ## explicit; go 1.18 github.com/inconshreveable/mousetrap -# github.com/inlets/cloud-provision v0.6.9 -## explicit; go 1.21 +# github.com/inlets/cloud-provision v0.7.0 +## explicit; go 1.22 github.com/inlets/cloud-provision/provision # github.com/jmespath/go-jmespath v0.4.0 ## explicit; go 1.14 @@ -248,7 +248,6 @@ github.com/morikuni/aec github.com/ovh/go-ovh/ovh # github.com/packethost/packngo v0.31.0 ## explicit; go 1.16 -github.com/packethost/packngo # github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c ## explicit; go 1.14 github.com/pkg/browser @@ -288,10 +287,10 @@ github.com/scaleway/scaleway-sdk-go/logger github.com/scaleway/scaleway-sdk-go/namegenerator github.com/scaleway/scaleway-sdk-go/scw github.com/scaleway/scaleway-sdk-go/validation -# github.com/sethvargo/go-password v0.3.0 -## explicit; go 1.22 +# github.com/sethvargo/go-password v0.3.1 +## explicit; go 1.21 github.com/sethvargo/go-password/password -# github.com/spf13/cobra v1.8.0 +# github.com/spf13/cobra v1.8.1 ## explicit; go 1.15 github.com/spf13/cobra # github.com/spf13/pflag v1.0.5