NEW PROVIDER: Exoscale (#390)

* Add exoscale provider

Signed-off-by: Pierre-Emmanuel Jacquier <pierre-emmanuel.jacquier@epitech.eu>

* Fix validation

Signed-off-by: Pierre-Emmanuel Jacquier <pierre-emmanuel.jacquier@epitech.eu>

* Fix DualProvider

Signed-off-by: Pierre-Emmanuel Jacquier <pierre-emmanuel.jacquier@epitech.eu>
This commit is contained in:
Pierre-Emmanuel Jacquier 2019-02-22 15:10:23 +01:00 committed by Tom Limoncelli
parent 5c03761fa6
commit 511c0bf7de
54 changed files with 6605 additions and 0 deletions

View file

@ -18,6 +18,7 @@ Currently supported DNS providers:
- CloudFlare
- Digitalocean
- DNSimple
- Exoscale
- Gandi
- Google
- HEXONET

View file

@ -11,6 +11,7 @@
<th class="rotate"><div><span>CLOUDFLAREAPI</span></div></th>
<th class="rotate"><div><span>DIGITALOCEAN</span></div></th>
<th class="rotate"><div><span>DNSIMPLE</span></div></th>
<th class="rotate"><div><span>EXOSCALE</span></div></th>
<th class="rotate"><div><span>GANDI</span></div></th>
<th class="rotate"><div><span>GANDI-LIVEDNS</span></div></th>
<th class="rotate"><div><span>GCLOUD</span></div></th>
@ -51,6 +52,9 @@
<td class="danger">
<i class="fa fa-times text-danger" aria-hidden="true"></i>
</td>
<td class="danger">
<i class="fa fa-times text-danger" aria-hidden="true"></i>
</td>
<td class="success">
<i class="fa fa-check text-success" aria-hidden="true"></i>
</td>
@ -165,6 +169,9 @@
<td class="success">
<i class="fa fa-check text-success" aria-hidden="true"></i>
</td>
<td class="danger">
<i class="fa fa-times text-danger" aria-hidden="true"></i>
</td>
<td class="success">
<i class="fa fa-check text-success" aria-hidden="true"></i>
</td>
@ -221,6 +228,9 @@
<td class="success">
<i class="fa fa-check text-success" aria-hidden="true"></i>
</td>
<td class="success">
<i class="fa fa-check text-success" aria-hidden="true"></i>
</td>
<td><i class="fa fa-minus dim"></i></td>
<td><i class="fa fa-minus dim"></i></td>
<td><i class="fa fa-minus dim"></i></td>
@ -409,6 +419,9 @@
<td class="danger">
<i class="fa fa-times text-danger" aria-hidden="true"></i>
</td>
<td class="danger">
<i class="fa fa-times text-danger" aria-hidden="true"></i>
</td>
<td><i class="fa fa-minus dim"></i></td>
<td><i class="fa fa-minus dim"></i></td>
<td><i class="fa fa-minus dim"></i></td>
@ -451,6 +464,7 @@
</td>
<td><i class="fa fa-minus dim"></i></td>
<td><i class="fa fa-minus dim"></i></td>
<td><i class="fa fa-minus dim"></i></td>
<td class="success">
<i class="fa fa-check text-success" aria-hidden="true"></i>
</td>
@ -484,6 +498,7 @@
<td><i class="fa fa-minus dim"></i></td>
<td><i class="fa fa-minus dim"></i></td>
<td><i class="fa fa-minus dim"></i></td>
<td><i class="fa fa-minus dim"></i></td>
<td class="success">
<i class="fa fa-check text-success" aria-hidden="true"></i>
</td>
@ -505,6 +520,9 @@
<td class="danger" data-toggle="tooltip" data-container="body" data-placement="top" title="DNSimple does not allow sufficient control over the apex NS records">
<i class="fa has-tooltip fa-times text-danger" aria-hidden="true"></i>
</td>
<td class="danger">
<i class="fa fa-times text-danger" aria-hidden="true"></i>
</td>
<td><i class="fa fa-minus dim"></i></td>
<td><i class="fa fa-minus dim"></i></td>
<td class="success">
@ -555,6 +573,9 @@
<td class="danger">
<i class="fa fa-times text-danger" aria-hidden="true"></i>
</td>
<td class="danger">
<i class="fa fa-times text-danger" aria-hidden="true"></i>
</td>
<td class="danger" data-toggle="tooltip" data-container="body" data-placement="top" title="Can only manage domains registered through their service">
<i class="fa has-tooltip fa-times text-danger" aria-hidden="true"></i>
</td>
@ -615,6 +636,9 @@
<td class="success">
<i class="fa fa-check text-success" aria-hidden="true"></i>
</td>
<td class="success">
<i class="fa fa-check text-success" aria-hidden="true"></i>
</td>
<td class="danger">
<i class="fa fa-times text-danger" aria-hidden="true"></i>
</td>

View file

@ -23,6 +23,13 @@
"knownFailures": "20,21,22",
"token": "$DNSIMPLE_TOKEN"
},
"EXOSCALE": {
"dns-endpoint": "https://api.exoscale.ch/dns",
"apikey": "$EXOSCALE_API_KEY",
"secretkey": "$EXOSCALE_SECRET_KEY",
"domain": "$EXOSCALE_DOMAIN",
"knownFailures": "20,21,22"
},
"GANDI": {
"COMMENT": "5: gandi does not accept TTLs less than 300",
"apikey": "$GANDI_KEY",

View file

@ -8,6 +8,7 @@ import (
_ "github.com/StackExchange/dnscontrol/providers/cloudflare"
_ "github.com/StackExchange/dnscontrol/providers/digitalocean"
_ "github.com/StackExchange/dnscontrol/providers/dnsimple"
_ "github.com/StackExchange/dnscontrol/providers/exoscale"
_ "github.com/StackExchange/dnscontrol/providers/gandi"
_ "github.com/StackExchange/dnscontrol/providers/gcloud"
_ "github.com/StackExchange/dnscontrol/providers/hexonet"

View file

@ -0,0 +1,245 @@
package exoscale
import (
"encoding/json"
"fmt"
"strings"
"github.com/exoscale/egoscale"
"github.com/pkg/errors"
"github.com/StackExchange/dnscontrol/models"
"github.com/StackExchange/dnscontrol/providers"
"github.com/StackExchange/dnscontrol/providers/diff"
)
type exoscaleProvider struct {
client *egoscale.Client
}
// NewExoscale creates a new Exoscale DNS provider.
func NewExoscale(m map[string]string, metadata json.RawMessage) (providers.DNSServiceProvider, error) {
endpoint, apiKey, secretKey := m["dns-endpoint"], m["apikey"], m["secretkey"]
return &exoscaleProvider{client: egoscale.NewClient(endpoint, apiKey, secretKey)}, nil
}
var features = providers.DocumentationNotes{
providers.CanUseAlias: providers.Can(),
providers.CanUseCAA: providers.Can(),
providers.CanUsePTR: providers.Can(),
providers.CanUseSRV: providers.Can(),
providers.CanUseTLSA: providers.Cannot(),
providers.DocCreateDomains: providers.Cannot(),
providers.DocDualHost: providers.Cannot("Exoscale does not allow sufficient control over the apex NS records"),
providers.DocOfficiallySupported: providers.Cannot(),
}
func init() {
providers.RegisterDomainServiceProviderType("EXOSCALE", NewExoscale, features)
}
// EnsureDomainExists returns an error if domain doesn't exist.
func (c *exoscaleProvider) EnsureDomainExists(domain string) error {
_, err := c.client.GetDomain(domain)
if err != nil {
_, err := c.client.CreateDomain(domain)
if err != nil {
return err
}
}
return err
}
// GetNameservers returns the nameservers for domain.
func (c *exoscaleProvider) GetNameservers(domain string) ([]*models.Nameserver, error) {
return nil, nil
}
// GetDomainCorrections returns a list of corretions for the domain.
func (c *exoscaleProvider) GetDomainCorrections(dc *models.DomainConfig) ([]*models.Correction, error) {
dc.Punycode()
records, err := c.client.GetRecords(dc.Name)
if err != nil {
return nil, err
}
existingRecords := make([]*models.RecordConfig, 0, len(records))
for _, r := range records {
if r.RecordType == "SOA" || r.RecordType == "NS" {
continue
}
if r.Name == "" {
r.Name = "@"
}
if r.RecordType == "CNAME" || r.RecordType == "MX" || r.RecordType == "ALIAS" || r.RecordType == "SRV" {
r.Content += "."
}
// exoscale adds these odd txt records that mirror the alias records.
// they seem to manage them on deletes and things, so we'll just pretend they don't exist
if r.RecordType == "TXT" && strings.HasPrefix(r.Content, "ALIAS for ") {
continue
}
rec := &models.RecordConfig{
TTL: uint32(r.TTL),
Original: r,
}
rec.SetLabel(r.Name, dc.Name)
switch rtype := r.RecordType; rtype {
case "ALIAS", "URL":
rec.Type = r.RecordType
rec.SetTarget(r.Content)
case "MX":
if err := rec.SetTargetMX(uint16(r.Prio), r.Content); err != nil {
panic(errors.Wrap(err, "unparsable record received from dnsimple"))
}
default:
if err := rec.PopulateFromString(r.RecordType, r.Content, dc.Name); err != nil {
panic(errors.Wrap(err, "unparsable record received from dnsimple"))
}
}
existingRecords = append(existingRecords, rec)
}
removeOtherNS(dc)
// Normalize
models.PostProcessRecords(existingRecords)
differ := diff.New(dc)
_, create, delete, modify := differ.IncrementalDiff(existingRecords)
var corrections = []*models.Correction{}
for _, del := range delete {
rec := del.Existing.Original.(egoscale.DNSRecord)
corrections = append(corrections, &models.Correction{
Msg: del.String(),
F: c.deleteRecordFunc(rec.ID, dc.Name),
})
}
for _, cre := range create {
rec := cre.Desired
corrections = append(corrections, &models.Correction{
Msg: cre.String(),
F: c.createRecordFunc(rec, dc.Name),
})
}
for _, mod := range modify {
old := mod.Existing.Original.(egoscale.DNSRecord)
new := mod.Desired
corrections = append(corrections, &models.Correction{
Msg: mod.String(),
F: c.updateRecordFunc(&old, new, dc.Name),
})
}
return corrections, nil
}
// Returns a function that can be invoked to create a record in a zone.
func (c *exoscaleProvider) createRecordFunc(rc *models.RecordConfig, domainName string) func() error {
return func() error {
client := c.client
target := rc.GetTargetCombined()
name := rc.GetLabel()
if rc.Type == "MX" {
target = rc.Target
}
if rc.Type == "NS" && (name == "@" || name == "") {
name = "*"
}
record := egoscale.DNSRecord{
Name: name,
RecordType: rc.Type,
Content: target,
TTL: int(rc.TTL),
Prio: int(rc.MxPreference),
}
_, err := client.CreateRecord(domainName, record)
if err != nil {
return err
}
return nil
}
}
// Returns a function that can be invoked to delete a record in a zone.
func (c *exoscaleProvider) deleteRecordFunc(recordID int64, domainName string) func() error {
return func() error {
client := c.client
if err := client.DeleteRecord(domainName, recordID); err != nil {
return err
}
return nil
}
}
// Returns a function that can be invoked to update a record in a zone.
func (c *exoscaleProvider) updateRecordFunc(old *egoscale.DNSRecord, rc *models.RecordConfig, domainName string) func() error {
return func() error {
client := c.client
target := rc.GetTargetCombined()
name := rc.GetLabel()
if rc.Type == "MX" {
target = rc.Target
}
if rc.Type == "NS" && (name == "@" || name == "") {
name = "*"
}
record := egoscale.UpdateDNSRecord{
Name: name,
RecordType: rc.Type,
Content: target,
TTL: int(rc.TTL),
Prio: int(rc.MxPreference),
ID: old.ID,
}
_, err := client.UpdateRecord(domainName, record)
if err != nil {
return err
}
return nil
}
}
func defaultNSSUffix(defNS string) bool {
return (strings.HasSuffix(defNS, ".exoscale.io.") ||
strings.HasSuffix(defNS, ".exoscale.com.") ||
strings.HasSuffix(defNS, ".exoscale.ch.") ||
strings.HasSuffix(defNS, ".exoscale.net."))
}
// remove all non-exoscale NS records from our desired state.
// if any are found, print a warning
func removeOtherNS(dc *models.DomainConfig) {
newList := make([]*models.RecordConfig, 0, len(dc.Records))
for _, rec := range dc.Records {
if rec.Type == "NS" {
// apex NS inside exoscale are expected.
if rec.GetLabelFQDN() == dc.Name && defaultNSSUffix(rec.GetTargetField()) {
continue
}
fmt.Printf("Warning: exoscale.com(.io, .ch, .net) does not allow NS records to be modified. %s will not be added.\n", rec.GetTargetField())
continue
}
newList = append(newList, rec)
}
dc.Records = newList
}

8
vendor/github.com/exoscale/egoscale/AUTHORS generated vendored Normal file
View file

@ -0,0 +1,8 @@
Pierre-Yves Ritschard
Vincent Bernat
Chris Baumbauer
Marc-Aurèle Brothier
Sebastien Goasguen
Yoan Blanc
Stefano Marengo
Pierre-Emmanuel Jacquier

285
vendor/github.com/exoscale/egoscale/CHANGELOG.md generated vendored Normal file
View file

@ -0,0 +1,285 @@
Changelog
=========
0.10.5 (unreleased)
------
- feat: `Client.Logger` to plug in any `*log.Logger`
- feat: `Client.TraceOn`/`ClientTraceOff` to toggle the HTTP tracing
0.10.4
------
- feat: `CIDR` to replace string string
- fix: prevent panic on nil
0.10.3
------
- feat: `Account` is Listable
- feat: `MACAddress` to replace string type
- fix: Go 1.7 support
0.10.2
------
- fix: ActivateIP6 response
0.10.1
------
- feat: expose `SyncRequest` and `SyncRequestWithContext`
- feat: addition of reverse DNS calls
- feat: addition of `SecurityGroup.UserSecurityGroup`
0.10.0
------
- global: cloudstack documentation links are moved into cs
- global: removal of all the `...Response` types
- feat: `Network` is `Listable`
- feat: addition of `deleteUser`
- feat: addition of `listHosts`
- feat: addition of `updateHost`
- feat: exo cmd (kudos to @pierre-emmanuelJ)
- change: refactor `Gettable` to use `ListRequest`
0.9.31
------
- fix: `IPAddress`.`ListRequest` with boolean fields
- fix: `Network`.`ListRequest` with boolean fields
- fix: `ServiceOffering`.`ListRequest` with boolean fields
0.9.30
------
- fix: `VirtualMachine` `PCIDevice` representation was incomplete
0.9.29
------
- change: `DNSErrorResponse` is a proper `error`
0.9.28
------
- feat: addition of `GetDomains`
- fix: `UpdateDomain` may contain more empty fields than `CreateDomain`
0.9.27
------
- fix: expects body to be `application/json`
0.9.26
------
- change: async timeout strategy wait two seconds and not fib(n) seconds
0.9.25
------
- fix: `GetVirtualUserData` response with `Decode` method handling base64 and gzip
0.9.24
------
- feat: `Template` is `Gettable`
- feat: `ServiceOffering` is `Gettable`
- feat: addition of `GetAPILimit`
- feat: addition of `CreateTemplate`, `PrepareTemplate`, `CopyTemplate`, `UpdateTemplate`, `RegisterTemplate`
- feat: addition of `MigrateVirtualMachine`
- feat: cmd cli
- change: remove useless fields related to Project and VPC
0.9.23
------
- feat: `booleanResponse` supports true booleans: https://github.com/apache/cloudstack/pull/2428
0.9.22
------
- feat: `ListUsers`, `CreateUser`, `UpdateUser`
- feat: `ListResourceDetails`
- feat: `SecurityGroup` helper `RuleByID`
- feat: `Sign` signs the payload
- feat: `UpdateNetworkOffering`
- feat: `GetVirtualMachineUserData`
- feat: `EnableAccount` and `DisableAccount` (admin stuff)
- feat: `AsyncRequest` and `AsyncRequestWithContext` to examine the polling
- fix: `AuthorizeSecurityGroupIngress` support for ICMPv6
- change: move `APIName()` into the `Client`, nice godoc
- change: `Payload` doesn't sign the request anymore
- change: `Client` exposes more of its underlying data
- change: requests are sent as GET unless it body size is too big
0.9.21
------
- feat: `Network` is `Listable`
- feat: `Zone` is `Gettable`
- feat: `Client.Payload` to help preview the HTTP parameters
- feat: generate command utility
- fix: `CreateSnapshot` was missing the `Name` attribute
- fix: `ListSnapshots` was missing the `IDs` attribute
- fix: `ListZones` was missing the `NetworkType` attribute
- fix: `ListAsyncJobs` was missing the `ListAll` attribute
- change: ICMP Type/Code are uint8 and TCP/UDP port are uint16
0.9.20
------
- feat: `Template` is `Listable`
- feat: `IPAddress` is `Listable`
- change: `List` and `Paginate` return pointers
- fix: `Template` was missing `tags`
0.9.19
------
- feat: `SSHKeyPair` is `Listable`
0.9.18
------
- feat: `VirtualMachine` is `Listable`
- feat: new `Client.Paginate` and `Client.PaginateWithContext`
- change: the inner logic of `Listable`
- remove: not working `Client.AsyncList`
0.9.17
------
- fix: `AuthorizeSecurityGroup(In|E)gress` startport may be zero
0.9.16
------
- feat: new `Listable` interface
- feat: `Nic` is `Listable`
- feat: `Volume` is `Listable`
- feat: `Zone` is `Listable`
- feat: `AffinityGroup` is `Listable`
- remove: deprecated methods `ListNics`, `AddIPToNic`, and `RemoveIPFromNic`
- remove: deprecated method `GetRootVolumeForVirtualMachine`
0.9.15
------
- feat: `IPAddress` is `Gettable` and `Deletable`
- fix: serialization of *bool
0.9.14
------
- fix: `GetVMPassword` response
- remove: deprecated `GetTopology`, `GetImages`, and al
0.9.13
------
- feat: IP4 and IP6 flags to DeployVirtualMachine
- feat: add ActivateIP6
- fix: error message was gobbled on 40x
0.9.12
------
- feat: add `BooleanRequestWithContext`
- feat: add `client.Get`, `client.GetWithContext` to fetch a resource
- feat: add `cleint.Delete`, `client.DeleteWithContext` to delete a resource
- feat: `SSHKeyPair` is `Gettable` and `Deletable`
- feat: `VirtualMachine` is `Gettable` and `Deletable`
- feat: `AffinityGroup` is `Gettable` and `Deletable`
- feat: `SecurityGroup` is `Gettable` and `Deletable`
- remove: deprecated methods `CreateAffinityGroup`, `DeleteAffinityGroup`
- remove: deprecated methods `CreateKeypair`, `DeleteKeypair`, `RegisterKeypair`
- remove: deprecated method `GetSecurityGroupID`
0.9.11
------
- feat: CloudStack API name is now public `APIName()`
- feat: enforce the mutual exclusivity of some fields
- feat: add `context.Context` to `RequestWithContext`
- change: `AsyncRequest` and `BooleanAsyncRequest` are gone, use `Request` and `BooleanRequest` instead.
- change: `AsyncInfo` is no more
0.9.10
------
- fix: typo made ListAll required in ListPublicIPAddresses
- fix: all bool are now *bool, respecting CS default value
- feat: (*VM).DefaultNic() to obtain the main Nic
0.9.9
-----
- fix: affinity groups virtualmachineIds attribute
- fix: uuidList is not a list of strings
0.9.8
-----
- feat: add RootDiskSize to RestoreVirtualMachine
- fix: monotonic polling using Context
0.9.7
-----
- feat: add Taggable interface to expose ResourceType
- feat: add (Create|Update|Delete|List)InstanceGroup(s)
- feat: add RegisterUserKeys
- feat: add ListResourceLimits
- feat: add ListAccounts
0.9.6
-----
- fix: update UpdateVirtualMachine userdata
- fix: Network's name/displaytext might be empty
0.9.5
-----
- fix: serialization of slice
0.9.4
-----
- fix: constants
0.9.3
-----
- change: userdata expects a string
- change: no pointer in sub-struct's
0.9.2
-----
- bug: createNetwork is a sync call
- bug: typo in listVirtualMachines' domainid
- bug: serialization of map[string], e.g. UpdateVirtualMachine
- change: IPAddress's use net.IP type
- feat: helpers VM.NicsByType, VM.NicByNetworkID, VM.NicByID
- feat: addition of CloudStack ApiErrorCode constants
0.9.1
-----
- bug: sync calls returns succes as a string rather than a bool
- change: unexport BooleanResponse types
- feat: original CloudStack error response can be obtained
0.9.0
-----
Big refactoring, addition of the documentation, compliance to golint.
0.1.0
-----
Initial library

48
vendor/github.com/exoscale/egoscale/Dockerfile generated vendored Normal file
View file

@ -0,0 +1,48 @@
#
# First, export the ops.asc key locally.
#
# gpg --export-secret-key E458F9F85608DF5A22ECCD158B58C61D4FFE0C86 > ops.asc
#
# Build the container
#
# docker build -t egoscale .
#
# Prepare a snapshot release
#
# docker run -v $PWD:/go/src/github.com/exoscale/egoscale egoscale goreleaser --snapshot
#
# Publish egoscale exposing a valid GITHUB_TOKEN
#
# git tag -a v0.10
# git push --tag
# docker run -v $PWD:/go/src/github.com/exoscale/egoscale -e GITHUB_TOKEN=... egoscale goreleaser
#
#
# ⚠ do not push this container anywhere ⚠
#
FROM golang:1.10-stretch
ARG DEBIAN_FRONTEND=noninteractive
RUN go get -u github.com/golang/dep/cmd/dep \
&& go get -u -d github.com/goreleaser/goreleaser/... \
&& go get -u -d github.com/goreleaser/nfpm/... \
&& apt-get update -q \
&& apt-get upgrade -qy \
&& apt-get install -qy \
rpm \
&& cd $GOPATH/src/github.com/goreleaser/nfpm \
&& dep ensure -v -vendor-only \
&& go install \
&& cd ../goreleaser \
&& dep ensure -v -vendor-only \
&& go install \
&& cd /
ADD ops.asc ops.asc
RUN gpg --allow-secret-key-import --import ops.asc
VOLUME /go/src/github.com/exoscale/egoscale
WORKDIR /go/src/github.com/exoscale/egoscale
CMD ['goreleaser', '--snapshot']

90
vendor/github.com/exoscale/egoscale/Jenkinsfile generated vendored Normal file
View file

@ -0,0 +1,90 @@
@Library('jenkins-pipeline') _
node {
cleanWs()
repo = 'exoscale/egoscale'
try {
dir('src') {
stage('SCM') {
checkout scm
}
stage('gofmt') {
gofmt(repo, "cs", "exo")
}
updateGithubCommitStatus('PENDING', "${env.WORKSPACE}/src")
stage('Build') {
parallel (
"golint": {
golint(repo, "cmd/cs/...", "cmd/exo/...", "generate")
},
"go test": {
test(repo)
},
"go install": {
build(repo, "cs", "exo")
},
)
}
}
} catch (err) {
currentBuild.result = 'FAILURE'
throw err
} finally {
if (!currentBuild.result) {
currentBuild.result = 'SUCCESS'
}
updateGithubCommitStatus(currentBuild.result, "${env.WORKSPACE}/src")
cleanWs cleanWhenFailure: false
}
}
def gofmt(repo, ...bins) {
docker.withRegistry('https://registry.internal.exoscale.ch') {
def image = docker.image('registry.internal.exoscale.ch/exoscale/golang:1.10')
image.pull()
image.inside("-u root --net=host -v ${env.WORKSPACE}/src:/go/src/github.com/${repo}") {
sh 'test `gofmt -s -d -e . | tee -a /dev/fd/2 | wc -l` -eq 0'
// let's not gofmt the dependencies
for (bin in bins) {
sh "cd /go/src/github.com/${repo}/cmd/${bin} && dep ensure -v -vendor-only"
}
}
}
}
def golint(repo, ...extras) {
docker.withRegistry('https://registry.internal.exoscale.ch') {
def image = docker.image('registry.internal.exoscale.ch/exoscale/golang:1.10')
image.inside("-u root --net=host -v ${env.WORKSPACE}/src:/go/src/github.com/${repo}") {
sh "golint -set_exit_status -min_confidence 0.6 \$(go list github.com/${repo}/... | grep -v /vendor/)"
sh "go vet `go list github.com/${repo}/... | grep -v /vendor/`"
sh "cd /go/src/github.com/${repo} && gometalinter ."
for (extra in extras) {
sh "cd /go/src/github.com/${repo} && gometalinter ./${extra}"
}
}
}
}
def test(repo) {
docker.withRegistry('https://registry.internal.exoscale.ch') {
def image = docker.image('registry.internal.exoscale.ch/exoscale/golang:1.10')
image.inside("-u root --net=host -v ${env.WORKSPACE}/src:/go/src/github.com/${repo}") {
sh "cd /go/src/github.com/${repo} && go test"
}
}
}
def build(repo, ...bins) {
docker.withRegistry('https://registry.internal.exoscale.ch') {
def image = docker.image('registry.internal.exoscale.ch/exoscale/golang:1.10')
image.inside("-u root --net=host -v ${env.WORKSPACE}/src:/go/src/github.com/exoscale/egoscale") {
for (bin in bins) {
sh "go install github.com/${repo}/cmd/${bin}"
sh "test -e /go/bin/${bin}"
}
}
}
}

201
vendor/github.com/exoscale/egoscale/LICENSE generated vendored Normal file
View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2014 exoscale(tm)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

17
vendor/github.com/exoscale/egoscale/README.md generated vendored Normal file
View file

@ -0,0 +1,17 @@
---
title: Egoscale
description: the Go library for Exoscale
---
<a href="https://gopherize.me/gopher/9c1bc7cfe1d84cf43e477dbfc4aa86332065f1fd"><img src="gopher.png" align="right" alt=""></a>
[![Build Status](https://travis-ci.org/exoscale/egoscale.svg?branch=master)](https://travis-ci.org/exoscale/egoscale) [![Maintainability](https://api.codeclimate.com/v1/badges/fcab3b624b7d3ca96a9d/maintainability)](https://codeclimate.com/github/exoscale/egoscale/maintainability) [![Test Coverage](https://api.codeclimate.com/v1/badges/fcab3b624b7d3ca96a9d/test_coverage)](https://codeclimate.com/github/exoscale/egoscale/test_coverage) [![GoDoc](https://godoc.org/github.com/exoscale/egoscale?status.svg)](https://godoc.org/github.com/exoscale/egoscale) [![Go Report Card](https://goreportcard.com/badge/github.com/exoscale/egoscale)](https://goreportcard.com/report/github.com/exoscale/egoscale)
A wrapper for the [Exoscale public cloud](https://www.exoscale.com) API.
## License
Licensed under the Apache License, Version 2.0 (the "License"); you
may not use this file except in compliance with the License. You may
obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0

161
vendor/github.com/exoscale/egoscale/accounts.go generated vendored Normal file
View file

@ -0,0 +1,161 @@
package egoscale
import "fmt"
// AccountType represents the type of an Account
//
// http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/4.8/accounts.html#accounts-users-and-domains
type AccountType int16
//go:generate stringer -type AccountType
const (
// UserAccount represents a User
UserAccount AccountType = iota
// AdminAccount represents an Admin
AdminAccount
// DomainAdminAccount represents a Domain Admin
DomainAdminAccount
)
// Account provides the detailed account information
type Account struct {
AccountDetails map[string]string `json:"accountdetails,omitempty" doc:"details for the account"`
AccountType AccountType `json:"accounttype,omitempty" doc:"account type (admin, domain-admin, user)"`
CPUAvailable string `json:"cpuavailable,omitempty" doc:"the total number of cpu cores available to be created for this account"`
CPULimit string `json:"cpulimit,omitempty" doc:"the total number of cpu cores the account can own"`
CPUTotal int64 `json:"cputotal,omitempty" doc:"the total number of cpu cores owned by account"`
DefaultZoneID string `json:"defaultzoneid,omitempty" doc:"the default zone of the account"`
Domain string `json:"domain,omitempty" doc:"name of the Domain the account belongs too"`
DomainID string `json:"domainid,omitempty" doc:"id of the Domain the account belongs too"`
EipLimit string `json:"eiplimit,omitempty" doc:"the total number of public elastic ip addresses this account can acquire"`
Groups []string `json:"groups,omitempty" doc:"the list of acl groups that account belongs to"`
ID string `json:"id,omitempty" doc:"the id of the account"`
IPAvailable string `json:"ipavailable,omitempty" doc:"the total number of public ip addresses available for this account to acquire"`
IPLimit string `json:"iplimit,omitempty" doc:"the total number of public ip addresses this account can acquire"`
IPTotal int64 `json:"iptotal,omitempty" doc:"the total number of public ip addresses allocated for this account"`
IsCleanupRequired bool `json:"iscleanuprequired,omitempty" doc:"true if the account requires cleanup"`
IsDefault bool `json:"isdefault,omitempty" doc:"true if account is default, false otherwise"`
MemoryAvailable string `json:"memoryavailable,omitempty" doc:"the total memory (in MB) available to be created for this account"`
MemoryLimit string `json:"memorylimit,omitempty" doc:"the total memory (in MB) the account can own"`
MemoryTotal int64 `json:"memorytotal,omitempty" doc:"the total memory (in MB) owned by account"`
Name string `json:"name,omitempty" doc:"the name of the account"`
NetworkAvailable string `json:"networkavailable,omitempty" doc:"the total number of networks available to be created for this account"`
NetworkDomain string `json:"networkdomain,omitempty" doc:"the network domain"`
NetworkLimit string `json:"networklimit,omitempty" doc:"the total number of networks the account can own"`
NetworkTotal int64 `json:"networktotal,omitempty" doc:"the total number of networks owned by account"`
PrimaryStorageAvailable string `json:"primarystorageavailable,omitempty" doc:"the total primary storage space (in GiB) available to be used for this account"`
PrimaryStorageLimit string `json:"primarystoragelimit,omitempty" doc:"the total primary storage space (in GiB) the account can own"`
PrimaryStorageTotal int64 `json:"primarystoragetotal,omitempty" doc:"the total primary storage space (in GiB) owned by account"`
ProjectAvailable string `json:"projectavailable,omitempty" doc:"the total number of projects available for administration by this account"`
ProjectLimit string `json:"projectlimit,omitempty" doc:"the total number of projects the account can own"`
ProjectTotal int64 `json:"projecttotal,omitempty" doc:"the total number of projects being administrated by this account"`
SecondaryStorageAvailable string `json:"secondarystorageavailable,omitempty" doc:"the total secondary storage space (in GiB) available to be used for this account"`
SecondaryStorageLimit string `json:"secondarystoragelimit,omitempty" doc:"the total secondary storage space (in GiB) the account can own"`
SecondaryStorageTotal int64 `json:"secondarystoragetotal,omitempty" doc:"the total secondary storage space (in GiB) owned by account"`
SMTP bool `json:"smtp,omitempty" doc:"if SMTP outbound is allowed"`
SnapshotAvailable string `json:"snapshotavailable,omitempty" doc:"the total number of snapshots available for this account"`
SnapshotLimit string `json:"snapshotlimit,omitempty" doc:"the total number of snapshots which can be stored by this account"`
SnapshotTotal int64 `json:"snapshottotal,omitempty" doc:"the total number of snapshots stored by this account"`
State string `json:"state,omitempty" doc:"the state of the account"`
TemplateAvailable string `json:"templateavailable,omitempty" doc:"the total number of templates available to be created by this account"`
TemplateLimit string `json:"templatelimit,omitempty" doc:"the total number of templates which can be created by this account"`
TemplateTotal int64 `json:"templatetotal,omitempty" doc:"the total number of templates which have been created by this account"`
User []User `json:"user,omitempty" doc:"the list of users associated with account"`
VMAvailable string `json:"vmavailable,omitempty" doc:"the total number of virtual machines available for this account to acquire"`
VMLimit string `json:"vmlimit,omitempty" doc:"the total number of virtual machines that can be deployed by this account"`
VMRunning int `json:"vmrunning,omitempty" doc:"the total number of virtual machines running for this account"`
VMStopped int `json:"vmstopped,omitempty" doc:"the total number of virtual machines stopped for this account"`
VMTotal int64 `json:"vmtotal,omitempty" doc:"the total number of virtual machines deployed by this account"`
VolumeAvailable string `json:"volumeavailable,omitempty" doc:"the total volume available for this account"`
VolumeLimit string `json:"volumelimit,omitempty" doc:"the total volume which can be used by this account"`
VolumeTotal int64 `json:"volumetotal,omitempty" doc:"the total volume being used by this account"`
}
// ListRequest builds the ListAccountsGroups request
func (a Account) ListRequest() (ListCommand, error) {
return &ListAccounts{
ID: a.ID,
DomainID: a.DomainID,
AccountType: a.AccountType,
State: a.State,
}, nil
}
// ListAccounts represents a query to display the accounts
type ListAccounts struct {
AccountType AccountType `json:"accounttype,omitempty" doc:"list accounts by account type. Valid account types are 1 (admin), 2 (domain-admin), and 0 (user)."`
DomainID string `json:"domainid,omitempty" doc:"list only resources belonging to the domain specified"`
ID string `json:"id,omitempty" doc:"list account by account ID"`
IsCleanUpRequired *bool `json:"iscleanuprequired,omitempty" doc:"list accounts by cleanuprequred attribute (values are true or false)"`
IsRecursive *bool `json:"isrecursive,omitempty" doc:"defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves."`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
ListAll *bool `json:"listall,omitempty" doc:"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"`
Name string `json:"name,omitempty" doc:"list account by account name"`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
State string `json:"state,omitempty" doc:"list accounts by state. Valid states are enabled, disabled, and locked."`
_ bool `name:"listAccounts" description:"Lists accounts and provides detailed account information for listed accounts"`
}
func (ListAccounts) response() interface{} {
return new(ListAccountsResponse)
}
// SetPage sets the current page
func (ls *ListAccounts) SetPage(page int) {
ls.Page = page
}
// SetPageSize sets the page size
func (ls *ListAccounts) SetPageSize(pageSize int) {
ls.PageSize = pageSize
}
func (ListAccounts) each(resp interface{}, callback IterateItemFunc) {
vms, ok := resp.(*ListAccountsResponse)
if !ok {
callback(nil, fmt.Errorf("wrong type. ListAccountsResponse expected, got %T", resp))
return
}
for i := range vms.Account {
if !callback(&vms.Account[i], nil) {
break
}
}
}
// ListAccountsResponse represents a list of accounts
type ListAccountsResponse struct {
Count int `json:"count"`
Account []Account `json:"account"`
}
// EnableAccount represents the activation of an account
type EnableAccount struct {
Account string `json:"account,omitempty" doc:"Enables specified account."`
DomainID string `json:"domainid,omitempty" doc:"Enables specified account in this domain."`
ID string `json:"id,omitempty" doc:"Account id"`
_ bool `name:"enableAccount" description:"Enables an account"`
}
func (EnableAccount) response() interface{} {
return new(Account)
}
// DisableAccount (Async) represents the deactivation of an account
type DisableAccount struct {
Lock *bool `json:"lock" doc:"If true, only lock the account; else disable the account"`
Account string `json:"account,omitempty" doc:"Disables specified account."`
DomainID string `json:"domainid,omitempty" doc:"Disables specified account in this domain."`
ID string `json:"id,omitempty" doc:"Account id"`
_ bool `name:"disableAccount" description:"Disables an account"`
}
func (DisableAccount) response() interface{} {
return new(AsyncJobResult)
}
func (DisableAccount) asyncResponse() interface{} {
return new(Account)
}

View file

@ -0,0 +1,16 @@
// Code generated by "stringer -type AccountType"; DO NOT EDIT.
package egoscale
import "strconv"
const _AccountType_name = "UserAccountAdminAccountDomainAdminAccount"
var _AccountType_index = [...]uint8{0, 11, 23, 41}
func (i AccountType) String() string {
if i < 0 || i >= AccountType(len(_AccountType_index)-1) {
return "AccountType(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _AccountType_name[_AccountType_index[i]:_AccountType_index[i+1]]
}

195
vendor/github.com/exoscale/egoscale/addresses.go generated vendored Normal file
View file

@ -0,0 +1,195 @@
package egoscale
import (
"context"
"fmt"
"net"
)
// IPAddress represents an IP Address
type IPAddress struct {
Account string `json:"account,omitempty" doc:"the account the public IP address is associated with"`
Allocated string `json:"allocated,omitempty" doc:"date the public IP address was acquired"`
Associated string `json:"associated,omitempty" doc:"date the public IP address was associated"`
AssociatedNetworkID string `json:"associatednetworkid,omitempty" doc:"the ID of the Network associated with the IP address"`
AssociatedNetworkName string `json:"associatednetworkname,omitempty" doc:"the name of the Network associated with the IP address"`
Domain string `json:"domain,omitempty" doc:"the domain the public IP address is associated with"`
DomainID string `json:"domainid,omitempty" doc:"the domain ID the public IP address is associated with"`
ForDisplay bool `json:"fordisplay,omitempty" doc:"is public ip for display to the regular user"`
ForVirtualNetwork bool `json:"forvirtualnetwork,omitempty" doc:"the virtual network for the IP address"`
ID string `json:"id,omitempty" doc:"public IP address id"`
IPAddress net.IP `json:"ipaddress,omitempty" doc:"public IP address"`
IsElastic bool `json:"iselastic,omitempty" doc:"is an elastic ip"`
IsPortable bool `json:"isportable,omitempty" doc:"is public IP portable across the zones"`
IsSourceNat bool `json:"issourcenat,omitempty" doc:"true if the IP address is a source nat address, false otherwise"`
IsStaticNat *bool `json:"isstaticnat,omitempty" doc:"true if this ip is for static nat, false otherwise"`
IsSystem bool `json:"issystem,omitempty" doc:"true if this ip is system ip (was allocated as a part of deployVm or createLbRule)"`
NetworkID string `json:"networkid,omitempty" doc:"the ID of the Network where ip belongs to"`
PhysicalNetworkID string `json:"physicalnetworkid,omitempty" doc:"the physical network this belongs to"`
Purpose string `json:"purpose,omitempty" doc:"purpose of the IP address. In Acton this value is not null for Ips with isSystem=true, and can have either StaticNat or LB value"`
ReverseDNS []ReverseDNS `json:"reversedns,omitempty" doc:"the list of PTR record(s) associated with the ip address"`
State string `json:"state,omitempty" doc:"State of the ip address. Can be: Allocatin, Allocated and Releasing"`
Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with ip address"`
VirtualMachineDisplayName string `json:"virtualmachinedisplayname,omitempty" doc:"virtual machine display name the ip address is assigned to (not null only for static nat Ip)"`
VirtualMachineID string `json:"virtualmachineid,omitempty" doc:"virtual machine id the ip address is assigned to (not null only for static nat Ip)"`
VirtualMachineName string `json:"virtualmachinename,omitempty" doc:"virtual machine name the ip address is assigned to (not null only for static nat Ip)"`
VlanID string `json:"vlanid,omitempty" doc:"the ID of the VLAN associated with the IP address. This parameter is visible to ROOT admins only"`
VlanName string `json:"vlanname,omitempty" doc:"the VLAN associated with the IP address"`
VMIPAddress net.IP `json:"vmipaddress,omitempty" doc:"virutal machine (dnat) ip address (not null only for static nat Ip)"`
ZoneID string `json:"zoneid,omitempty" doc:"the ID of the zone the public IP address belongs to"`
ZoneName string `json:"zonename,omitempty" doc:"the name of the zone the public IP address belongs to"`
}
// ResourceType returns the type of the resource
func (IPAddress) ResourceType() string {
return "PublicIpAddress"
}
// ListRequest builds the ListAdresses request
func (ipaddress IPAddress) ListRequest() (ListCommand, error) {
req := &ListPublicIPAddresses{
Account: ipaddress.Account,
AssociatedNetworkID: ipaddress.AssociatedNetworkID,
DomainID: ipaddress.DomainID,
ID: ipaddress.ID,
IPAddress: ipaddress.IPAddress,
PhysicalNetworkID: ipaddress.PhysicalNetworkID,
VlanID: ipaddress.VlanID,
ZoneID: ipaddress.ZoneID,
}
if ipaddress.IsElastic {
req.IsElastic = &ipaddress.IsElastic
}
if ipaddress.IsSourceNat {
req.IsSourceNat = &ipaddress.IsSourceNat
}
if ipaddress.ForDisplay {
req.ForDisplay = &ipaddress.ForDisplay
}
if ipaddress.ForVirtualNetwork {
req.ForVirtualNetwork = &ipaddress.ForVirtualNetwork
}
return req, nil
}
// Delete removes the resource
func (ipaddress IPAddress) Delete(ctx context.Context, client *Client) error {
if ipaddress.ID == "" {
return fmt.Errorf("an IPAddress may only be deleted using ID")
}
return client.BooleanRequestWithContext(ctx, &DisassociateIPAddress{
ID: ipaddress.ID,
})
}
// AssociateIPAddress (Async) represents the IP creation
type AssociateIPAddress struct {
Account string `json:"account,omitempty" doc:"the account to associate with this IP address"`
DomainID string `json:"domainid,omitempty" doc:"the ID of the domain to associate with this IP address"`
ForDisplay *bool `json:"fordisplay,omitempty" doc:"an optional field, whether to the display the ip to the end user or not"`
IsPortable *bool `json:"isportable,omitempty" doc:"should be set to true if public IP is required to be transferable across zones, if not specified defaults to false"`
NetworkdID string `json:"networkid,omitempty" doc:"The network this ip address should be associated to."`
RegionID int `json:"regionid,omitempty" doc:"region ID from where portable ip is to be associated."`
ZoneID string `json:"zoneid,omitempty" doc:"the ID of the availability zone you want to acquire an public IP address from"`
_ bool `name:"associateIpAddress" description:"Acquires and associates a public IP to an account."`
}
func (AssociateIPAddress) response() interface{} {
return new(AsyncJobResult)
}
func (AssociateIPAddress) asyncResponse() interface{} {
return new(IPAddress)
}
// DisassociateIPAddress (Async) represents the IP deletion
type DisassociateIPAddress struct {
ID string `json:"id" doc:"the id of the public ip address to disassociate"`
_ bool `name:"disassociateIpAddress" description:"Disassociates an ip address from the account."`
}
func (DisassociateIPAddress) response() interface{} {
return new(AsyncJobResult)
}
func (DisassociateIPAddress) asyncResponse() interface{} {
return new(booleanResponse)
}
// UpdateIPAddress (Async) represents the IP modification
type UpdateIPAddress struct {
ID string `json:"id" doc:"the id of the public ip address to update"`
CustomID string `json:"customid,omitempty" doc:"an optional field, in case you want to set a custom id to the resource. Allowed to Root Admins only"`
ForDisplay *bool `json:"fordisplay,omitempty" doc:"an optional field, whether to the display the ip to the end user or not"`
_ bool `name:"updateIpAddress" description:"Updates an ip address"`
}
func (UpdateIPAddress) response() interface{} {
return new(AsyncJobResult)
}
func (UpdateIPAddress) asyncResponse() interface{} {
return new(IPAddress)
}
// ListPublicIPAddresses represents a search for public IP addresses
type ListPublicIPAddresses struct {
Account string `json:"account,omitempty" doc:"list resources by account. Must be used with the domainId parameter."`
AllocatedOnly *bool `json:"allocatedonly,omitempty" doc:"limits search results to allocated public IP addresses"`
AssociatedNetworkID string `json:"associatednetworkid,omitempty" doc:"lists all public IP addresses associated to the network specified"`
DomainID string `json:"domainid,omitempty" doc:"list only resources belonging to the domain specified"`
ForDisplay *bool `json:"fordisplay,omitempty" doc:"list resources by display flag; only ROOT admin is eligible to pass this parameter"`
ForLoadBalancing *bool `json:"forloadbalancing,omitempty" doc:"list only ips used for load balancing"`
ForVirtualNetwork *bool `json:"forvirtualnetwork,omitempty" doc:"the virtual network for the IP address"`
ID string `json:"id,omitempty" doc:"lists ip address by id"`
IPAddress net.IP `json:"ipaddress,omitempty" doc:"lists the specified IP address"`
IsElastic *bool `json:"iselastic,omitempty" doc:"list only elastic ip addresses"`
IsRecursive *bool `json:"isrecursive,omitempty" doc:"defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves."`
IsSourceNat *bool `json:"issourcenat,omitempty" doc:"list only source nat ip addresses"`
IsStaticNat *bool `json:"isstaticnat,omitempty" doc:"list only static nat ip addresses"`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
ListAll *bool `json:"listall,omitempty" doc:"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
PhysicalNetworkID string `json:"physicalnetworkid,omitempty" doc:"lists all public IP addresses by physical network id"`
Tags []ResourceTag `json:"tags,omitempty" doc:"List resources by tags (key/value pairs)"`
VlanID string `json:"vlanid,omitempty" doc:"lists all public IP addresses by VLAN ID"`
ZoneID string `json:"zoneid,omitempty" doc:"lists all public IP addresses by Zone ID"`
_ bool `name:"listPublicIpAddresses" description:"Lists all public ip addresses"`
}
// ListPublicIPAddressesResponse represents a list of public IP addresses
type ListPublicIPAddressesResponse struct {
Count int `json:"count"`
PublicIPAddress []IPAddress `json:"publicipaddress"`
}
func (ListPublicIPAddresses) response() interface{} {
return new(ListPublicIPAddressesResponse)
}
// SetPage sets the current page
func (ls *ListPublicIPAddresses) SetPage(page int) {
ls.Page = page
}
// SetPageSize sets the page size
func (ls *ListPublicIPAddresses) SetPageSize(pageSize int) {
ls.PageSize = pageSize
}
func (ListPublicIPAddresses) each(resp interface{}, callback IterateItemFunc) {
ips, ok := resp.(*ListPublicIPAddressesResponse)
if !ok {
callback(nil, fmt.Errorf("wrong type. ListPublicIPAddressesResponse expected, got %T", resp))
return
}
for i := range ips.PublicIPAddress {
if !callback(&ips.PublicIPAddress[i], nil) {
break
}
}
}

182
vendor/github.com/exoscale/egoscale/affinity_groups.go generated vendored Normal file
View file

@ -0,0 +1,182 @@
package egoscale
import (
"context"
"fmt"
"net/url"
)
// AffinityGroup represents an (anti-)affinity group
//
// Affinity and Anti-Affinity groups provide a way to influence where VMs should run.
// See: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/stable/virtual_machines.html#affinity-groups
type AffinityGroup struct {
Account string `json:"account,omitempty" doc:"the account owning the affinity group"`
Description string `json:"description,omitempty" doc:"the description of the affinity group"`
Domain string `json:"domain,omitempty" doc:"the domain name of the affinity group"`
DomainID string `json:"domainid,omitempty" doc:"the domain ID of the affinity group"`
ID string `json:"id,omitempty" doc:"the ID of the affinity group"`
Name string `json:"name,omitempty" doc:"the name of the affinity group"`
Type string `json:"type,omitempty" doc:"the type of the affinity group"`
VirtualMachineIDs []string `json:"virtualmachineIds,omitempty" doc:"virtual machine Ids associated with this affinity group "`
}
// ListRequest builds the ListAffinityGroups request
func (ag AffinityGroup) ListRequest() (ListCommand, error) {
return &ListAffinityGroups{
ID: ag.ID,
Name: ag.Name,
}, nil
}
// Delete removes the given Affinity Group
func (ag AffinityGroup) Delete(ctx context.Context, client *Client) error {
if ag.ID == "" && ag.Name == "" {
return fmt.Errorf("an Affinity Group may only be deleted using ID or Name")
}
req := &DeleteAffinityGroup{
Account: ag.Account,
DomainID: ag.DomainID,
}
if ag.ID != "" {
req.ID = ag.ID
} else {
req.Name = ag.Name
}
return client.BooleanRequestWithContext(ctx, req)
}
// AffinityGroupType represent an affinity group type
type AffinityGroupType struct {
Type string `json:"type,omitempty" doc:"the type of the affinity group"`
}
// CreateAffinityGroup (Async) represents a new (anti-)affinity group
type CreateAffinityGroup struct {
Account string `json:"account,omitempty" doc:"an account for the affinity group. Must be used with domainId."`
Description string `json:"description,omitempty" doc:"optional description of the affinity group"`
DomainID string `json:"domainid,omitempty" doc:"domainId of the account owning the affinity group"`
Name string `json:"name" doc:"name of the affinity group"`
Type string `json:"type" doc:"Type of the affinity group from the available affinity/anti-affinity group types"`
_ bool `name:"createAffinityGroup" description:"Creates an affinity/anti-affinity group"`
}
func (CreateAffinityGroup) response() interface{} {
return new(AsyncJobResult)
}
func (CreateAffinityGroup) asyncResponse() interface{} {
return new(AffinityGroup)
}
// UpdateVMAffinityGroup (Async) represents a modification of a (anti-)affinity group
type UpdateVMAffinityGroup struct {
ID string `json:"id" doc:"The ID of the virtual machine"`
AffinityGroupIDs []string `json:"affinitygroupids,omitempty" doc:"comma separated list of affinity groups id that are going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupnames parameter"`
AffinityGroupNames []string `json:"affinitygroupnames,omitempty" doc:"comma separated list of affinity groups names that are going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupids parameter"`
_ bool `name:"updateVMAffinityGroup" description:"Updates the affinity/anti-affinity group associations of a virtual machine. The VM has to be stopped and restarted for the new properties to take effect."`
}
func (req UpdateVMAffinityGroup) onBeforeSend(params url.Values) error {
// Either AffinityGroupIDs or AffinityGroupNames must be set
if len(req.AffinityGroupIDs) == 0 && len(req.AffinityGroupNames) == 0 {
params.Set("affinitygroupids", "")
}
return nil
}
func (UpdateVMAffinityGroup) response() interface{} {
return new(AsyncJobResult)
}
func (UpdateVMAffinityGroup) asyncResponse() interface{} {
return new(VirtualMachine)
}
// DeleteAffinityGroup (Async) represents an (anti-)affinity group to be deleted
type DeleteAffinityGroup struct {
Account string `json:"account,omitempty" doc:"the account of the affinity group. Must be specified with domain ID"`
DomainID string `json:"domainid,omitempty" doc:"the domain ID of account owning the affinity group"`
ID string `json:"id,omitempty" doc:"The ID of the affinity group. Mutually exclusive with name parameter"`
Name string `json:"name,omitempty" doc:"The name of the affinity group. Mutually exclusive with ID parameter"`
_ bool `name:"deleteAffinityGroup" description:"Deletes affinity group"`
}
func (DeleteAffinityGroup) response() interface{} {
return new(AsyncJobResult)
}
func (DeleteAffinityGroup) asyncResponse() interface{} {
return new(booleanResponse)
}
// ListAffinityGroups represents an (anti-)affinity groups search
type ListAffinityGroups struct {
Account string `json:"account,omitempty" doc:"list resources by account. Must be used with the domainId parameter."`
DomainID string `json:"domainid,omitempty" doc:"list only resources belonging to the domain specified"`
ID string `json:"id,omitempty" doc:"list the affinity group by the ID provided"`
IsRecursive *bool `json:"isrecursive,omitempty" doc:"defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves."`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
ListAll *bool `json:"listall,omitempty" doc:"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"`
Name string `json:"name,omitempty" doc:"lists affinity groups by name"`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
Type string `json:"type,omitempty" doc:"lists affinity groups by type"`
VirtualMachineID string `json:"virtualmachineid,omitempty" doc:"lists affinity groups by virtual machine ID"`
_ bool `name:"listAffinityGroups" description:"Lists affinity groups"`
}
func (ListAffinityGroups) response() interface{} {
return new(ListAffinityGroupsResponse)
}
// SetPage sets the current page
func (ls *ListAffinityGroups) SetPage(page int) {
ls.Page = page
}
// SetPageSize sets the page size
func (ls *ListAffinityGroups) SetPageSize(pageSize int) {
ls.PageSize = pageSize
}
func (ListAffinityGroups) each(resp interface{}, callback IterateItemFunc) {
vms, ok := resp.(*ListAffinityGroupsResponse)
if !ok {
callback(nil, fmt.Errorf("wrong type. ListAffinityGroupsResponse expected, got %T", resp))
return
}
for i := range vms.AffinityGroup {
if !callback(&vms.AffinityGroup[i], nil) {
break
}
}
}
// ListAffinityGroupsResponse represents a list of (anti-)affinity groups
type ListAffinityGroupsResponse struct {
Count int `json:"count"`
AffinityGroup []AffinityGroup `json:"affinitygroup"`
}
// ListAffinityGroupTypes represents an (anti-)affinity groups search
type ListAffinityGroupTypes struct {
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
_ bool `name:"listAffinityGroupTypes" description:"Lists affinity group types available"`
}
func (ListAffinityGroupTypes) response() interface{} {
return new(ListAffinityGroupTypesResponse)
}
// ListAffinityGroupTypesResponse represents a list of (anti-)affinity group types
type ListAffinityGroupTypesResponse struct {
Count int `json:"count"`
AffinityGroupType []AffinityGroupType `json:"affinitygrouptype"`
}

39
vendor/github.com/exoscale/egoscale/apis.go generated vendored Normal file
View file

@ -0,0 +1,39 @@
package egoscale
// API represents an API service
type API struct {
Description string `json:"description,omitempty" doc:"description of the api"`
IsAsync bool `json:"isasync,omitempty" doc:"true if api is asynchronous"`
Name string `json:"name,omitempty" doc:"the name of the api command"`
Related string `json:"related,omitempty" doc:"comma separated related apis"`
Since string `json:"since,omitempty" doc:"version of CloudStack the api was introduced in"`
Type string `json:"type,omitempty" doc:"response field type"`
Params []APIParam `json:"params,omitempty" doc:"the list params the api accepts"`
Response []APIParam `json:"response,omitempty" doc:"api response fields"`
}
// APIParam represents an API parameter field
type APIParam struct {
Description string `json:"description"`
Length int64 `json:"length"`
Name string `json:"name"`
Required bool `json:"required"`
Since string `json:"since"`
Type string `json:"type"`
}
// ListAPIs represents a query to list the api
type ListAPIs struct {
Name string `json:"name,omitempty" doc:"API name"`
_ bool `name:"listApis" description:"lists all available apis on the server, provided by the Api Discovery plugin"`
}
// ListAPIsResponse represents a list of API
type ListAPIsResponse struct {
Count int `json:"count"`
API []API `json:"api"`
}
func (*ListAPIs) response() interface{} {
return new(ListAPIsResponse)
}

95
vendor/github.com/exoscale/egoscale/async_jobs.go generated vendored Normal file
View file

@ -0,0 +1,95 @@
package egoscale
import (
"encoding/json"
"errors"
)
// AsyncJobResult represents an asynchronous job result
type AsyncJobResult struct {
AccountID string `json:"accountid"`
Cmd string `json:"cmd"`
Created string `json:"created"`
JobInstanceID string `json:"jobinstanceid,omitempty"`
JobInstanceType string `json:"jobinstancetype,omitempty"`
JobProcStatus int `json:"jobprocstatus"`
JobResult *json.RawMessage `json:"jobresult"`
JobResultCode int `json:"jobresultcode"`
JobResultType string `json:"jobresulttype"`
JobStatus JobStatusType `json:"jobstatus"`
UserID string `json:"userid"`
JobID string `json:"jobid"`
}
func (a AsyncJobResult) Error() error {
r := new(ErrorResponse)
if e := json.Unmarshal(*a.JobResult, r); e != nil {
return e
}
return r
}
// QueryAsyncJobResult represents a query to fetch the status of async job
type QueryAsyncJobResult struct {
JobID string `json:"jobid" doc:"the ID of the asychronous job"`
_ bool `name:"queryAsyncJobResult" description:"Retrieves the current status of asynchronous job."`
}
func (QueryAsyncJobResult) response() interface{} {
return new(AsyncJobResult)
}
// ListAsyncJobs list the asynchronous jobs
type ListAsyncJobs struct {
Account string `json:"account,omitempty" doc:"list resources by account. Must be used with the domainId parameter."`
DomainID string `json:"domainid,omitempty" doc:"list only resources belonging to the domain specified"`
IsRecursive *bool `json:"isrecursive,omitempty" doc:"defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves."`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
ListAll *bool `json:"listall,omitempty" doc:"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
StartDate string `json:"startdate,omitempty" doc:"the start date of the async job"`
_ bool `name:"listAsyncJobs" description:"Lists all pending asynchronous jobs for the account."`
}
// ListAsyncJobsResponse represents a list of job results
type ListAsyncJobsResponse struct {
Count int `json:"count"`
AsyncJobs []AsyncJobResult `json:"asyncjobs"`
}
func (ListAsyncJobs) response() interface{} {
return new(ListAsyncJobsResponse)
}
// Result unmarshals the result of an AsyncJobResult into the given interface
func (a AsyncJobResult) Result(i interface{}) error {
if a.JobStatus == Failure {
return a.Error()
}
if a.JobStatus == Success {
m := map[string]json.RawMessage{}
err := json.Unmarshal(*(a.JobResult), &m)
if err == nil {
if len(m) >= 1 {
if _, ok := m["success"]; ok {
return json.Unmarshal(*(a.JobResult), i)
}
// more than one keys are list...response
if len(m) > 1 {
return json.Unmarshal(*(a.JobResult), i)
}
// otherwise, pick the first key
for k := range m {
return json.Unmarshal(m[k], i)
}
}
return errors.New("empty response")
}
}
return nil
}

50
vendor/github.com/exoscale/egoscale/cidr.go generated vendored Normal file
View file

@ -0,0 +1,50 @@
package egoscale
import (
"encoding/json"
"fmt"
"net"
)
// CIDR represents a nicely JSON serializable net.IPNet
type CIDR struct {
*net.IPNet
}
// UnmarshalJSON unmarshals the raw JSON into the MAC address
func (cidr *CIDR) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
c, err := ParseCIDR(s)
if err != nil {
return err
}
cidr.IPNet = c.IPNet
return nil
}
// MarshalJSON converts the CIDR to a string representation
func (cidr CIDR) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("%q", cidr.IPNet)), nil
}
// ParseCIDR parses a CIDR from a string
func ParseCIDR(s string) (*CIDR, error) {
_, net, err := net.ParseCIDR(s)
if err != nil {
return nil, err
}
return &CIDR{net}, nil
}
// ForceParseCIDR forces parseCIDR or panics
func ForceParseCIDR(s string) *CIDR {
cidr, err := ParseCIDR(s)
if err != nil {
panic(err)
}
return cidr
}

383
vendor/github.com/exoscale/egoscale/client.go generated vendored Normal file
View file

@ -0,0 +1,383 @@
package egoscale
import (
"context"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"os"
"strings"
"time"
)
// Taggable represents a resource which can have tags attached
//
// This is a helper to fill the resourcetype of a CreateTags call
type Taggable interface {
// CloudStack resource type of the Taggable type
ResourceType() string
}
// Deletable represents an Interface that can be "Delete" by the client
type Deletable interface {
// Delete removes the given resource(s) or throws
Delete(context context.Context, client *Client) error
}
// Listable represents an Interface that can be "List" by the client
type Listable interface {
// ListRequest builds the list command
ListRequest() (ListCommand, error)
}
// Gettable represents an Interface that can be "Get" by the client
type Gettable interface {
Listable
}
// Client represents the CloudStack API client
type Client struct {
// HTTPClient holds the HTTP client
HTTPClient *http.Client
// Endpoints is CloudStack API
Endpoint string
// APIKey is the API identifier
APIKey string
// apisecret is the API secret, hence non exposed
apiSecret string
// PageSize represents the default size for a paginated result
PageSize int
// Timeout represents the default timeout for the async requests
Timeout time.Duration
// RetryStrategy represents the waiting strategy for polling the async requests
RetryStrategy RetryStrategyFunc
// Logger contains any log, plug your own
Logger *log.Logger
}
// RetryStrategyFunc represents a how much time to wait between two calls to CloudStack
type RetryStrategyFunc func(int64) time.Duration
// IterateItemFunc represents the callback to iterate a list of results, if false stops
type IterateItemFunc func(interface{}, error) bool
// WaitAsyncJobResultFunc represents the callback to wait a results of an async request, if false stops
type WaitAsyncJobResultFunc func(*AsyncJobResult, error) bool
// NewClient creates a CloudStack API client with default timeout (60)
//
// Timeout is set to both the HTTP client and the client itself.
func NewClient(endpoint, apiKey, apiSecret string) *Client {
timeout := 60 * time.Second
httpClient := &http.Client{
Transport: http.DefaultTransport,
}
client := &Client{
HTTPClient: httpClient,
Endpoint: endpoint,
APIKey: apiKey,
apiSecret: apiSecret,
PageSize: 50,
Timeout: timeout,
RetryStrategy: MonotonicRetryStrategyFunc(2),
Logger: log.New(ioutil.Discard, "", 0),
}
if prefix, ok := os.LookupEnv("EXOSCALE_TRACE"); ok {
client.Logger = log.New(os.Stderr, prefix, log.LstdFlags)
client.TraceOn()
}
return client
}
// Get populates the given resource or fails
func (client *Client) Get(g Gettable) error {
ctx, cancel := context.WithTimeout(context.Background(), client.Timeout)
defer cancel()
return client.GetWithContext(ctx, g)
}
// GetWithContext populates the given resource or fails
func (client *Client) GetWithContext(ctx context.Context, g Gettable) error {
gs, err := client.ListWithContext(ctx, g)
if err != nil {
return err
}
count := len(gs)
if count != 1 {
req, err := g.ListRequest()
if err != nil {
return err
}
payload, err := client.Payload(req)
if err != nil {
return err
}
// formatting the query string nicely
payload = strings.Replace(payload, "&", ", ", -1)
if count == 0 {
return &ErrorResponse{
ErrorCode: ParamError,
ErrorText: fmt.Sprintf("not found, query: %s", payload),
}
}
return fmt.Errorf("more than one element found: %s", payload)
}
return Copy(g, gs[0])
}
// Delete removes the given resource of fails
func (client *Client) Delete(g Deletable) error {
ctx, cancel := context.WithTimeout(context.Background(), client.Timeout)
defer cancel()
return client.DeleteWithContext(ctx, g)
}
// DeleteWithContext removes the given resource of fails
func (client *Client) DeleteWithContext(ctx context.Context, g Deletable) error {
return g.Delete(ctx, client)
}
// List lists the given resource (and paginate till the end)
func (client *Client) List(g Listable) ([]interface{}, error) {
ctx, cancel := context.WithTimeout(context.Background(), client.Timeout)
defer cancel()
return client.ListWithContext(ctx, g)
}
// ListWithContext lists the given resources (and paginate till the end)
func (client *Client) ListWithContext(ctx context.Context, g Listable) ([]interface{}, error) {
s := make([]interface{}, 0)
if g == nil {
return s, fmt.Errorf("g Listable shouldn't be nil")
}
req, err := g.ListRequest()
if err != nil {
return s, err
}
client.PaginateWithContext(ctx, req, func(item interface{}, e error) bool {
if item != nil {
s = append(s, item)
return true
}
err = e
return false
})
return s, err
}
// AsyncListWithContext lists the given resources (and paginate till the end)
//
//
// // NB: goroutine may leak if not read until the end. Create a proper context!
// ctx, cancel := context.WithCancel(context.Background())
// defer cancel()
//
// outChan, errChan := client.AsyncListWithContext(ctx, new(egoscale.VirtualMachine))
//
// for {
// select {
// case i, ok := <- outChan:
// if ok {
// vm := i.(egoscale.VirtualMachine)
// // ...
// } else {
// outChan = nil
// }
// case err, ok := <- errChan:
// if ok {
// // do something
// }
// // Once an error has been received, you can expect the channels to be closed.
// errChan = nil
// }
// if errChan == nil && outChan == nil {
// break
// }
// }
//
func (client *Client) AsyncListWithContext(ctx context.Context, g Listable) (<-chan interface{}, <-chan error) {
outChan := make(chan interface{}, client.PageSize)
errChan := make(chan error)
go func() {
defer close(outChan)
defer close(errChan)
req, err := g.ListRequest()
if err != nil {
errChan <- err
return
}
client.PaginateWithContext(ctx, req, func(item interface{}, e error) bool {
if item != nil {
outChan <- item
return true
}
errChan <- e
return false
})
}()
return outChan, errChan
}
// Paginate runs the ListCommand and paginates
func (client *Client) Paginate(req ListCommand, callback IterateItemFunc) {
ctx, cancel := context.WithTimeout(context.Background(), client.Timeout)
defer cancel()
client.PaginateWithContext(ctx, req, callback)
}
// PaginateWithContext runs the ListCommand as long as the ctx is valid
func (client *Client) PaginateWithContext(ctx context.Context, req ListCommand, callback IterateItemFunc) {
pageSize := client.PageSize
page := 1
for {
req.SetPage(page)
req.SetPageSize(pageSize)
resp, err := client.RequestWithContext(ctx, req)
if err != nil {
callback(nil, err)
break
}
size := 0
didErr := false
req.each(resp, func(element interface{}, err error) bool {
// If the context was cancelled, kill it in flight
if e := ctx.Err(); e != nil {
element = nil
err = e
}
if callback(element, err) {
size++
return true
}
didErr = true
return false
})
if size < pageSize || didErr {
break
}
page++
}
}
// APIName returns the CloudStack name of the given command
func (client *Client) APIName(command Command) string {
// This is due to a limitation of Go<=1.7
if _, ok := command.(*AuthorizeSecurityGroupEgress); ok {
return "authorizeSecurityGroupEgress"
}
info, err := info(command)
if err != nil {
panic(err)
}
return info.Name
}
// APIDescription returns the description of the given CloudStack command
func (client *Client) APIDescription(command Command) string {
info, err := info(command)
if err != nil {
panic(err)
}
return info.Description
}
// Response returns the response structure of the given command
func (client *Client) Response(command Command) interface{} {
switch command.(type) {
case AsyncCommand:
return (command.(AsyncCommand)).asyncResponse()
default:
return command.response()
}
}
// TraceOn activates the HTTP tracer
func (client *Client) TraceOn() {
if _, ok := client.HTTPClient.Transport.(*traceTransport); !ok {
client.HTTPClient.Transport = &traceTransport{
transport: client.HTTPClient.Transport,
logger: client.Logger,
}
}
}
// TraceOff deactivates the HTTP tracer
func (client *Client) TraceOff() {
if rt, ok := client.HTTPClient.Transport.(*traceTransport); ok {
client.HTTPClient.Transport = rt.transport
}
}
// traceTransport contains the original HTTP transport to enable it to be reverted
type traceTransport struct {
transport http.RoundTripper
logger *log.Logger
}
// RoundTrip executes a single HTTP transaction
func (t *traceTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if dump, err := httputil.DumpRequest(req, true); err == nil {
t.logger.Printf("%s", dump)
}
resp, err := t.transport.RoundTrip(req)
if err != nil {
return nil, err
}
if dump, err := httputil.DumpResponse(resp, true); err == nil {
t.logger.Printf("%s", dump)
}
return resp, nil
}
// MonotonicRetryStrategyFunc returns a function that waits for n seconds for each iteration
func MonotonicRetryStrategyFunc(seconds int) RetryStrategyFunc {
return func(iteration int64) time.Duration {
return time.Duration(seconds) * time.Second
}
}
// FibonacciRetryStrategy waits for an increasing amount of time following the Fibonacci sequence
func FibonacciRetryStrategy(iteration int64) time.Duration {
var a, b, i, tmp int64
a = 0
b = 1
for i = 0; i < iteration; i++ {
tmp = a + b
a = b
b = tmp
}
return time.Duration(a) * time.Second
}

37
vendor/github.com/exoscale/egoscale/copier.go generated vendored Normal file
View file

@ -0,0 +1,37 @@
package egoscale
import (
"fmt"
"reflect"
)
// Copy copies the value from from into to. The type of "from" must be convertible into the type of "to".
func Copy(to, from interface{}) error {
tt := reflect.TypeOf(to)
tv := reflect.ValueOf(to)
ft := reflect.TypeOf(from)
fv := reflect.ValueOf(from)
if tt.Kind() != reflect.Ptr {
return fmt.Errorf("must copy to a pointer, got %q", tt.Name())
}
tt = tt.Elem()
tv = tv.Elem()
for {
if ft.ConvertibleTo(tt) {
break
}
if ft.Kind() == reflect.Ptr {
ft = ft.Elem()
fv = fv.Elem()
} else {
return fmt.Errorf("cannot convert %q into %q", tt.Name(), ft.Name())
}
}
tv.Set(fv.Convert(tt))
return nil
}

View file

@ -0,0 +1,47 @@
// Code generated by "stringer -type CSErrorCode"; DO NOT EDIT.
package egoscale
import "strconv"
const _CSErrorCode_name = "CloudRuntimeExceptionExecutionExceptionHypervisorVersionChangedExceptionCloudExceptionAccountLimitExceptionAgentUnavailableExceptionCloudAuthenticationExceptionConcurrentOperationExceptionConflictingNetworkSettingsExceptionDiscoveredWithErrorExceptionHAStateExceptionInsufficientAddressCapacityExceptionInsufficientCapacityExceptionInsufficientNetworkCapacityExceptionInsufficientServerCapacityExceptionInsufficientStorageCapacityExceptionInternalErrorExceptionInvalidParameterValueExceptionManagementServerExceptionNetworkRuleConflictExceptionPermissionDeniedExceptionResourceAllocationExceptionResourceInUseExceptionResourceUnavailableExceptionStorageUnavailableExceptionUnsupportedServiceExceptionVirtualMachineMigrationExceptionAsyncCommandQueuedRequestLimitExceptionServerAPIException"
var _CSErrorCode_map = map[CSErrorCode]string{
4250: _CSErrorCode_name[0:21],
4260: _CSErrorCode_name[21:39],
4265: _CSErrorCode_name[39:72],
4275: _CSErrorCode_name[72:86],
4280: _CSErrorCode_name[86:107],
4285: _CSErrorCode_name[107:132],
4290: _CSErrorCode_name[132:160],
4300: _CSErrorCode_name[160:188],
4305: _CSErrorCode_name[188:223],
4310: _CSErrorCode_name[223:251],
4315: _CSErrorCode_name[251:267],
4320: _CSErrorCode_name[267:303],
4325: _CSErrorCode_name[303:332],
4330: _CSErrorCode_name[332:368],
4335: _CSErrorCode_name[368:403],
4340: _CSErrorCode_name[403:439],
4345: _CSErrorCode_name[439:461],
4350: _CSErrorCode_name[461:491],
4355: _CSErrorCode_name[491:516],
4360: _CSErrorCode_name[516:544],
4365: _CSErrorCode_name[544:569],
4370: _CSErrorCode_name[569:596],
4375: _CSErrorCode_name[596:618],
4380: _CSErrorCode_name[618:646],
4385: _CSErrorCode_name[646:673],
4390: _CSErrorCode_name[673:700],
4395: _CSErrorCode_name[700:732],
4540: _CSErrorCode_name[732:750],
4545: _CSErrorCode_name[750:771],
9999: _CSErrorCode_name[771:789],
}
func (i CSErrorCode) String() string {
if str, ok := _CSErrorCode_map[i]; ok {
return str
}
return "CSErrorCode(" + strconv.FormatInt(int64(i), 10) + ")"
}

322
vendor/github.com/exoscale/egoscale/dns.go generated vendored Normal file
View file

@ -0,0 +1,322 @@
package egoscale
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
)
// DNSDomain represents a domain
type DNSDomain struct {
ID int64 `json:"id"`
AccountID int64 `json:"account_id,omitempty"`
UserID int64 `json:"user_id,omitempty"`
RegistrantID int64 `json:"registrant_id,omitempty"`
Name string `json:"name"`
UnicodeName string `json:"unicode_name"`
Token string `json:"token"`
State string `json:"state"`
Language string `json:"language,omitempty"`
Lockable bool `json:"lockable"`
AutoRenew bool `json:"auto_renew"`
WhoisProtected bool `json:"whois_protected"`
RecordCount int64 `json:"record_count"`
ServiceCount int64 `json:"service_count"`
ExpiresOn string `json:"expires_on,omitempty"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
// DNSDomainResponse represents a domain creation response
type DNSDomainResponse struct {
Domain *DNSDomain `json:"domain"`
}
// DNSRecord represents a DNS record
type DNSRecord struct {
ID int64 `json:"id,omitempty"`
DomainID int64 `json:"domain_id,omitempty"`
Name string `json:"name"`
TTL int `json:"ttl,omitempty"`
CreatedAt string `json:"created_at,omitempty"`
UpdatedAt string `json:"updated_at,omitempty"`
Content string `json:"content"`
RecordType string `json:"record_type"`
Prio int `json:"prio,omitempty"`
}
// DNSRecordResponse represents the creation of a DNS record
type DNSRecordResponse struct {
Record DNSRecord `json:"record"`
}
// UpdateDNSRecord represents a DNS record
type UpdateDNSRecord struct {
ID int64 `json:"id,omitempty"`
DomainID int64 `json:"domain_id,omitempty"`
Name string `json:"name,omitempty"`
TTL int `json:"ttl,omitempty"`
CreatedAt string `json:"created_at,omitempty"`
UpdatedAt string `json:"updated_at,omitempty"`
Content string `json:"content,omitempty"`
RecordType string `json:"record_type,omitempty"`
Prio int `json:"prio,omitempty"`
}
// UpdateDNSRecordResponse represents the creation of a DNS record
type UpdateDNSRecordResponse struct {
Record UpdateDNSRecord `json:"record"`
}
// DNSErrorResponse represents an error in the API
type DNSErrorResponse struct {
Message string `json:"message,omitempty"`
Errors *DNSError `json:"errors"`
}
// DNSError represents an error
type DNSError struct {
Name []string `json:"name"`
}
// Record represent record type
type Record int
//go:generate stringer -type=Record
const (
// A record type
A Record = iota
// AAAA record type
AAAA
// ALIAS record type
ALIAS
// CNAME record type
CNAME
// HINFO record type
HINFO
// MX record type
MX
// NAPTR record type
NAPTR
// NS record type
NS
// POOL record type
POOL
// SPF record type
SPF
// SRV record type
SRV
// SSHFP record type
SSHFP
// TXT record type
TXT
// URL record type
URL
)
// Error formats the DNSerror into a string
func (req *DNSErrorResponse) Error() string {
if req.Errors != nil {
return fmt.Sprintf("dns error: %s (%s)", req.Message, strings.Join(req.Errors.Name, ", "))
}
return fmt.Sprintf("dns error: %s", req.Message)
}
// CreateDomain creates a DNS domain
func (client *Client) CreateDomain(name string) (*DNSDomain, error) {
m, err := json.Marshal(DNSDomainResponse{
Domain: &DNSDomain{
Name: name,
},
})
if err != nil {
return nil, err
}
resp, err := client.dnsRequest("/v1/domains", string(m), "POST")
if err != nil {
return nil, err
}
var d *DNSDomainResponse
if err := json.Unmarshal(resp, &d); err != nil {
return nil, err
}
return d.Domain, nil
}
// GetDomain gets a DNS domain
func (client *Client) GetDomain(name string) (*DNSDomain, error) {
resp, err := client.dnsRequest("/v1/domains/"+name, "", "GET")
if err != nil {
return nil, err
}
var d *DNSDomainResponse
if err := json.Unmarshal(resp, &d); err != nil {
return nil, err
}
return d.Domain, nil
}
// GetDomains gets DNS domains
func (client *Client) GetDomains() ([]DNSDomain, error) {
resp, err := client.dnsRequest("/v1/domains", "", "GET")
if err != nil {
return nil, err
}
var d []DNSDomainResponse
if err := json.Unmarshal(resp, &d); err != nil {
return nil, err
}
domains := make([]DNSDomain, len(d))
for i := range d {
domains[i] = *d[i].Domain
}
return domains, nil
}
// DeleteDomain delets a DNS domain
func (client *Client) DeleteDomain(name string) error {
_, err := client.dnsRequest("/v1/domains/"+name, "", "DELETE")
return err
}
// GetRecord returns a DNS record
func (client *Client) GetRecord(domain string, recordID int64) (*DNSRecord, error) {
id := strconv.FormatInt(recordID, 10)
resp, err := client.dnsRequest("/v1/domains/"+domain+"/records/"+id, "", "GET")
if err != nil {
return nil, err
}
var r DNSRecordResponse
if err = json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &(r.Record), nil
}
// GetRecords returns the DNS records
func (client *Client) GetRecords(name string) ([]DNSRecord, error) {
resp, err := client.dnsRequest("/v1/domains/"+name+"/records", "", "GET")
if err != nil {
return nil, err
}
var r []DNSRecordResponse
if err = json.Unmarshal(resp, &r); err != nil {
return nil, err
}
records := make([]DNSRecord, 0, len(r))
for _, rec := range r {
records = append(records, rec.Record)
}
return records, nil
}
// CreateRecord creates a DNS record
func (client *Client) CreateRecord(name string, rec DNSRecord) (*DNSRecord, error) {
body, err := json.Marshal(DNSRecordResponse{
Record: rec,
})
if err != nil {
return nil, err
}
resp, err := client.dnsRequest("/v1/domains/"+name+"/records", string(body), "POST")
if err != nil {
return nil, err
}
var r DNSRecordResponse
if err = json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &(r.Record), nil
}
// UpdateRecord updates a DNS record
func (client *Client) UpdateRecord(name string, rec UpdateDNSRecord) (*DNSRecord, error) {
body, err := json.Marshal(UpdateDNSRecordResponse{
Record: rec,
})
if err != nil {
return nil, err
}
id := strconv.FormatInt(rec.ID, 10)
resp, err := client.dnsRequest("/v1/domains/"+name+"/records/"+id, string(body), "PUT")
if err != nil {
return nil, err
}
var r DNSRecordResponse
if err = json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &(r.Record), nil
}
// DeleteRecord deletes a record
func (client *Client) DeleteRecord(name string, recordID int64) error {
id := strconv.FormatInt(recordID, 10)
_, err := client.dnsRequest("/v1/domains/"+name+"/records/"+id, "", "DELETE")
return err
}
func (client *Client) dnsRequest(uri string, params string, method string) (json.RawMessage, error) {
url := client.Endpoint + uri
req, err := http.NewRequest(method, url, strings.NewReader(params))
if err != nil {
return nil, err
}
var hdr = make(http.Header)
hdr.Add("X-DNS-TOKEN", client.APIKey+":"+client.apiSecret)
hdr.Add("User-Agent", fmt.Sprintf("exoscale/egoscale (%v)", Version))
hdr.Add("Accept", "application/json")
if params != "" {
hdr.Add("Content-Type", "application/json")
}
req.Header = hdr
resp, err := client.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close() // nolint: errcheck
contentType := resp.Header.Get("content-type")
if !strings.Contains(contentType, "application/json") {
return nil, fmt.Errorf(`response content-type expected to be "application/json", got %q`, contentType)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode >= 400 {
e := new(DNSErrorResponse)
if err := json.Unmarshal(b, e); err != nil {
return nil, err
}
return nil, e
}
return b, nil
}

177
vendor/github.com/exoscale/egoscale/doc.go generated vendored Normal file
View file

@ -0,0 +1,177 @@
/*
Package egoscale is a mapping for with the CloudStack API (http://cloudstack.apache.org/api.html) from Go. It has been designed against the Exoscale (https://www.exoscale.com/) infrastructure but should fit other CloudStack services.
Requests and Responses
To build a request, construct the adequate struct. This library expects a pointer for efficiency reasons only. The response is a struct corresponding to the data at stake. E.g. DeployVirtualMachine gives a VirtualMachine, as a pointer as well to avoid big copies.
Then everything within the struct is not a pointer. Find below some examples of how egoscale may be used to interact with a CloudStack endpoint, especially Exoscale itself. If anything feels odd or unclear, please let us know: https://github.com/exoscale/egoscale/issues
req := &egoscale.DeployVirtualMachine{
Size: 10,
ServiceOfferingID: "...",
TemplateID: "...",
ZoneID: "...",
}
fmt.Println("Deployment started")
resp, err := cs.Request(req)
if err != nil {
panic(err)
}
vm := resp.(*egoscale.VirtualMachine)
fmt.Printf("Virtual Machine ID: %s\n", vm.ID)
This exemple deploys a virtual machine while controlling the job status as it goes. It enables a finer control over errors, e.g. HTTP timeout, and eventually a way to kill it of (from the client side).
req := &egoscale.DeployVirtualMachine{
Size: 10,
ServiceOfferingID: "...",
TemplateID: "...",
ZoneID: "...",
}
vm := &egoscale.VirtualMachine{}
fmt.Println("Deployment started")
cs.AsyncRequest(req, func(jobResult *egoscale.AsyncJobResult, err error) bool {
if err != nil {
// any kind of error
panic(err)
}
// Keep waiting
if jobResult.JobStatus == egoscale.Pending {
fmt.Println("wait...")
return true
}
// Unmarshal the response into the response struct
if err := jobResult.Response(vm); err != nil {
// JSON unmarshaling error
panic(err)
}
// Stop waiting
return false
})
fmt.Printf("Virtual Machine ID: %s\n", vm.ID)
Debugging and traces
As this library is mostly an HTTP client, you can reuse all the existing tools around it.
cs := egoscale.NewClient("https://api.exoscale.ch/compute", "EXO...", "...")
// sets a logger on stderr
cs.Logger = log.Newos.Stderr, "prefix", log.LstdFlags)
// activates the HTTP traces
cs.TraceOn()
Nota bene: when running the tests or the egoscale library via another tool, e.g. the exo cli (or the cs cli), the environment variable EXOSCALE_TRACE=prefix does the above configuration for you. As a developer using egoscale as a library, you'll find it more convenient to plug your favorite io.Writer as it's Logger.
APIs
All the available APIs on the server and provided by the API Discovery plugin
cs := egoscale.NewClient("https://api.exoscale.ch/compute", "EXO...", "...")
resp, err := cs.Request(&egoscale.ListAPIs{})
if err != nil {
panic(err)
}
for _, api := range resp.(*egoscale.ListAPIsResponse).API {
fmt.Printf("%s %s\n", api.Name, api.Description)
}
// Output:
// listNetworks Lists all available networks
// ...
Security Groups
Security Groups provide a way to isolate traffic to VMs. Rules are added via the two Authorization commands.
resp, err := cs.Request(&egoscale.CreateSecurityGroup{
Name: "Load balancer",
Description: "Opens HTTP/HTTPS ports from the outside world",
})
securityGroup := resp.(*egoscale.SecurityGroup)
resp, err = cs.Request(&egoscale.AuthorizeSecurityGroupIngress{
Description: "SSH traffic",
SecurityGroupID: securityGroup.ID,
CidrList: []string{"0.0.0.0/0"},
Protocol: "tcp",
StartPort: 22,
EndPort: 22,
})
// The modified SecurityGroup is returned
securityGroup := resp.(*egoscale.SecurityGroup)
// ...
err = client.BooleanRequest(&egoscale.DeleteSecurityGroup{
ID: securityGroup.ID,
})
// ...
Security Group also implement the generic List, Get and Delete interfaces (Listable, Gettable and Deletable).
// List all Security Groups
sgs, err := cs.List(new(egoscale.SecurityGroup))
for _, s := range sgs {
sg := s.(egoscale.SecurityGroup)
// ...
}
// Get a Security Group
sg := &egoscale.SecurityGroup{Name: "Load balancer"}
if err := cs.Get(sg); err != nil {
...
}
// The SecurityGroup struct has been loaded with the SecurityGroup informations
if err := cs.Delete(sg); err != nil {
...
}
// The SecurityGroup has been deleted
See: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/stable/networking_and_traffic.html#security-groups
Zones
A Zone corresponds to a Data Center. You may list them. Zone implements the Listable interface, which let you perform a list in two different ways. The first exposes the underlying CloudStack request while the second one hide them and you only manipulate the structs of your interest.
// Using ListZones request
req := &egoscale.ListZones{}
resp, err := client.Request(req)
if err != nil {
panic(err)
}
for _, zone := range resp.(*egoscale.ListZonesResponse) {
...
}
// Using client.List
zone := &egoscale.Zone{}
zones, err := client.List(zone)
if err != nil {
panic(err)
}
for _, z := range zones {
zone := z.(egoscale.Zone)
...
}
Elastic IPs
An Elastic IP is a way to attach an IP address to many Virtual Machines. The API side of the story configures the external environment, like the routing. Some work is required within the machine to properly configure the interfaces.
See: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/latest/networking_and_traffic.html#about-elastic-ips
*/
package egoscale

View file

@ -0,0 +1,37 @@
// Code generated by "stringer -type ErrorCode"; DO NOT EDIT.
package egoscale
import "strconv"
const (
_ErrorCode_name_0 = "Unauthorized"
_ErrorCode_name_1 = "MethodNotAllowed"
_ErrorCode_name_2 = "UnsupportedActionError"
_ErrorCode_name_3 = "APILimitExceededMalformedParameterErrorParamError"
_ErrorCode_name_4 = "InternalErrorAccountErrorAccountResourceLimitErrorInsufficientCapacityErrorResourceUnavailableErrorResourceAllocationErrorResourceInUseErrorNetworkRuleConflictError"
)
var (
_ErrorCode_index_3 = [...]uint8{0, 16, 39, 49}
_ErrorCode_index_4 = [...]uint8{0, 13, 25, 50, 75, 99, 122, 140, 164}
)
func (i ErrorCode) String() string {
switch {
case i == 401:
return _ErrorCode_name_0
case i == 405:
return _ErrorCode_name_1
case i == 422:
return _ErrorCode_name_2
case 429 <= i && i <= 431:
i -= 429
return _ErrorCode_name_3[_ErrorCode_index_3[i]:_ErrorCode_index_3[i+1]]
case 530 <= i && i <= 537:
i -= 530
return _ErrorCode_name_4[_ErrorCode_index_4[i]:_ErrorCode_index_4[i+1]]
default:
return "ErrorCode(" + strconv.FormatInt(int64(i), 10) + ")"
}
}

66
vendor/github.com/exoscale/egoscale/events.go generated vendored Normal file
View file

@ -0,0 +1,66 @@
package egoscale
// Event represents an event in the system
type Event struct {
Account string `json:"account,omitempty" doc:"the account name for the account that owns the object being acted on in the event (e.g. the owner of the virtual machine, ip address, or security group)"`
Created string `json:"created,omitempty" doc:"the date the event was created"`
Description string `json:"description,omitempty" doc:"a brief description of the event"`
Domain string `json:"domain,omitempty" doc:"the name of the account's domain"`
DomainID string `json:"domainid,omitempty" doc:"the id of the account's domain"`
ID string `json:"id,omitempty" doc:"the ID of the event"`
Level string `json:"level,omitempty" doc:"the event level (INFO, WARN, ERROR)"`
ParentID string `json:"parentid,omitempty" doc:"whether the event is parented"`
State string `json:"state,omitempty" doc:"the state of the event"`
Type string `json:"type,omitempty" doc:"the type of the event (see event types)"`
UserName string `json:"username,omitempty" doc:"the name of the user who performed the action (can be different from the account if an admin is performing an action for a user, e.g. starting/stopping a user's virtual machine)"`
}
// EventType represent a type of event
type EventType struct {
Name string `json:"name,omitempty" doc:"Event Type"`
}
// ListEvents list the events
type ListEvents struct {
Account string `json:"account,omitempty" doc:"list resources by account. Must be used with the domainId parameter."`
DomainID string `json:"domainid,omitempty" doc:"list only resources belonging to the domain specified"`
Duration int `json:"duration,omitempty" doc:"the duration of the event"`
EndDate string `json:"enddate,omitempty" doc:"the end date range of the list you want to retrieve (use format \"yyyy-MM-dd\" or the new format \"yyyy-MM-dd HH:mm:ss\")"`
EntryTime int `json:"entrytime,omitempty" doc:"the time the event was entered"`
ID string `json:"id,omitempty" doc:"the ID of the event"`
IsRecursive *bool `json:"isrecursive,omitempty" doc:"defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves." doc:"defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves."`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
Level string `json:"level,omitempty" doc:"the event level (INFO, WARN, ERROR)"`
ListAll *bool `json:"listall,omitempty" doc:"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"`
Page int `json:"page,omitempty" `
PageSize int `json:"pagesize,omitempty"`
StartDate string `json:"startdate,omitempty" doc:"the start date range of the list you want to retrieve (use format \"yyyy-MM-dd\" or the new format \"yyyy-MM-dd HH:mm:ss\")"`
Type string `json:"type,omitempty" doc:"the event type (see event types)"`
_ bool `name:"listEvents" description:"A command to list events."`
}
// ListEventsResponse represents a response of a list query
type ListEventsResponse struct {
Count int `json:"count"`
Event []Event `json:"event"`
}
func (ListEvents) response() interface{} {
return new(ListEventsResponse)
}
// ListEventTypes list the event types
type ListEventTypes struct {
_ bool `name:"listEventTypes" description:"List Event Types"`
}
// ListEventTypesResponse represents a response of a list query
type ListEventTypesResponse struct {
Count int `json:"count"`
EventType []EventType `json:"eventtype"`
_ bool `name:"listEventTypes" description:"List Event Types"`
}
func (ListEventTypes) response() interface{} {
return new(ListEventTypesResponse)
}

BIN
vendor/github.com/exoscale/egoscale/gopher.png generated vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

99
vendor/github.com/exoscale/egoscale/hosts.go generated vendored Normal file
View file

@ -0,0 +1,99 @@
package egoscale
import (
"net"
)
// Host represents the Hypervisor
type Host struct {
Capabilities string `json:"capabilities,omitempty" doc:"capabilities of the host"`
ClusterID string `json:"clusterid,omitempty" doc:"the cluster ID of the host"`
ClusterName string `json:"clustername,omitempty" doc:"the cluster name of the host"`
ClusterType string `json:"clustertype,omitempty" doc:"the cluster type of the cluster that host belongs to"`
CPUAllocated int64 `json:"cpuallocated,omitempty" doc:"the amount of the host's CPU currently allocated"`
CPUNumber int `json:"cpunumber,omitempty" doc:"the CPU number of the host"`
CPUSockets int `json:"cpusockets,omitempty" doc:"the number of CPU sockets on the host"`
CPUSpeed int64 `json:"cpuspeed,omitempty" doc:"the CPU speed of the host"`
CPUUsed int64 `json:"cpuused,omitempty" doc:"the amount of the host's CPU currently used"`
CPUWithOverProvisioning int64 `json:"cpuwithoverprovisioning,omitempty" doc:"the amount of the host's CPU after applying the cpu.overprovisioning.factor"`
Created string `json:"created,omitempty" doc:"the date and time the host was created"`
Disconnected string `json:"disconnected,omitempty" doc:"true if the host is disconnected. False otherwise."`
DiskSizeAllocated int64 `json:"disksizeallocated,omitempty" doc:"the host's or host storage pool's currently allocated disk size"`
DiskSizeTotal int64 `json:"disksizetotal,omitempty" doc:"the total disk size of the host or host storage pool"`
DiskSizeUsed int64 `json:"disksizeused,omitempty" doc:"the host's or host storage pool's currently used disk size"`
DiskWithOverProvisioning int64 `json:"diskwithoverprovisioning,omitempty" doc:"the total disk size of the host or host storage pool with over provisioning factor"`
Events string `json:"events,omitempty" doc:"events available for the host"`
HAHost *bool `json:"hahost,omitempty" doc:"true if the host is Ha host (dedicated to vms started by HA process; false otherwise"`
HostTags string `json:"hosttags,omitempty" doc:"comma-separated list of tags for the host"`
Hypervisor string `json:"hypervisor,omitempty" doc:"the host hypervisor"`
HypervisorVersion string `json:"hypervisorversion,omitempty" doc:"the hypervisor version"`
ID string `json:"id,omitempty" doc:"the ID of the host"`
IPAddress net.IP `json:"ipaddress,omitempty" doc:"the IP address of the host"`
IsLocalstorageActive *bool `json:"islocalstorageactive,omitempty" doc:"true if local storage is active, false otherwise"`
LastPinged string `json:"lastpinged,omitempty" doc:"the date and time the host was last pinged"`
ManagementServerID string `json:"managementserverid,omitempty" doc:"the management server ID of the host"`
MemoryAllocated int64 `json:"memoryallocated,omitempty" doc:"the amount of VM's memory allocated onto the host"`
MemoryPhysical int64 `json:"memoryphysical,omitempty" doc:"the total physical memory of the host"`
MemoryReserved int64 `json:"memoryreserved,omitempty" doc:"the amount of the host's memory reserved"`
MemoryTotal int64 `json:"memorytotal,omitempty" doc:"the total memory of the host available (must be physical - reserved)"`
MemoryUsed int64 `json:"memoryused,omitempty" doc:"the amount of the host's memory used by running vm"`
Name string `json:"name,omitempty" doc:"the name of the host"`
NetworkKbsRead int64 `json:"networkkbsread,omitempty" doc:"the incoming network traffic on the host"`
NetworkKbsWrite int64 `json:"networkkbswrite,omitempty" doc:"the outgoing network traffic on the host"`
OSCategoryID string `json:"oscategoryid,omitempty" doc:"the OS category ID of the host"`
OSCategoryName string `json:"oscategoryname,omitempty" doc:"the OS category name of the host"`
PCIDevices []PCIDevice `json:"pcidevices,omitempty" doc:"PCI cards present in the host"`
PodID string `json:"podid,omitempty" doc:"the Pod ID of the host"`
PodName string `json:"podname,omitempty" doc:"the Pod name of the host"`
Removed string `json:"removed,omitempty" doc:"the date and time the host was removed"`
ResourceState string `json:"resourcestate,omitempty" doc:"the resource state of the host"`
State string `json:"state,omitempty" doc:"the state of the host"`
StorageID string `json:"storageid,omitempty" doc:"the host's storage pool id"`
Type string `json:"type,omitempty" doc:"the host type"`
Version string `json:"version,omitempty" doc:"the host version"`
ZoneID string `json:"zoneid,omitempty" doc:"the Zone ID of the host"`
ZoneName string `json:"zonename,omitempty" doc:"the Zone name of the host"`
}
// ListHosts lists hosts
type ListHosts struct {
ClusterID string `json:"clusterid,omitempty" doc:"lists hosts existing in particular cluster"`
Details []string `json:"details,omitempty" doc:"comma separated list of host details requested, value can be a list of [ min, all, capacity, events, stats]"`
HAHost *bool `json:"hahost,omitempty" doc:"if true, list only hosts dedicated to HA"`
Hypervisor string `json:"hypervisor,omitempty" doc:"hypervisor type of host: KVM,Simulator"`
ID string `json:"id,omitempty" doc:"the id of the host"`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
Name string `json:"name,omitempty" doc:"the name of the host"`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
PodID string `json:"podid,omitempty" doc:"the Pod ID for the host"`
ResourceState string `json:"resourcestate,omitempty" doc:"list hosts by resource state. Resource state represents current state determined by admin of host, value can be one of [Enabled, Disabled, Unmanaged, PrepareForMaintenance, ErrorInMaintenance, Maintenance, Error]"`
State string `json:"state,omitempty" doc:"the state of the host"`
Type string `json:"type,omitempty" doc:"the host type"`
ZoneID string `json:"zoneid,omitempty" doc:"the Zone ID for the host"`
_ bool `name:"listHosts" description:"Lists hosts."`
}
func (ListHosts) response() interface{} {
return new(ListHostsResponse)
}
// ListHostsResponse represents a list of hosts
type ListHostsResponse struct {
Count int `json:"count"`
Host []Host `json:"host"`
}
// UpdateHost changes the resources state of a host
type UpdateHost struct {
Allocationstate string `json:"allocationstate,omitempty" doc:"Change resource state of host, valid values are [Enable, Disable]. Operation may failed if host in states not allowing Enable/Disable"`
HostTags []string `json:"hosttags,omitempty" doc:"list of tags to be added to the host"`
ID string `json:"id" doc:"the ID of the host to update"`
OSCategoryID string `json:"oscategoryid,omitempty" doc:"the id of Os category to update the host with"`
URL string `json:"url,omitempty" doc:"the new uri for the secondary storage: nfs://host/path"`
_ bool `name:"updateHost" description:"Updates a host."`
}
func (UpdateHost) response() interface{} {
return new(Host)
}

View file

@ -0,0 +1,16 @@
// Code generated by "stringer -type JobStatusType"; DO NOT EDIT.
package egoscale
import "strconv"
const _JobStatusType_name = "PendingSuccessFailure"
var _JobStatusType_index = [...]uint8{0, 7, 14, 21}
func (i JobStatusType) String() string {
if i < 0 || i >= JobStatusType(len(_JobStatusType_index)-1) {
return "JobStatusType(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _JobStatusType_name[_JobStatusType_index[i]:_JobStatusType_index[i+1]]
}

140
vendor/github.com/exoscale/egoscale/limits.go generated vendored Normal file
View file

@ -0,0 +1,140 @@
package egoscale
// https://github.com/apache/cloudstack/blob/master/api/src/main/java/com/cloud/configuration/Resource.java
// ResourceTypeName represents the name of a resource type (for limits)
type ResourceTypeName string
const (
// VirtualMachineTypeName is the resource type name of a VM
VirtualMachineTypeName ResourceTypeName = "user_vm"
// IPAddressTypeName is the resource type name of an IP address
IPAddressTypeName ResourceTypeName = "public_ip"
// VolumeTypeName is the resource type name of a volume
VolumeTypeName ResourceTypeName = "volume"
// SnapshotTypeName is the resource type name of a snapshot
SnapshotTypeName ResourceTypeName = "snapshot"
// TemplateTypeName is the resource type name of a template
TemplateTypeName ResourceTypeName = "template"
// ProjectTypeName is the resource type name of a project
ProjectTypeName ResourceTypeName = "project"
// NetworkTypeName is the resource type name of a network
NetworkTypeName ResourceTypeName = "network"
// VPCTypeName is the resource type name of a VPC
VPCTypeName ResourceTypeName = "vpc"
// CPUTypeName is the resource type name of a CPU
CPUTypeName ResourceTypeName = "cpu"
// MemoryTypeName is the resource type name of Memory
MemoryTypeName ResourceTypeName = "memory"
// PrimaryStorageTypeName is the resource type name of primary storage
PrimaryStorageTypeName ResourceTypeName = "primary_storage"
// SecondaryStorageTypeName is the resource type name of secondary storage
SecondaryStorageTypeName ResourceTypeName = "secondary_storage"
)
// ResourceType represents the ID of a resource type (for limits)
type ResourceType int64
//go:generate stringer -type=ResourceType
const (
// VirtualMachineType is the resource type ID of a VM
VirtualMachineType ResourceType = iota
// IPAddressType is the resource type ID of an IP address
IPAddressType
// VolumeType is the resource type ID of a volume
VolumeType
// SnapshotType is the resource type ID of a snapshot
SnapshotType
// TemplateType is the resource type ID of a template
TemplateType
// ProjectType is the resource type ID of a project
ProjectType
// NetworkType is the resource type ID of a network
NetworkType
// VPCType is the resource type ID of a VPC
VPCType
// CPUType is the resource type ID of a CPU
CPUType
// MemoryType is the resource type ID of Memory
MemoryType
// PrimaryStorageType is the resource type ID of primary storage
PrimaryStorageType
// SecondaryStorageType is the resource type ID of secondary storage
SecondaryStorageType
)
// ResourceLimit represents the limit on a particular resource
type ResourceLimit struct {
Account string `json:"account,omitempty" doc:"the account of the resource limit"`
Domain string `json:"domain,omitempty" doc:"the domain name of the resource limit"`
DomainID string `json:"domainid,omitempty" doc:"the domain ID of the resource limit"`
Max int64 `json:"max,omitempty" doc:"the maximum number of the resource. A -1 means the resource currently has no limit."`
ResourceType ResourceType `json:"resourcetype,omitempty" doc:"resource type. Values include 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11. See the resourceType parameter for more information on these values."`
ResourceTypeName ResourceTypeName `json:"resourcetypename,omitempty" doc:"resource type name. Values include user_vm, public_ip, volume, snapshot, template, project, network, vpc, cpu, memory, primary_storage, secondary_storage."`
}
// APILimit represents the limit count
type APILimit struct {
Account string `json:"account,omitempty" doc:"the account name of the api remaining count"`
Accountid string `json:"accountid,omitempty" doc:"the account uuid of the api remaining count"`
APIAllowed int `json:"apiAllowed,omitempty" doc:"currently allowed number of apis"`
APIIssued int `json:"apiIssued,omitempty" doc:"number of api already issued"`
ExpireAfter int64 `json:"expireAfter,omitempty" doc:"seconds left to reset counters"`
}
// ListResourceLimits lists the resource limits
type ListResourceLimits struct {
Account string `json:"account,omitempty" doc:"list resources by account. Must be used with the domainId parameter."`
DomainID string `json:"domainid,omitempty" doc:"list only resources belonging to the domain specified"`
ID int64 `json:"id,omitempty" doc:"Lists resource limits by ID."`
IsRecursive *bool `json:"isrecursive,omitempty" doc:"defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves."`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
ListAll *bool `json:"listall,omitempty" doc:"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
ResourceType ResourceType `json:"resourcetype,omitempty" doc:"Type of resource. Values are 0, 1, 2, 3, 4, 6, 7, 8, 9, 10 and 11. 0 - Instance. Number of instances a user can create. 1 - IP. Number of public IP addresses an account can own. 2 - Volume. Number of disk volumes an account can own. 3 - Snapshot. Number of snapshots an account can own. 4 - Template. Number of templates an account can register/create. 5 - Project. Number of projects an account can own. 6 - Network. Number of networks an account can own. 7 - VPC. Number of VPC an account can own. 8 - CPU. Number of CPU an account can allocate for his resources. 9 - Memory. Amount of RAM an account can allocate for his resources. 10 - PrimaryStorage. Total primary storage space (in GiB) a user can use. 11 - SecondaryStorage. Total secondary storage space (in GiB) a user can use. 12 - Elastic IP. Number of public elastic IP addresses an account can own. 13 - SMTP. If the account is allowed SMTP outbound traffic."`
ResourceTypeName ResourceTypeName `json:"resourcetypename,omitempty" doc:"Type of resource (wins over resourceType if both are provided). Values are: user_vm - Instance. Number of instances a user can create. public_ip - IP. Number of public IP addresses an account can own. volume - Volume. Number of disk volumes an account can own. snapshot - Snapshot. Number of snapshots an account can own. template - Template. Number of templates an account can register/create. project - Project. Number of projects an account can own. network - Network. Number of networks an account can own. vpc - VPC. Number of VPC an account can own. cpu - CPU. Number of CPU an account can allocate for his resources. memory - Memory. Amount of RAM an account can allocate for his resources. primary_storage - PrimaryStorage. Total primary storage space (in GiB) a user can use. secondary_storage - SecondaryStorage. Total secondary storage space (in GiB) a user can use. public_elastic_ip - IP. Number of public elastic IP addresses an account can own. smtp - SG. If the account is allowed SMTP outbound traffic."`
_ bool `name:"listResourceLimits" description:"Lists resource limits."`
}
// ListResourceLimitsResponse represents a list of resource limits
type ListResourceLimitsResponse struct {
Count int `json:"count"`
ResourceLimit []ResourceLimit `json:"resourcelimit"`
}
func (ListResourceLimits) response() interface{} {
return new(ListResourceLimitsResponse)
}
// UpdateResourceLimit updates the resource limit
type UpdateResourceLimit struct {
Account string `json:"account,omitempty" doc:"Update resource for a specified account. Must be used with the domainId parameter."`
DomainID string `json:"domainid,omitempty" doc:"Update resource limits for all accounts in specified domain. If used with the account parameter, updates resource limits for a specified account in specified domain."`
Max int64 `json:"max,omitempty" doc:"Maximum resource limit."`
ResourceType ResourceType `json:"resourcetype" doc:"Type of resource to update. Values are 0, 1, 2, 3, 4, 6, 7, 8, 9, 10 and 11. 0 - Instance. Number of instances a user can create. 1 - IP. Number of public IP addresses a user can own. 2 - Volume. Number of disk volumes a user can create. 3 - Snapshot. Number of snapshots a user can create. 4 - Template. Number of templates that a user can register/create. 6 - Network. Number of guest network a user can create. 7 - VPC. Number of VPC a user can create. 8 - CPU. Total number of CPU cores a user can use. 9 - Memory. Total Memory (in MB) a user can use. 10 - PrimaryStorage. Total primary storage space (in GiB) a user can use. 11 - SecondaryStorage. Total secondary storage space (in GiB) a user can use."`
_ bool `name:"updateResourceLimit" description:"Updates resource limits for an account or domain."`
}
// UpdateResourceLimitResponse represents an updated resource limit
type UpdateResourceLimitResponse struct {
ResourceLimit ResourceLimit `json:"resourcelimit"`
}
func (UpdateResourceLimit) response() interface{} {
return new(UpdateResourceLimitResponse)
}
// GetAPILimit gets API limit count for the caller
type GetAPILimit struct {
_ bool `name:"getApiLimit" description:"Get API limit count for the caller"`
}
// GetAPILimitResponse represents the limits towards the API call
type GetAPILimitResponse struct {
APILimit APILimit `json:"apilimit"`
}
func (GetAPILimit) response() interface{} {
return new(GetAPILimitResponse)
}

63
vendor/github.com/exoscale/egoscale/macaddress.go generated vendored Normal file
View file

@ -0,0 +1,63 @@
package egoscale
import (
"encoding/json"
"fmt"
"net"
)
// MACAddress is a nicely JSON serializable net.HardwareAddr
type MACAddress net.HardwareAddr
// String returns the MAC address in standard format
func (mac MACAddress) String() string {
return (net.HardwareAddr)(mac).String()
}
// MAC48 builds a MAC-48 MACAddress
func MAC48(a, b, c, d, e, f byte) MACAddress {
m := make(MACAddress, 6)
m[0] = a
m[1] = b
m[2] = c
m[3] = d
m[4] = e
m[5] = f
return m
}
// UnmarshalJSON unmarshals the raw JSON into the MAC address
func (mac *MACAddress) UnmarshalJSON(b []byte) error {
var addr string
if err := json.Unmarshal(b, &addr); err != nil {
return err
}
hw, err := ParseMAC(addr)
if err != nil {
return err
}
*mac = make(MACAddress, 6)
copy(*mac, hw)
return nil
}
// MarshalJSON converts the MAC Address to a string representation
func (mac MACAddress) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("%q", mac.String())), nil
}
// ParseMAC converts a string into a MACAddress
func ParseMAC(s string) (MACAddress, error) {
hw, err := net.ParseMAC(s)
return (MACAddress)(hw), err
}
// ForceParseMAC acts like ParseMAC but panics if in case of an error
func ForceParseMAC(s string) MACAddress {
mac, err := ParseMAC(s)
if err != nil {
panic(err)
}
return mac
}

View file

@ -0,0 +1,77 @@
package egoscale
// NetworkOffering corresponds to the Compute Offerings
type NetworkOffering struct {
Availability string `json:"availability,omitempty" doc:"availability of the network offering"`
ConserveMode bool `json:"conservemode,omitempty" doc:"true if network offering is ip conserve mode enabled"`
Created string `json:"created,omitempty" doc:"the date this network offering was created"`
Details map[string]string `json:"details,omitempty" doc:"additional key/value details tied with network offering"`
DisplayText string `json:"displaytext,omitempty" doc:"an alternate display text of the network offering."`
EgressDefaultPolicy bool `json:"egressdefaultpolicy,omitempty" doc:"true if guest network default egress policy is allow; false if default egress policy is deny"`
GuestIPType string `json:"guestiptype,omitempty" doc:"guest type of the network offering, can be Shared or Isolated"`
ID string `json:"id,omitempty" doc:"the id of the network offering"`
IsDefault bool `json:"isdefault,omitempty" doc:"true if network offering is default, false otherwise"`
IsPersistent bool `json:"ispersistent,omitempty" doc:"true if network offering supports persistent networks, false otherwise"`
MaxConnections int `json:"maxconnections,omitempty" doc:"maximum number of concurrents connections to be handled by lb"`
Name string `json:"name,omitempty" doc:"the name of the network offering"`
NetworkRate int `json:"networkrate,omitempty" doc:"data transfer rate in megabits per second allowed."`
Service []Service `json:"service,omitempty" doc:"the list of supported services"`
ServiceOfferingID string `json:"serviceofferingid,omitempty" doc:"the ID of the service offering used by virtual router provider"`
SpecifyIPRanges bool `json:"specifyipranges,omitempty" doc:"true if network offering supports specifying ip ranges, false otherwise"`
SpecifyVlan bool `json:"specifyvlan,omitempty" doc:"true if network offering supports vlans, false otherwise"`
State string `json:"state,omitempty" doc:"state of the network offering. Can be Disabled/Enabled/Inactive"`
SupportsStrechedL2Subnet bool `json:"supportsstrechedl2subnet,omitempty" doc:"true if network offering supports network that span multiple zones"`
Tags string `json:"tags,omitempty" doc:"the tags for the network offering"`
TrafficType string `json:"traffictype,omitempty" doc:"the traffic type for the network offering, supported types are Public, Management, Control, Guest, Vlan or Storage."`
}
// ListNetworkOfferings represents a query for network offerings
type ListNetworkOfferings struct {
Availability string `json:"availability,omitempty" doc:"the availability of network offering. Default value is Required"`
DisplayText string `json:"displaytext,omitempty" doc:"list network offerings by display text"`
GuestIPType string `json:"guestiptype,omitempty" doc:"list network offerings by guest type: Shared or Isolated"`
ID string `json:"id,omitempty" doc:"list network offerings by id"`
IsDefault *bool `json:"isdefault,omitempty" doc:"true if need to list only default network offerings. Default value is false"`
IsTagged *bool `json:"istagged,omitempty" doc:"true if offering has tags specified"`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
Name string `json:"name,omitempty" doc:"list network offerings by name"`
NetworkID string `json:"networkid,omitempty" doc:"the ID of the network. Pass this in if you want to see the available network offering that a network can be changed to."`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
SourceNATSupported *bool `json:"sourcenatsupported,omitempty" doc:"true if need to list only netwok offerings where source nat is supported, false otherwise"`
SpecifyIPRanges *bool `json:"specifyipranges,omitempty" doc:"true if need to list only network offerings which support specifying ip ranges"`
SpecifyVlan *bool `json:"specifyvlan,omitempty" doc:"the tags for the network offering."`
State string `json:"state,omitempty" doc:"list network offerings by state"`
SupportedServices []Service `json:"supportedservices,omitempty" doc:"list network offerings supporting certain services"`
Tags string `json:"tags,omitempty" doc:"list network offerings by tags"`
TrafficType string `json:"traffictype,omitempty" doc:"list by traffic type"`
ZoneID string `json:"zoneid,omitempty" doc:"list netowrk offerings available for network creation in specific zone"`
_ bool `name:"listNetworkOfferings" description:"Lists all available network offerings."`
}
// ListNetworkOfferingsResponse represents a list of service offerings
type ListNetworkOfferingsResponse struct {
Count int `json:"count"`
NetworkOffering []NetworkOffering `json:"networkoffering"`
}
func (ListNetworkOfferings) response() interface{} {
return new(ListNetworkOfferingsResponse)
}
// UpdateNetworkOffering represents a modification of a network offering
type UpdateNetworkOffering struct {
Availability string `json:"availability,omitempty" doc:"the availability of network offering. Default value is Required for Guest Virtual network offering; Optional for Guest Direct network offering"`
DisplayText string `json:"displaytext,omitempty" doc:"the display text of the network offering"`
ID string `json:"id,omitempty" doc:"the id of the network offering"`
KeepAliveEnabled *bool `json:"keepaliveenabled,omitempty" doc:"if true keepalive will be turned on in the loadbalancer. At the time of writing this has only an effect on haproxy; the mode http and httpclose options are unset in the haproxy conf file."`
MaxConnections int `json:"maxconnections,omitempty" doc:"maximum number of concurrent connections supported by the network offering"`
Name string `json:"name,omitempty" doc:"the name of the network offering"`
SortKey int `json:"sortkey,omitempty" doc:"sort key of the network offering, integer"`
State string `json:"state,omitempty" doc:"update state for the network offering"`
_ bool `name:"updateNetworkOffering" description:"Updates a network offering."`
}
func (UpdateNetworkOffering) response() interface{} {
return new(NetworkOffering)
}

259
vendor/github.com/exoscale/egoscale/networks.go generated vendored Normal file
View file

@ -0,0 +1,259 @@
package egoscale
import (
"fmt"
"net"
"net/url"
)
// Network represents a network
//
// See: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/latest/networking_and_traffic.html
type Network struct {
Account string `json:"account,omitempty" doc:"the owner of the network"`
AccountID string `json:"accountid,omitempty" doc:"the owner ID of the network"`
BroadcastDomainType string `json:"broadcastdomaintype,omitempty" doc:"Broadcast domain type of the network"`
BroadcastURI string `json:"broadcasturi,omitempty" doc:"broadcast uri of the network."`
CanUseForDeploy bool `json:"canusefordeploy,omitempty" doc:"list networks available for vm deployment"`
CIDR *CIDR `json:"cidr,omitempty" doc:"Cloudstack managed address space, all CloudStack managed VMs get IP address from CIDR"`
DisplayNetwork bool `json:"displaynetwork,omitempty" doc:"an optional field, whether to the display the network to the end user or not."`
DisplayText string `json:"displaytext,omitempty" doc:"the displaytext of the network"`
DNS1 net.IP `json:"dns1,omitempty" doc:"the first DNS for the network"`
DNS2 net.IP `json:"dns2,omitempty" doc:"the second DNS for the network"`
Domain string `json:"domain,omitempty" doc:"the domain name of the network owner"`
DomainID string `json:"domainid,omitempty" doc:"the domain id of the network owner"`
Gateway net.IP `json:"gateway,omitempty" doc:"the network's gateway"`
ID string `json:"id,omitempty" doc:"the id of the network"`
IP6CIDR *CIDR `json:"ip6cidr,omitempty" doc:"the cidr of IPv6 network"`
IP6Gateway net.IP `json:"ip6gateway,omitempty" doc:"the gateway of IPv6 network"`
IsDefault bool `json:"isdefault,omitempty" doc:"true if network is default, false otherwise"`
IsPersistent bool `json:"ispersistent,omitempty" doc:"list networks that are persistent"`
IsSystem bool `json:"issystem,omitempty" doc:"true if network is system, false otherwise"`
Name string `json:"name,omitempty" doc:"the name of the network"`
Netmask net.IP `json:"netmask,omitempty" doc:"the network's netmask"`
NetworkCIDR *CIDR `json:"networkcidr,omitempty" doc:"the network CIDR of the guest network configured with IP reservation. It is the summation of CIDR and RESERVED_IP_RANGE"`
NetworkDomain string `json:"networkdomain,omitempty" doc:"the network domain"`
NetworkOfferingAvailability string `json:"networkofferingavailability,omitempty" doc:"availability of the network offering the network is created from"`
NetworkOfferingConserveMode bool `json:"networkofferingconservemode,omitempty" doc:"true if network offering is ip conserve mode enabled"`
NetworkOfferingDisplayText string `json:"networkofferingdisplaytext,omitempty" doc:"display text of the network offering the network is created from"`
NetworkOfferingID string `json:"networkofferingid,omitempty" doc:"network offering id the network is created from"`
NetworkOfferingName string `json:"networkofferingname,omitempty" doc:"name of the network offering the network is created from"`
PhysicalNetworkID string `json:"physicalnetworkid,omitempty" doc:"the physical network id"`
Related string `json:"related,omitempty" doc:"related to what other network configuration"`
ReservedIPRange string `json:"reservediprange,omitempty" doc:"the network's IP range not to be used by CloudStack guest VMs and can be used for non CloudStack purposes"`
RestartRequired bool `json:"restartrequired,omitempty" doc:"true network requires restart"`
Service []Service `json:"service,omitempty" doc:"the list of services"`
SpecifyIPRanges bool `json:"specifyipranges,omitempty" doc:"true if network supports specifying ip ranges, false otherwise"`
State string `json:"state,omitempty" doc:"state of the network"`
StrechedL2Subnet bool `json:"strechedl2subnet,omitempty" doc:"true if network can span multiple zones"`
SubdomainAccess bool `json:"subdomainaccess,omitempty" doc:"true if users from subdomains can access the domain level network"`
Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with network"`
TrafficType string `json:"traffictype,omitempty" doc:"the traffic type of the network"`
Type string `json:"type,omitempty" doc:"the type of the network"`
Vlan string `json:"vlan,omitemtpy" doc:"The vlan of the network. This parameter is visible to ROOT admins only"`
ZoneID string `json:"zoneid,omitempty" doc:"zone id of the network"`
ZoneName string `json:"zonename,omitempty" doc:"the name of the zone the network belongs to"`
ZonesNetworkSpans []Zone `json:"zonesnetworkspans,omitempty" doc:"If a network is enabled for 'streched l2 subnet' then represents zones on which network currently spans"`
}
// ListRequest builds the ListNetworks request
func (network Network) ListRequest() (ListCommand, error) {
//TODO add tags support
req := &ListNetworks{
Account: network.Account,
DomainID: network.DomainID,
ID: network.ID,
PhysicalNetworkID: network.PhysicalNetworkID,
TrafficType: network.TrafficType,
Type: network.Type,
ZoneID: network.ZoneID,
}
if network.CanUseForDeploy {
req.CanUseForDeploy = &network.CanUseForDeploy
}
if network.RestartRequired {
req.RestartRequired = &network.RestartRequired
}
return req, nil
}
// ResourceType returns the type of the resource
func (Network) ResourceType() string {
return "Network"
}
// Service is a feature of a network
type Service struct {
Capability []ServiceCapability `json:"capability,omitempty"`
Name string `json:"name"`
Provider []ServiceProvider `json:"provider,omitempty"`
}
// ServiceCapability represents optional capability of a service
type ServiceCapability struct {
CanChooseServiceCapability bool `json:"canchooseservicecapability"`
Name string `json:"name"`
Value string `json:"value"`
}
// ServiceProvider represents the provider of the service
type ServiceProvider struct {
CanEnableIndividualService bool `json:"canenableindividualservice"`
DestinationPhysicalNetworkID string `json:"destinationphysicalnetworkid"`
ID string `json:"id"`
Name string `json:"name"`
PhysicalNetworkID string `json:"physicalnetworkid"`
ServiceList []string `json:"servicelist,omitempty"`
}
// CreateNetwork creates a network
type CreateNetwork struct {
Account string `json:"account,omitempty" doc:"account who will own the network"`
DisplayNetwork *bool `json:"displaynetwork,omitempty" doc:"an optional field, whether to the display the network to the end user or not."`
DisplayText string `json:"displaytext,omitempty" doc:"the display text of the network"` // This field is required but might be empty
DomainID string `json:"domainid,omitempty" doc:"domain ID of the account owning a network"`
EndIP net.IP `json:"endip,omitempty" doc:"the ending IP address in the network IP range. If not specified, will be defaulted to startIP"`
EndIpv6 net.IP `json:"endipv6,omitempty" doc:"the ending IPv6 address in the IPv6 network range"`
Gateway net.IP `json:"gateway,omitempty" doc:"the gateway of the network. Required for Shared networks and Isolated networks when it belongs to VPC"`
IP6CIDR *CIDR `json:"ip6cidr,omitempty" doc:"the CIDR of IPv6 network, must be at least /64"`
IP6Gateway net.IP `json:"ip6gateway,omitempty" doc:"the gateway of the IPv6 network. Required for Shared networks and Isolated networks when it belongs to VPC"`
IsolatedPVlan string `json:"isolatedpvlan,omitempty" doc:"the isolated private vlan for this network"`
Name string `json:"name,omitempty" doc:"the name of the network"` // This field is required but might be empty
Netmask net.IP `json:"netmask,omitempty" doc:"the netmask of the network. Required for Shared networks and Isolated networks when it belongs to VPC"`
NetworkDomain string `json:"networkdomain,omitempty" doc:"network domain"`
NetworkOfferingID string `json:"networkofferingid" doc:"the network offering id"`
PhysicalNetworkID string `json:"physicalnetworkid,omitempty" doc:"the Physical Network ID the network belongs to"`
StartIP net.IP `json:"startip,omitempty" doc:"the beginning IP address in the network IP range"`
StartIpv6 net.IP `json:"startipv6,omitempty" doc:"the beginning IPv6 address in the IPv6 network range"`
SubdomainAccess *bool `json:"subdomainaccess,omitempty" doc:"Defines whether to allow subdomains to use networks dedicated to their parent domain(s). Should be used with aclType=Domain, defaulted to allow.subdomain.network.access global config if not specified"`
Vlan string `json:"vlan,omitempty" doc:"the ID or VID of the network"`
ZoneID string `json:"zoneid" doc:"the Zone ID for the network"`
_ bool `name:"createNetwork" description:"Creates a network"`
}
func (CreateNetwork) response() interface{} {
return new(Network)
}
func (req CreateNetwork) onBeforeSend(params url.Values) error {
// Those fields are required but might be empty
if req.Name == "" {
params.Set("name", "")
}
if req.DisplayText == "" {
params.Set("displaytext", "")
}
return nil
}
// UpdateNetwork (Async) updates a network
type UpdateNetwork struct {
ID string `json:"id" doc:"the ID of the network"`
ChangeCidr *bool `json:"changecidr,omitempty" doc:"Force update even if cidr type is different"`
CustomID string `json:"customid,omitempty" doc:"an optional field, in case you want to set a custom id to the resource. Allowed to Root Admins only"`
DisplayNetwork *bool `json:"displaynetwork,omitempty" doc:"an optional field, whether to the display the network to the end user or not."`
DisplayText string `json:"displaytext,omitempty" doc:"the new display text for the network"`
GuestVMCidr string `json:"guestvmcidr,omitempty" doc:"CIDR for Guest VMs,Cloudstack allocates IPs to Guest VMs only from this CIDR"`
Name string `json:"name,omitempty" doc:"the new name for the network"`
NetworkDomain string `json:"networkdomain,omitempty" doc:"network domain"`
NetworkOfferingID string `json:"networkofferingid,omitempty" doc:"network offering ID"`
_ bool `name:"updateNetwork" description:"Updates a network"`
}
func (UpdateNetwork) response() interface{} {
return new(AsyncJobResult)
}
func (UpdateNetwork) asyncResponse() interface{} {
return new(Network)
}
// RestartNetwork (Async) updates a network
type RestartNetwork struct {
ID string `json:"id" doc:"The id of the network to restart."`
Cleanup *bool `json:"cleanup,omitempty" doc:"If cleanup old network elements"`
_ bool `name:"restartNetwork" description:"Restarts the network; includes 1) restarting network elements - virtual routers, dhcp servers 2) reapplying all public ips 3) reapplying loadBalancing/portForwarding rules"`
}
func (RestartNetwork) response() interface{} {
return new(AsyncJobResult)
}
func (RestartNetwork) asyncResponse() interface{} {
return new(Network)
}
// DeleteNetwork deletes a network
type DeleteNetwork struct {
ID string `json:"id" doc:"the ID of the network"`
Forced *bool `json:"forced,omitempty" doc:"Force delete a network. Network will be marked as 'Destroy' even when commands to shutdown and cleanup to the backend fails."`
_ bool `name:"deleteNetwork" description:"Deletes a network"`
}
func (DeleteNetwork) response() interface{} {
return new(AsyncJobResult)
}
func (DeleteNetwork) asyncResponse() interface{} {
return new(booleanResponse)
}
// ListNetworks represents a query to a network
type ListNetworks struct {
Account string `json:"account,omitempty" doc:"list resources by account. Must be used with the domainId parameter."`
CanUseForDeploy *bool `json:"canusefordeploy,omitempty" doc:"list networks available for vm deployment"`
DisplayNetwork *bool `json:"displaynetwork,omitempty" doc:"list resources by display flag; only ROOT admin is eligible to pass this parameter"`
DomainID string `json:"domainid,omitempty" doc:"list only resources belonging to the domain specified"`
ID string `json:"id,omitempty" doc:"list networks by id"`
IsRecursive *bool `json:"isrecursive,omitempty" doc:"defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves."`
IsSystem *bool `json:"issystem,omitempty" doc:"true if network is system, false otherwise"`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
ListAll *bool `json:"listall,omitempty" doc:"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
PhysicalNetworkID string `json:"physicalnetworkid,omitempty" doc:"list networks by physical network id"`
RestartRequired *bool `json:"restartrequired,omitempty" doc:"list networks by restartRequired"`
SpecifyIPRanges *bool `json:"specifyipranges,omitempty" doc:"true if need to list only networks which support specifying ip ranges"`
SupportedServices []Service `json:"supportedservices,omitempty" doc:"list networks supporting certain services"`
Tags []ResourceTag `json:"tags,omitempty" doc:"List resources by tags (key/value pairs)"`
TrafficType string `json:"traffictype,omitempty" doc:"type of the traffic"`
Type string `json:"type,omitempty" doc:"the type of the network. Supported values are: Isolated and Shared"`
ZoneID string `json:"zoneid,omitempty" doc:"the Zone ID of the network"`
_ bool `name:"listNetworks" description:"Lists all available networks."`
}
// ListNetworksResponse represents the list of networks
type ListNetworksResponse struct {
Count int `json:"count"`
Network []Network `json:"network"`
}
func (ListNetworks) response() interface{} {
return new(ListNetworksResponse)
}
// SetPage sets the current page
func (listNetwork *ListNetworks) SetPage(page int) {
listNetwork.Page = page
}
// SetPageSize sets the page size
func (listNetwork *ListNetworks) SetPageSize(pageSize int) {
listNetwork.PageSize = pageSize
}
func (ListNetworks) each(resp interface{}, callback IterateItemFunc) {
networks, ok := resp.(*ListNetworksResponse)
if !ok {
callback(nil, fmt.Errorf("type error: ListNetworksResponse expected, got %T", resp))
return
}
for i := range networks.Network {
if !callback(&networks.Network[i], nil) {
break
}
}
}

141
vendor/github.com/exoscale/egoscale/nics.go generated vendored Normal file
View file

@ -0,0 +1,141 @@
package egoscale
import (
"errors"
"net"
)
// Nic represents a Network Interface Controller (NIC)
//
// See: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/latest/networking_and_traffic.html#configuring-multiple-ip-addresses-on-a-single-nic
type Nic struct {
BroadcastURI string `json:"broadcasturi,omitempty" doc:"the broadcast uri of the nic"`
DeviceID string `json:"deviceid,omitempty" doc:"device id for the network when plugged into the virtual machine"`
Gateway net.IP `json:"gateway,omitempty" doc:"the gateway of the nic"`
ID string `json:"id,omitempty" doc:"the ID of the nic"`
IP6Address net.IP `json:"ip6address,omitempty" doc:"the IPv6 address of network"`
IP6CIDR *CIDR `json:"ip6cidr,omitempty" doc:"the cidr of IPv6 network"`
IP6Gateway net.IP `json:"ip6gateway,omitempty" doc:"the gateway of IPv6 network"`
IPAddress net.IP `json:"ipaddress,omitempty" doc:"the ip address of the nic"`
IsDefault bool `json:"isdefault,omitempty" doc:"true if nic is default, false otherwise"`
IsolationURI string `json:"isolationuri,omitempty" doc:"the isolation uri of the nic"`
MACAddress MACAddress `json:"macaddress,omitempty" doc:"true if nic is default, false otherwise"`
Netmask net.IP `json:"netmask,omitempty" doc:"the netmask of the nic"`
NetworkID string `json:"networkid,omitempty" doc:"the ID of the corresponding network"`
NetworkName string `json:"networkname,omitempty" doc:"the name of the corresponding network"`
ReverseDNS []ReverseDNS `json:"reversedns,omitempty" doc:"the list of PTR record(s) associated with the virtual machine"`
SecondaryIP []NicSecondaryIP `json:"secondaryip,omitempty" doc:"the Secondary ipv4 addr of nic"`
TrafficType string `json:"traffictype,omitempty" doc:"the traffic type of the nic"`
Type string `json:"type,omitempty" doc:"the type of the nic"`
VirtualMachineID string `json:"virtualmachineid,omitempty" doc:"Id of the vm to which the nic belongs"`
}
// ListRequest build a ListNics request from the given Nic
func (nic Nic) ListRequest() (ListCommand, error) {
if nic.VirtualMachineID == "" {
return nil, errors.New("command ListNics requires the VirtualMachineID field to be set")
}
req := &ListNics{
VirtualMachineID: nic.VirtualMachineID,
NicID: nic.ID,
NetworkID: nic.NetworkID,
}
return req, nil
}
// NicSecondaryIP represents a link between NicID and IPAddress
type NicSecondaryIP struct {
ID string `json:"id,omitempty" doc:"the ID of the secondary private IP addr"`
IPAddress net.IP `json:"ipaddress,omitempty" doc:"Secondary IP address"`
NetworkID string `json:"networkid,omitempty" doc:"the ID of the network"`
NicID string `json:"nicid,omitempty" doc:"the ID of the nic"`
VirtualMachineID string `json:"virtualmachineid,omitempty" doc:"the ID of the vm"`
}
// ListNics represents the NIC search
type ListNics struct {
ForDisplay bool `json:"fordisplay,omitempty" doc:"list resources by display flag; only ROOT admin is eligible to pass this parameter"`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
NetworkID string `json:"networkid,omitempty" doc:"list nic of the specific vm's network"`
NicID string `json:"nicid,omitempty" doc:"the ID of the nic to to list IPs"`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
VirtualMachineID string `json:"virtualmachineid" doc:"the ID of the vm"`
_ bool `name:"listNics" description:"list the vm nics IP to NIC"`
}
// ListNicsResponse represents a list of templates
type ListNicsResponse struct {
Count int `json:"count"`
Nic []Nic `json:"nic"`
}
func (ListNics) response() interface{} {
return new(ListNicsResponse)
}
// SetPage sets the current page
func (ls *ListNics) SetPage(page int) {
ls.Page = page
}
// SetPageSize sets the page size
func (ls *ListNics) SetPageSize(pageSize int) {
ls.PageSize = pageSize
}
func (ListNics) each(resp interface{}, callback IterateItemFunc) {
nics := resp.(*ListNicsResponse)
for i := range nics.Nic {
if !callback(&(nics.Nic[i]), nil) {
break
}
}
}
// AddIPToNic (Async) represents the assignation of a secondary IP
type AddIPToNic struct {
NicID string `json:"nicid" doc:"the ID of the nic to which you want to assign private IP"`
IPAddress net.IP `json:"ipaddress,omitempty" doc:"Secondary IP Address"`
_ bool `name:"addIpToNic" description:"Assigns secondary IP to NIC"`
}
func (AddIPToNic) response() interface{} {
return new(AsyncJobResult)
}
func (AddIPToNic) asyncResponse() interface{} {
return new(NicSecondaryIP)
}
// RemoveIPFromNic (Async) represents a deletion request
type RemoveIPFromNic struct {
ID string `json:"id" doc:"the ID of the secondary ip address to nic"`
_ bool `name:"removeIpFromNic" description:"Removes secondary IP from the NIC."`
}
func (RemoveIPFromNic) response() interface{} {
return new(AsyncJobResult)
}
func (RemoveIPFromNic) asyncResponse() interface{} {
return new(booleanResponse)
}
// ActivateIP6 (Async) activates the IP6 on the given NIC
//
// Exoscale specific API: https://community.exoscale.ch/api/compute/#activateip6_GET
type ActivateIP6 struct {
NicID string `json:"nicid" doc:"the ID of the nic to which you want to assign the IPv6"`
_ bool `name:"activateIp6" description:"Activate the IPv6 on the VM's nic"`
}
func (ActivateIP6) response() interface{} {
return new(AsyncJobResult)
}
func (ActivateIP6) asyncResponse() interface{} {
return new(Nic)
}

16
vendor/github.com/exoscale/egoscale/record_string.go generated vendored Normal file
View file

@ -0,0 +1,16 @@
// Code generated by "stringer -type=Record"; DO NOT EDIT.
package egoscale
import "strconv"
const _Record_name = "AAAAAALIASCNAMEHINFOMXNAPTRNSPOOLSPFSRVSSHFPTXTURL"
var _Record_index = [...]uint8{0, 1, 5, 10, 15, 20, 22, 27, 29, 33, 36, 39, 44, 47, 50}
func (i Record) String() string {
if i < 0 || i >= Record(len(_Record_index)-1) {
return "Record(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _Record_name[_Record_index[i]:_Record_index[i+1]]
}

377
vendor/github.com/exoscale/egoscale/request.go generated vendored Normal file
View file

@ -0,0 +1,377 @@
package egoscale
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"time"
)
// Error formats a CloudStack error into a standard error
func (e ErrorResponse) Error() string {
return fmt.Sprintf("API error %s %d (%s %d): %s", e.ErrorCode, e.ErrorCode, e.CSErrorCode, e.CSErrorCode, e.ErrorText)
}
// Error formats a CloudStack job response into a standard error
func (e booleanResponse) Error() error {
if !e.Success {
return fmt.Errorf("API error: %s", e.DisplayText)
}
return nil
}
func (client *Client) parseResponse(resp *http.Response, key string) (json.RawMessage, error) {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
m := map[string]json.RawMessage{}
if err := json.Unmarshal(b, &m); err != nil {
return nil, err
}
response, ok := m[key]
if !ok {
if resp.StatusCode >= 400 {
response, ok = m["errorresponse"]
}
if !ok {
for k := range m {
return nil, fmt.Errorf("malformed JSON response, %q was expected, got %q", key, k)
}
}
}
if resp.StatusCode >= 400 {
errorResponse := new(ErrorResponse)
if e := json.Unmarshal(response, errorResponse); e != nil && errorResponse.ErrorCode <= 0 {
return nil, fmt.Errorf("%d %s", resp.StatusCode, b)
}
return nil, errorResponse
}
n := map[string]json.RawMessage{}
if err := json.Unmarshal(response, &n); err != nil {
return nil, err
}
if len(n) > 1 {
return response, nil
}
if len(n) == 1 {
for k := range n {
// boolean response and asyncjob result may also contain
// only one key
if k == "success" || k == "jobid" {
return response, nil
}
return n[k], nil
}
}
return response, nil
}
// asyncRequest perform an asynchronous job with a context
func (client *Client) asyncRequest(ctx context.Context, asyncCommand AsyncCommand) (interface{}, error) {
var err error
resp := asyncCommand.asyncResponse()
client.AsyncRequestWithContext(
ctx,
asyncCommand,
func(j *AsyncJobResult, e error) bool {
if e != nil {
err = e
return false
}
if j.JobStatus == Success {
if r := j.Result(resp); r != nil {
err = r
}
return false
}
return true
},
)
return resp, err
}
// SyncRequestWithContext performs a sync request with a context
func (client *Client) SyncRequestWithContext(ctx context.Context, command Command) (interface{}, error) {
body, err := client.request(ctx, command)
if err != nil {
return nil, err
}
response := command.response()
b, ok := response.(*booleanResponse)
if ok {
m := make(map[string]interface{})
if errUnmarshal := json.Unmarshal(body, &m); errUnmarshal != nil {
return nil, errUnmarshal
}
b.DisplayText, _ = m["displaytext"].(string)
if success, okSuccess := m["success"].(string); okSuccess {
b.Success = success == "true"
}
if success, okSuccess := m["success"].(bool); okSuccess {
b.Success = success
}
return b, nil
}
if err := json.Unmarshal(body, response); err != nil {
errResponse := new(ErrorResponse)
if e := json.Unmarshal(body, errResponse); e == nil && errResponse.ErrorCode > 0 {
return errResponse, nil
}
return nil, err
}
return response, nil
}
// BooleanRequest performs the given boolean command
func (client *Client) BooleanRequest(command Command) error {
resp, err := client.Request(command)
if err != nil {
return err
}
if b, ok := resp.(*booleanResponse); ok {
return b.Error()
}
panic(fmt.Errorf("command %q is not a proper boolean response. %#v", client.APIName(command), resp))
}
// BooleanRequestWithContext performs the given boolean command
func (client *Client) BooleanRequestWithContext(ctx context.Context, command Command) error {
resp, err := client.RequestWithContext(ctx, command)
if err != nil {
return err
}
if b, ok := resp.(*booleanResponse); ok {
return b.Error()
}
panic(fmt.Errorf("command %q is not a proper boolean response. %#v", client.APIName(command), resp))
}
// Request performs the given command
func (client *Client) Request(command Command) (interface{}, error) {
ctx, cancel := context.WithTimeout(context.Background(), client.Timeout)
defer cancel()
return client.RequestWithContext(ctx, command)
}
// RequestWithContext preforms a command with a context
func (client *Client) RequestWithContext(ctx context.Context, command Command) (interface{}, error) {
switch command.(type) {
case AsyncCommand:
return client.asyncRequest(ctx, command.(AsyncCommand))
default:
return client.SyncRequestWithContext(ctx, command)
}
}
// SyncRequest performs the command as is
func (client *Client) SyncRequest(command Command) (interface{}, error) {
ctx, cancel := context.WithTimeout(context.Background(), client.Timeout)
defer cancel()
return client.SyncRequestWithContext(ctx, command)
}
// AsyncRequest performs the given command
func (client *Client) AsyncRequest(asyncCommand AsyncCommand, callback WaitAsyncJobResultFunc) {
ctx, cancel := context.WithTimeout(context.Background(), client.Timeout)
defer cancel()
client.AsyncRequestWithContext(ctx, asyncCommand, callback)
}
// AsyncRequestWithContext preforms a request with a context
func (client *Client) AsyncRequestWithContext(ctx context.Context, asyncCommand AsyncCommand, callback WaitAsyncJobResultFunc) {
result, err := client.SyncRequestWithContext(ctx, asyncCommand)
if err != nil {
if !callback(nil, err) {
return
}
}
jobResult, ok := result.(*AsyncJobResult)
if !ok {
callback(nil, fmt.Errorf("wrong type, AsyncJobResult was expected instead of %T", result))
}
// Successful response
if jobResult.JobID == "" || jobResult.JobStatus != Pending {
callback(jobResult, nil)
// without a JobID, the next requests will only fail
return
}
for iteration := 0; ; iteration++ {
time.Sleep(client.RetryStrategy(int64(iteration)))
req := &QueryAsyncJobResult{JobID: jobResult.JobID}
resp, err := client.SyncRequestWithContext(ctx, req)
if err != nil && !callback(nil, err) {
return
}
result, ok := resp.(*AsyncJobResult)
if !ok {
if !callback(nil, fmt.Errorf("wrong type. AsyncJobResult expected, got %T", resp)) {
return
}
}
if result.JobStatus == Failure {
if !callback(nil, result.Error()) {
return
}
} else {
if !callback(result, nil) {
return
}
}
}
}
// Payload builds the HTTP request from the given command
func (client *Client) Payload(command Command) (string, error) {
params := url.Values{}
err := prepareValues("", params, command)
if err != nil {
return "", err
}
if hookReq, ok := command.(onBeforeHook); ok {
if err := hookReq.onBeforeSend(params); err != nil {
return "", err
}
}
params.Set("apikey", client.APIKey)
params.Set("command", client.APIName(command))
params.Set("response", "json")
// This code is borrowed from net/url/url.go
// The way it's encoded by net/url doesn't match
// how CloudStack work.
var buf bytes.Buffer
keys := make([]string, 0, len(params))
for k := range params {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
prefix := csEncode(k) + "="
for _, v := range params[k] {
if buf.Len() > 0 {
buf.WriteByte('&')
}
buf.WriteString(prefix)
buf.WriteString(csEncode(v))
}
}
return buf.String(), nil
}
// Sign signs the HTTP request and return it
func (client *Client) Sign(query string) (string, error) {
mac := hmac.New(sha1.New, []byte(client.apiSecret))
_, err := mac.Write([]byte(strings.ToLower(query)))
if err != nil {
return "", err
}
signature := csEncode(base64.StdEncoding.EncodeToString(mac.Sum(nil)))
return fmt.Sprintf("%s&signature=%s", csQuotePlus(query), signature), nil
}
// request makes a Request while being close to the metal
func (client *Client) request(ctx context.Context, command Command) (json.RawMessage, error) {
payload, err := client.Payload(command)
if err != nil {
return nil, err
}
query, err := client.Sign(payload)
if err != nil {
return nil, err
}
method := "GET"
url := fmt.Sprintf("%s?%s", client.Endpoint, query)
var body io.Reader
// respect Internet Explorer limit of 2048
if len(url) > 2048 {
url = client.Endpoint
method = "POST"
body = strings.NewReader(query)
}
request, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
request = request.WithContext(ctx)
request.Header.Add("User-Agent", fmt.Sprintf("exoscale/egoscale (%v)", Version))
if method == "POST" {
request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
request.Header.Add("Content-Length", strconv.Itoa(len(query)))
}
resp, err := client.HTTPClient.Do(request)
if err != nil {
return nil, err
}
defer resp.Body.Close() // nolint: errcheck
contentType := resp.Header.Get("content-type")
if !strings.Contains(contentType, "application/json") {
return nil, fmt.Errorf(`body content-type response expected "application/json", got %q`, contentType)
}
apiName := client.APIName(command)
key := fmt.Sprintf("%sresponse", strings.ToLower(apiName))
// XXX: addIpToNic, activateIp6 are kind of special
if key == "addiptonicresponse" {
key = "addiptovmnicresponse"
} else if key == "activateip6response" {
key = "activateip6nicresponse"
}
text, err := client.parseResponse(resp, key)
if err != nil {
return nil, err
}
return text, nil
}

184
vendor/github.com/exoscale/egoscale/request_type.go generated vendored Normal file
View file

@ -0,0 +1,184 @@
package egoscale
import (
"net/url"
)
// Command represents a CloudStack request
type Command interface {
response() interface{}
}
// AsyncCommand represents a async CloudStack request
type AsyncCommand interface {
Command
// Response interface to Unmarshal the JSON into
asyncResponse() interface{}
}
// ListCommand represents a CloudStack list request
type ListCommand interface {
Command
// SetPage defines the current pages
SetPage(int)
// SetPageSize defines the size of the page
SetPageSize(int)
// each reads the data from the response and feeds channels, and returns true if we are on the last page
each(interface{}, IterateItemFunc)
}
// onBeforeHook represents an action to be done on the params before sending them
//
// This little took helps with issue of relying on JSON serialization logic only.
// `omitempty` may make sense in some cases but not all the time.
type onBeforeHook interface {
onBeforeSend(params url.Values) error
}
// CommandInfo represents the meta data related to a Command
type CommandInfo struct {
Name string
Description string
RootOnly bool
}
// JobStatusType represents the status of a Job
type JobStatusType int
//go:generate stringer -type JobStatusType
const (
// Pending represents a job in progress
Pending JobStatusType = iota
// Success represents a successfully completed job
Success
// Failure represents a job that has failed to complete
Failure
)
// ErrorCode represents the CloudStack ApiErrorCode enum
//
// See: https://github.com/apache/cloudstack/blob/master/api/src/org/apache/cloudstack/api/ApiErrorCode.java
type ErrorCode int
//go:generate stringer -type ErrorCode
const (
// Unauthorized represents ... (TODO)
Unauthorized ErrorCode = 401
// MethodNotAllowed represents ... (TODO)
MethodNotAllowed ErrorCode = 405
// UnsupportedActionError represents ... (TODO)
UnsupportedActionError ErrorCode = 422
// APILimitExceeded represents ... (TODO)
APILimitExceeded ErrorCode = 429
// MalformedParameterError represents ... (TODO)
MalformedParameterError ErrorCode = 430
// ParamError represents ... (TODO)
ParamError ErrorCode = 431
// InternalError represents a server error
InternalError ErrorCode = 530
// AccountError represents ... (TODO)
AccountError ErrorCode = 531
// AccountResourceLimitError represents ... (TODO)
AccountResourceLimitError ErrorCode = 532
// InsufficientCapacityError represents ... (TODO)
InsufficientCapacityError ErrorCode = 533
// ResourceUnavailableError represents ... (TODO)
ResourceUnavailableError ErrorCode = 534
// ResourceAllocationError represents ... (TODO)
ResourceAllocationError ErrorCode = 535
// ResourceInUseError represents ... (TODO)
ResourceInUseError ErrorCode = 536
// NetworkRuleConflictError represents ... (TODO)
NetworkRuleConflictError ErrorCode = 537
)
// CSErrorCode represents the CloudStack CSExceptionErrorCode enum
//
// See: https://github.com/apache/cloudstack/blob/master/utils/src/main/java/com/cloud/utils/exception/CSExceptionErrorCode.java
type CSErrorCode int
//go:generate stringer -type CSErrorCode
const (
// CloudRuntimeException ... (TODO)
CloudRuntimeException CSErrorCode = 4250
// ExecutionException ... (TODO)
ExecutionException CSErrorCode = 4260
// HypervisorVersionChangedException ... (TODO)
HypervisorVersionChangedException CSErrorCode = 4265
// CloudException ... (TODO)
CloudException CSErrorCode = 4275
// AccountLimitException ... (TODO)
AccountLimitException CSErrorCode = 4280
// AgentUnavailableException ... (TODO)
AgentUnavailableException CSErrorCode = 4285
// CloudAuthenticationException ... (TODO)
CloudAuthenticationException CSErrorCode = 4290
// ConcurrentOperationException ... (TODO)
ConcurrentOperationException CSErrorCode = 4300
// ConflictingNetworksException ... (TODO)
ConflictingNetworkSettingsException CSErrorCode = 4305
// DiscoveredWithErrorException ... (TODO)
DiscoveredWithErrorException CSErrorCode = 4310
// HAStateException ... (TODO)
HAStateException CSErrorCode = 4315
// InsufficientAddressCapacityException ... (TODO)
InsufficientAddressCapacityException CSErrorCode = 4320
// InsufficientCapacityException ... (TODO)
InsufficientCapacityException CSErrorCode = 4325
// InsufficientNetworkCapacityException ... (TODO)
InsufficientNetworkCapacityException CSErrorCode = 4330
// InsufficientServerCapaticyException ... (TODO)
InsufficientServerCapacityException CSErrorCode = 4335
// InsufficientStorageCapacityException ... (TODO)
InsufficientStorageCapacityException CSErrorCode = 4340
// InternalErrorException ... (TODO)
InternalErrorException CSErrorCode = 4345
// InvalidParameterValueException ... (TODO)
InvalidParameterValueException CSErrorCode = 4350
// ManagementServerException ... (TODO)
ManagementServerException CSErrorCode = 4355
// NetworkRuleConflictException ... (TODO)
NetworkRuleConflictException CSErrorCode = 4360
// PermissionDeniedException ... (TODO)
PermissionDeniedException CSErrorCode = 4365
// ResourceAllocationException ... (TODO)
ResourceAllocationException CSErrorCode = 4370
// ResourceInUseException ... (TODO)
ResourceInUseException CSErrorCode = 4375
// ResourceUnavailableException ... (TODO)
ResourceUnavailableException CSErrorCode = 4380
// StorageUnavailableException ... (TODO)
StorageUnavailableException CSErrorCode = 4385
// UnsupportedServiceException ... (TODO)
UnsupportedServiceException CSErrorCode = 4390
// VirtualMachineMigrationException ... (TODO)
VirtualMachineMigrationException CSErrorCode = 4395
// AsyncCommandQueued ... (TODO)
AsyncCommandQueued CSErrorCode = 4540
// RequestLimitException ... (TODO)
RequestLimitException CSErrorCode = 4545
// ServerAPIException ... (TODO)
ServerAPIException CSErrorCode = 9999
)
// ErrorResponse represents the standard error response from CloudStack
type ErrorResponse struct {
CSErrorCode CSErrorCode `json:"cserrorcode"`
ErrorCode ErrorCode `json:"errorcode"`
ErrorText string `json:"errortext"`
UUIDList []UUIDItem `json:"uuidList,omitempty"` // uuid*L*ist is not a typo
}
// UUIDItem represents an item of the UUIDList part of an ErrorResponse
type UUIDItem struct {
Description string `json:"description,omitempty"`
SerialVersionUID int64 `json:"serialVersionUID,omitempty"`
UUID string `json:"uuid"`
}
// booleanResponse represents a boolean response (usually after a deletion)
type booleanResponse struct {
DisplayText string `json:"displaytext,omitempty"`
Success bool `json:"success"`
}

View file

@ -0,0 +1,36 @@
package egoscale
// ListResourceDetails lists the resource tag(s) (but different from listTags...)
type ListResourceDetails struct {
ResourceType string `json:"resourcetype" doc:"list by resource type"`
Account string `json:"account,omitempty" doc:"list resources by account. Must be used with the domainId parameter."`
DomainID string `json:"domainid,omitempty" doc:"list only resources belonging to the domain specified"`
ForDisplay bool `json:"fordisplay,omitempty" doc:"if set to true, only details marked with display=true, are returned. False by default"`
Key string `json:"key,omitempty" doc:"list by key"`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
ListAll bool `json:"listall,omitempty" doc:"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
ResourceID string `json:"resourceid,omitempty" doc:"list by resource id"`
Value string `json:"value,omitempty" doc:"list by key, value. Needs to be passed only along with key"`
IsRecursive bool `json:"isrecursive,omitempty" doc:"defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves."`
_ bool `name:"listResourceDetails" description:"List resource detail(s)"`
}
// ListResourceDetailsResponse represents a list of resource details
type ListResourceDetailsResponse struct {
Count int `json:"count"`
ResourceDetail []ResourceTag `json:"resourcedetail"`
}
func (*ListResourceDetails) name() string {
return "listResourceDetails"
}
func (*ListResourceDetails) description() string {
return "List resource detail(s)"
}
func (*ListResourceDetails) response() interface{} {
return new(ListResourceDetailsResponse)
}

View file

@ -0,0 +1,16 @@
// Code generated by "stringer -type=ResourceType"; DO NOT EDIT.
package egoscale
import "strconv"
const _ResourceType_name = "VirtualMachineTypeIPAddressTypeVolumeTypeSnapshotTypeTemplateTypeProjectTypeNetworkTypeVPCTypeCPUTypeMemoryTypePrimaryStorageTypeSecondaryStorageType"
var _ResourceType_index = [...]uint8{0, 18, 31, 41, 53, 65, 76, 87, 94, 101, 111, 129, 149}
func (i ResourceType) String() string {
if i < 0 || i >= ResourceType(len(_ResourceType_index)-1) {
return "ResourceType(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _ResourceType_name[_ResourceType_index[i]:_ResourceType_index[i+1]]
}

77
vendor/github.com/exoscale/egoscale/reversedns.go generated vendored Normal file
View file

@ -0,0 +1,77 @@
package egoscale
import (
"net"
)
// ReverseDNS represents the PTR record linked with an IPAddress or IP6Address belonging to a Virtual Machine or a Public IP Address (Elastic IP) instance
type ReverseDNS struct {
DomainName string `json:"domainname,omitempty" doc:"the domain name of the PTR record"`
IP6Address net.IP `json:"ip6address,omitempty" doc:"the IPv6 address linked with the PTR record (mutually exclusive with ipaddress)"`
IPAddress net.IP `json:"ipaddress,omitempty" doc:"the IPv4 address linked with the PTR record (mutually exclusive with ip6address)"`
NicID string `json:"nicid,omitempty" doc:"the virtual machine default NIC ID"`
PublicIPID string `json:"publicipid,omitempty" doc:"the public IP address ID"`
VirtualMachineID string `json:"virtualmachineid,omitempty" doc:"the virtual machine ID"`
}
// DeleteReverseDNSFromPublicIPAddress is a command to create/delete the PTR record of a public IP address
type DeleteReverseDNSFromPublicIPAddress struct {
ID string `json:"id,omitempty" doc:"the ID of the public IP address"`
_ bool `name:"deleteReverseDnsFromPublicIpAddress" description:"delete the PTR DNS record from the public IP address"`
}
func (*DeleteReverseDNSFromPublicIPAddress) response() interface{} {
return new(booleanResponse)
}
// DeleteReverseDNSFromVirtualMachine is a command to create/delete the PTR record(s) of a virtual machine
type DeleteReverseDNSFromVirtualMachine struct {
ID string `json:"id,omitempty" doc:"the ID of the virtual machine"`
_ bool `name:"deleteReverseDnsFromVirtualMachine" description:"Delete the PTR DNS record(s) from the virtual machine"`
}
func (*DeleteReverseDNSFromVirtualMachine) response() interface{} {
return new(booleanResponse)
}
// QueryReverseDNSForPublicIPAddress is a command to create/query the PTR record of a public IP address
type QueryReverseDNSForPublicIPAddress struct {
ID string `json:"id,omitempty" doc:"the ID of the public IP address"`
_ bool `name:"queryReverseDnsForPublicIpAddress" description:"Query the PTR DNS record for the public IP address"`
}
func (*QueryReverseDNSForPublicIPAddress) response() interface{} {
return new(IPAddress)
}
// QueryReverseDNSForVirtualMachine is a command to create/query the PTR record(s) of a virtual machine
type QueryReverseDNSForVirtualMachine struct {
ID string `json:"id,omitempty" doc:"the ID of the virtual machine"`
_ bool `name:"queryReverseDnsForVirtualMachine" description:"Query the PTR DNS record(s) for the virtual machine"`
}
func (*QueryReverseDNSForVirtualMachine) response() interface{} {
return new(VirtualMachine)
}
// UpdateReverseDNSForPublicIPAddress is a command to create/update the PTR record of a public IP address
type UpdateReverseDNSForPublicIPAddress struct {
DomainName string `json:"domainname,omitempty" doc:"the domain name for the PTR record. It must have a valid TLD"`
ID string `json:"id,omitempty" doc:"the ID of the public IP address"`
_ bool `name:"updateReverseDnsForPublicIpAddress" description:"Update/create the PTR DNS record for the public IP address"`
}
func (*UpdateReverseDNSForPublicIPAddress) response() interface{} {
return new(IPAddress)
}
// UpdateReverseDNSForVirtualMachine is a command to create/update the PTR record(s) of a virtual machine
type UpdateReverseDNSForVirtualMachine struct {
DomainName string `json:"domainname,omitempty" doc:"the domain name for the PTR record(s). It must have a valid TLD"`
ID string `json:"id,omitempty" doc:"the ID of the virtual machine"`
_ bool `name:"updateReverseDnsForVirtualMachine" description:"Update/create the PTR DNS record(s) for the virtual machine"`
}
func (*UpdateReverseDNSForVirtualMachine) response() interface{} {
return new(VirtualMachine)
}

272
vendor/github.com/exoscale/egoscale/security_groups.go generated vendored Normal file
View file

@ -0,0 +1,272 @@
package egoscale
import (
"context"
"fmt"
"net/url"
"strconv"
"strings"
)
// SecurityGroup represent a firewalling set of rules
type SecurityGroup struct {
Account string `json:"account,omitempty" doc:"the account owning the security group"`
Description string `json:"description,omitempty" doc:"the description of the security group"`
Domain string `json:"domain,omitempty" doc:"the domain name of the security group"`
DomainID string `json:"domainid,omitempty" doc:"the domain ID of the security group"`
EgressRule []EgressRule `json:"egressrule,omitempty" doc:"the list of egress rules associated with the security group"`
ID string `json:"id,omitempty" doc:"the ID of the security group"`
IngressRule []IngressRule `json:"ingressrule,omitempty" doc:"the list of ingress rules associated with the security group"`
Name string `json:"name,omitempty" doc:"the name of the security group"`
Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with the rule"`
}
// ResourceType returns the type of the resource
func (SecurityGroup) ResourceType() string {
return "SecurityGroup"
}
// UserSecurityGroup converts a SecurityGroup to a UserSecurityGroup
func (sg SecurityGroup) UserSecurityGroup() UserSecurityGroup {
return UserSecurityGroup{
Account: sg.Account,
Group: sg.Name,
}
}
// ListRequest builds the ListSecurityGroups request
func (sg SecurityGroup) ListRequest() (ListCommand, error) {
//TODO add tags
req := &ListSecurityGroups{
Account: sg.Account,
DomainID: sg.DomainID,
ID: sg.ID,
SecurityGroupName: sg.Name,
}
return req, nil
}
// Delete deletes the given Security Group
func (sg SecurityGroup) Delete(ctx context.Context, client *Client) error {
if sg.ID == "" && sg.Name == "" {
return fmt.Errorf("a SecurityGroup may only be deleted using ID or Name")
}
req := &DeleteSecurityGroup{
Account: sg.Account,
DomainID: sg.DomainID,
}
if sg.ID != "" {
req.ID = sg.ID
} else {
req.Name = sg.Name
}
return client.BooleanRequestWithContext(ctx, req)
}
// RuleByID returns IngressRule or EgressRule by a rule ID
func (sg SecurityGroup) RuleByID(ruleID string) (*IngressRule, *EgressRule) {
for i, in := range sg.IngressRule {
if ruleID == in.RuleID {
return &sg.IngressRule[i], nil
}
}
for i, out := range sg.EgressRule {
if ruleID == out.RuleID {
return nil, &sg.EgressRule[i]
}
}
return nil, nil
}
// IngressRule represents the ingress rule
type IngressRule struct {
Account string `json:"account,omitempty" doc:"account owning the security group rule"`
CIDR *CIDR `json:"cidr,omitempty" doc:"the CIDR notation for the base IP address of the security group rule"`
Description string `json:"description,omitempty" doc:"description of the security group rule"`
EndPort uint16 `json:"endport,omitempty" doc:"the ending port of the security group rule "`
IcmpCode uint8 `json:"icmpcode,omitempty" doc:"the code for the ICMP message response"`
IcmpType uint8 `json:"icmptype,omitempty" doc:"the type of the ICMP message response"`
Protocol string `json:"protocol,omitempty" doc:"the protocol of the security group rule"`
RuleID string `json:"ruleid,omitempty" doc:"the id of the security group rule"`
SecurityGroupID string `json:"securitygroupid,omitempty"`
SecurityGroupName string `json:"securitygroupname,omitempty" doc:"security group name"`
StartPort uint16 `json:"startport,omitempty" doc:"the starting port of the security group rule"`
Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with the rule"`
UserSecurityGroupList []UserSecurityGroup `json:"usersecuritygrouplist,omitempty"`
}
// EgressRule represents the ingress rule
type EgressRule IngressRule
// UserSecurityGroup represents the traffic of another security group
type UserSecurityGroup struct {
Group string `json:"group,omitempty"`
Account string `json:"account,omitempty"`
}
// String gives the UserSecurityGroup name
func (usg UserSecurityGroup) String() string {
return usg.Group
}
// CreateSecurityGroup represents a security group creation
type CreateSecurityGroup struct {
Name string `json:"name" doc:"name of the security group"`
Account string `json:"account,omitempty" doc:"an optional account for the security group. Must be used with domainId."`
Description string `json:"description,omitempty" doc:"the description of the security group"`
DomainID string `json:"domainid,omitempty" doc:"an optional domainId for the security group. If the account parameter is used, domainId must also be used."`
_ bool `name:"createSecurityGroup" description:"Creates a security group"`
}
func (CreateSecurityGroup) response() interface{} {
return new(SecurityGroup)
}
// DeleteSecurityGroup represents a security group deletion
type DeleteSecurityGroup struct {
Account string `json:"account,omitempty" doc:"the account of the security group. Must be specified with domain ID"`
DomainID string `json:"domainid,omitempty" doc:"the domain ID of account owning the security group"`
ID string `json:"id,omitempty" doc:"The ID of the security group. Mutually exclusive with name parameter"`
Name string `json:"name,omitempty" doc:"The ID of the security group. Mutually exclusive with id parameter"`
_ bool `name:"deleteSecurityGroup" description:"Deletes security group"`
}
func (DeleteSecurityGroup) response() interface{} {
return new(booleanResponse)
}
// AuthorizeSecurityGroupIngress (Async) represents the ingress rule creation
type AuthorizeSecurityGroupIngress struct {
Account string `json:"account,omitempty" doc:"an optional account for the security group. Must be used with domainId."`
CIDRList []CIDR `json:"cidrlist,omitempty" doc:"the cidr list associated"`
Description string `json:"description,omitempty" doc:"the description of the ingress/egress rule"`
DomainID string `json:"domainid,omitempty" doc:"an optional domainid for the security group. If the account parameter is used, domainid must also be used."`
EndPort uint16 `json:"endport,omitempty" doc:"end port for this ingress rule"`
IcmpCode uint8 `json:"icmpcode,omitempty" doc:"error code for this icmp message"`
IcmpType uint8 `json:"icmptype,omitempty" doc:"type of the icmp message being sent"`
Protocol string `json:"protocol,omitempty" doc:"TCP is default. UDP, ICMP, ICMPv6, AH, ESP, GRE are the other supported protocols"`
SecurityGroupID string `json:"securitygroupid,omitempty" doc:"The ID of the security group. Mutually exclusive with securitygroupname parameter"`
SecurityGroupName string `json:"securitygroupname,omitempty" doc:"The name of the security group. Mutually exclusive with securitygroupid parameter"`
StartPort uint16 `json:"startport,omitempty" doc:"start port for this ingress rule"`
UserSecurityGroupList []UserSecurityGroup `json:"usersecuritygrouplist,omitempty" doc:"user to security group mapping"`
_ bool `name:"authorizeSecurityGroupIngress" description:"Authorizes a particular ingress/egress rule for this security group"`
}
func (AuthorizeSecurityGroupIngress) response() interface{} {
return new(AsyncJobResult)
}
func (AuthorizeSecurityGroupIngress) asyncResponse() interface{} {
return new(SecurityGroup)
}
func (req AuthorizeSecurityGroupIngress) onBeforeSend(params url.Values) error {
// ICMP code and type may be zero but can also be omitted...
if strings.HasPrefix(strings.ToLower(req.Protocol), "icmp") {
params.Set("icmpcode", strconv.FormatInt(int64(req.IcmpCode), 10))
params.Set("icmptype", strconv.FormatInt(int64(req.IcmpType), 10))
}
// StartPort may be zero but can also be omitted...
if req.EndPort != 0 && req.StartPort == 0 {
params.Set("startport", "0")
}
return nil
}
// AuthorizeSecurityGroupEgress (Async) represents the egress rule creation
type AuthorizeSecurityGroupEgress AuthorizeSecurityGroupIngress
func (AuthorizeSecurityGroupEgress) response() interface{} {
return new(AsyncJobResult)
}
func (AuthorizeSecurityGroupEgress) asyncResponse() interface{} {
return new(SecurityGroup)
}
func (req AuthorizeSecurityGroupEgress) onBeforeSend(params url.Values) error {
return (AuthorizeSecurityGroupIngress)(req).onBeforeSend(params)
}
// RevokeSecurityGroupIngress (Async) represents the ingress/egress rule deletion
type RevokeSecurityGroupIngress struct {
ID string `json:"id" doc:"The ID of the ingress rule"`
_ bool `name:"revokeSecurityGroupIngress" description:"Deletes a particular ingress rule from this security group"`
}
func (RevokeSecurityGroupIngress) response() interface{} {
return new(AsyncJobResult)
}
func (RevokeSecurityGroupIngress) asyncResponse() interface{} {
return new(booleanResponse)
}
// RevokeSecurityGroupEgress (Async) represents the ingress/egress rule deletion
type RevokeSecurityGroupEgress struct {
ID string `json:"id" doc:"The ID of the egress rule"`
_ bool `name:"revokeSecurityGroupEgress" description:"Deletes a particular egress rule from this security group"`
}
func (RevokeSecurityGroupEgress) response() interface{} {
return new(AsyncJobResult)
}
func (RevokeSecurityGroupEgress) asyncResponse() interface{} {
return new(booleanResponse)
}
// ListSecurityGroups represents a search for security groups
type ListSecurityGroups struct {
Account string `json:"account,omitempty" doc:"list resources by account. Must be used with the domainId parameter."`
DomainID string `json:"domainid,omitempty" doc:"list only resources belonging to the domain specified"`
ID string `json:"id,omitempty" doc:"list the security group by the id provided"`
IsRecursive *bool `json:"isrecursive,omitempty" doc:"defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves."`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
ListAll *bool `json:"listall,omitempty" doc:"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
SecurityGroupName string `json:"securitygroupname,omitempty" doc:"lists security groups by name"`
Tags []ResourceTag `json:"tags,omitempty" doc:"List resources by tags (key/value pairs)"`
VirtualMachineID string `json:"virtualmachineid,omitempty" doc:"lists security groups by virtual machine id"`
_ bool `name:"listSecurityGroups" description:"Lists security groups"`
}
// ListSecurityGroupsResponse represents a list of security groups
type ListSecurityGroupsResponse struct {
Count int `json:"count"`
SecurityGroup []SecurityGroup `json:"securitygroup"`
}
func (ListSecurityGroups) response() interface{} {
return new(ListSecurityGroupsResponse)
}
// SetPage sets the current page
func (lsg *ListSecurityGroups) SetPage(page int) {
lsg.Page = page
}
// SetPageSize sets the page size
func (lsg *ListSecurityGroups) SetPageSize(pageSize int) {
lsg.PageSize = pageSize
}
func (ListSecurityGroups) each(resp interface{}, callback IterateItemFunc) {
sgs, ok := resp.(*ListSecurityGroupsResponse)
if !ok {
callback(nil, fmt.Errorf("wrong type. ListSecurityGroupsResponse expected, got %T", resp))
return
}
for i := range sgs.SecurityGroup {
if !callback(&sgs.SecurityGroup[i], nil) {
break
}
}
}

332
vendor/github.com/exoscale/egoscale/serialization.go generated vendored Normal file
View file

@ -0,0 +1,332 @@
package egoscale
import (
"encoding/base64"
"fmt"
"log"
"net"
"net/url"
"reflect"
"strconv"
"strings"
)
func csQuotePlus(s string) string {
s = strings.Replace(s, "+", "%20", -1)
s = strings.Replace(s, "%5B", "[", -1)
s = strings.Replace(s, "%5D", "]", -1)
return s
}
func csEncode(s string) string {
return csQuotePlus(url.QueryEscape(s))
}
// info returns the meta info of a command
//
// command is not a Command so it's easier to Test
func info(command interface{}) (*CommandInfo, error) {
typeof := reflect.TypeOf(command)
// Going up the pointer chain to find the underlying struct
for typeof.Kind() == reflect.Ptr {
typeof = typeof.Elem()
}
field, ok := typeof.FieldByName("_")
if !ok {
return nil, fmt.Errorf(`missing meta ("_") field in %#v`, command)
}
name, nameOk := field.Tag.Lookup("name")
description, _ := field.Tag.Lookup("description")
if !nameOk {
return nil, fmt.Errorf(`missing "name" key in the tag string of %#v`, command)
}
info := &CommandInfo{
Name: name,
Description: description,
}
return info, nil
}
// prepareValues uses a command to build a POST request
//
// command is not a Command so it's easier to Test
func prepareValues(prefix string, params url.Values, command interface{}) error {
value := reflect.ValueOf(command)
typeof := reflect.TypeOf(command)
// Going up the pointer chain to find the underlying struct
for typeof.Kind() == reflect.Ptr {
typeof = typeof.Elem()
value = value.Elem()
}
// Checking for nil commands
if !value.IsValid() {
return fmt.Errorf("cannot serialize the invalid value %#v", command)
}
for i := 0; i < typeof.NumField(); i++ {
field := typeof.Field(i)
if field.Name == "_" {
continue
}
val := value.Field(i)
tag := field.Tag
if json, ok := tag.Lookup("json"); ok {
n, required := ExtractJSONTag(field.Name, json)
name := prefix + n
switch val.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
v := val.Int()
if v == 0 {
if required {
return fmt.Errorf("%s.%s (%v) is required, got 0", typeof.Name(), n, val.Kind())
}
} else {
params.Set(name, strconv.FormatInt(v, 10))
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
v := val.Uint()
if v == 0 {
if required {
return fmt.Errorf("%s.%s (%v) is required, got 0", typeof.Name(), n, val.Kind())
}
} else {
params.Set(name, strconv.FormatUint(v, 10))
}
case reflect.Float32, reflect.Float64:
v := val.Float()
if v == 0 {
if required {
return fmt.Errorf("%s.%s (%v) is required, got 0", typeof.Name(), n, val.Kind())
}
} else {
params.Set(name, strconv.FormatFloat(v, 'f', -1, 64))
}
case reflect.String:
v := val.String()
if v == "" {
if required {
return fmt.Errorf("%s.%s (%v) is required, got \"\"", typeof.Name(), n, val.Kind())
}
} else {
params.Set(name, v)
}
case reflect.Bool:
v := val.Bool()
if !v {
if required {
params.Set(name, "false")
}
} else {
params.Set(name, "true")
}
case reflect.Ptr:
if val.IsNil() {
if required {
return fmt.Errorf("%s.%s (%v) is required, got tempty ptr", typeof.Name(), n, val.Kind())
}
} else {
switch field.Type.Elem().Kind() {
case reflect.Bool:
params.Set(name, strconv.FormatBool(val.Elem().Bool()))
case reflect.Struct:
i := val.Interface()
s, ok := i.(fmt.Stringer)
if !ok {
return fmt.Errorf("%s.%s (%v) is not a Stringer", typeof.Name(), field.Name, val.Kind())
}
if s != nil && s.String() == "" {
if required {
return fmt.Errorf("%s.%s (%v) is required, got empty value", typeof.Name(), field.Name, val.Kind())
}
} else {
params.Set(n, s.String())
}
default:
log.Printf("[SKIP] %s.%s (%v) not supported", typeof.Name(), n, field.Type.Elem().Kind())
}
}
case reflect.Slice:
switch field.Type.Elem().Kind() {
case reflect.Uint8:
switch field.Type {
case reflect.TypeOf(net.IPv4zero):
ip := (net.IP)(val.Bytes())
if ip == nil || ip.Equal(net.IPv4zero) {
if required {
return fmt.Errorf("%s.%s (%v) is required, got zero IPv4 address", typeof.Name(), n, val.Kind())
}
} else {
params.Set(name, ip.String())
}
case reflect.TypeOf(MAC48(0, 0, 0, 0, 0, 0)):
mac := val.Interface().(MACAddress)
s := mac.String()
if s == "" {
if required {
return fmt.Errorf("%s.%s (%v) is required, got empty MAC address", typeof.Name(), field.Name, val.Kind())
}
} else {
params.Set(name, s)
}
default:
if val.Len() == 0 {
if required {
return fmt.Errorf("%s.%s (%v) is required, got empty slice", typeof.Name(), n, val.Kind())
}
} else {
v := val.Bytes()
params.Set(name, base64.StdEncoding.EncodeToString(v))
}
}
case reflect.String:
{
if val.Len() == 0 {
if required {
return fmt.Errorf("%s.%s (%v) is required, got empty slice", typeof.Name(), n, val.Kind())
}
} else {
elems := make([]string, 0, val.Len())
for i := 0; i < val.Len(); i++ {
// XXX what if the value contains a comma? Double encode?
s := val.Index(i).String()
elems = append(elems, s)
}
params.Set(name, strings.Join(elems, ","))
}
}
default:
switch field.Type.Elem() {
case reflect.TypeOf(CIDR{}):
if val.Len() == 0 {
if required {
return fmt.Errorf("%s.%s (%v) is required, got empty slice", typeof.Name(), n, val.Kind())
}
} else {
value := reflect.ValueOf(val.Interface())
ss := make([]string, val.Len())
for i := 0; i < value.Len(); i++ {
v := value.Index(i).Interface()
s, ok := v.(fmt.Stringer)
if !ok {
return fmt.Errorf("not a String, %T", v)
}
ss[i] = s.String()
}
params.Set(name, strings.Join(ss, ","))
}
default:
if val.Len() == 0 {
if required {
return fmt.Errorf("%s.%s (%v) is required, got empty slice", typeof.Name(), n, val.Kind())
}
} else {
err := prepareList(name, params, val.Interface())
if err != nil {
return err
}
}
}
}
case reflect.Map:
if val.Len() == 0 {
if required {
return fmt.Errorf("%s.%s (%v) is required, got empty map", typeof.Name(), field.Name, val.Kind())
}
} else {
err := prepareMap(name, params, val.Interface())
if err != nil {
return err
}
}
case reflect.Struct:
i := val.Interface()
s, ok := i.(fmt.Stringer)
if !ok {
return fmt.Errorf("%s.%s (%v) is not a Stringer", typeof.Name(), field.Name, val.Kind())
}
if s != nil && s.String() == "" {
if required {
return fmt.Errorf("%s.%s (%v) is required, got empty value", typeof.Name(), field.Name, val.Kind())
}
} else {
params.Set(n, s.String())
}
default:
if required {
return fmt.Errorf("unsupported type %s.%s (%v)", typeof.Name(), n, val.Kind())
}
fmt.Printf("%s\n", val.Kind())
}
} else {
log.Printf("[SKIP] %s.%s no json label found", typeof.Name(), field.Name)
}
}
return nil
}
func prepareList(prefix string, params url.Values, slice interface{}) error {
value := reflect.ValueOf(slice)
for i := 0; i < value.Len(); i++ {
err := prepareValues(fmt.Sprintf("%s[%d].", prefix, i), params, value.Index(i).Interface())
if err != nil {
return err
}
}
return nil
}
func prepareMap(prefix string, params url.Values, m interface{}) error {
value := reflect.ValueOf(m)
for i, key := range value.MapKeys() {
var keyName string
var keyValue string
switch key.Kind() {
case reflect.String:
keyName = key.String()
default:
return fmt.Errorf("only map[string]string are supported (XXX)")
}
val := value.MapIndex(key)
switch val.Kind() {
case reflect.String:
keyValue = val.String()
default:
return fmt.Errorf("only map[string]string are supported (XXX)")
}
params.Set(fmt.Sprintf("%s[%d].%s", prefix, i, keyName), keyValue)
}
return nil
}
// ExtractJSONTag returns the variable name or defaultName as well as if the field is required (!omitempty)
func ExtractJSONTag(defaultName, jsonTag string) (string, bool) {
tags := strings.Split(jsonTag, ",")
name := tags[0]
required := true
for _, tag := range tags {
if tag == "omitempty" {
required = false
}
}
if name == "" || name == "omitempty" {
name = defaultName
}
return name, required
}

View file

@ -0,0 +1,112 @@
package egoscale
import (
"fmt"
)
// ServiceOffering corresponds to the Compute Offerings
//
// A service offering correspond to some hardware features (CPU, RAM).
//
// See: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/latest/service_offerings.html
type ServiceOffering struct {
Authorized bool `json:"authorized,omitempty" doc:"is the account/domain authorized to use this service offering"`
CPUNumber int `json:"cpunumber,omitempty" doc:"the number of CPU"`
CPUSpeed int `json:"cpuspeed,omitempty" doc:"the clock rate CPU speed in Mhz"`
Created string `json:"created,omitempty" doc:"the date this service offering was created"`
DefaultUse bool `json:"defaultuse,omitempty" doc:"is this a default system vm offering"`
DeploymentPlanner string `json:"deploymentplanner,omitempty" doc:"deployment strategy used to deploy VM."`
DiskBytesReadRate int64 `json:"diskBytesReadRate,omitempty" doc:"bytes read rate of the service offering"`
DiskBytesWriteRate int64 `json:"diskBytesWriteRate,omitempty" doc:"bytes write rate of the service offering"`
DiskIopsReadRate int64 `json:"diskIopsReadRate,omitempty" doc:"io requests read rate of the service offering"`
DiskIopsWriteRate int64 `json:"diskIopsWriteRate,omitempty" doc:"io requests write rate of the service offering"`
Displaytext string `json:"displaytext,omitempty" doc:"an alternate display text of the service offering."`
Domain string `json:"domain,omitempty" doc:"Domain name for the offering"`
DomainID string `json:"domainid,omitempty" doc:"the domain id of the service offering"`
HostTags string `json:"hosttags,omitempty" doc:"the host tag for the service offering"`
HypervisorSnapshotReserve int `json:"hypervisorsnapshotreserve,omitempty" doc:"Hypervisor snapshot reserve space as a percent of a volume (for managed storage using Xen or VMware)"`
ID string `json:"id,omitempty" doc:"the id of the service offering"`
IsCustomized bool `json:"iscustomized,omitempty" doc:"is true if the offering is customized"`
IsCustomizedIops bool `json:"iscustomizediops,omitempty" doc:"true if disk offering uses custom iops, false otherwise"`
IsSystem bool `json:"issystem,omitempty" doc:"is this a system vm offering"`
IsVolatile bool `json:"isvolatile,omitempty" doc:"true if the vm needs to be volatile, i.e., on every reboot of vm from API root disk is discarded and creates a new root disk"`
LimitCPUUse bool `json:"limitcpuuse,omitempty" doc:"restrict the CPU usage to committed service offering"`
MaxIops int64 `json:"maxiops,omitempty" doc:"the max iops of the disk offering"`
Memory int `json:"memory,omitempty" doc:"the memory in MB"`
MinIops int64 `json:"miniops,omitempty" doc:"the min iops of the disk offering"`
Name string `json:"name,omitempty" doc:"the name of the service offering"`
NetworkRate int `json:"networkrate,omitempty" doc:"data transfer rate in megabits per second allowed."`
OfferHA bool `json:"offerha,omitempty" doc:"the ha support in the service offering"`
Restricted bool `json:"restricted,omitempty" doc:"is this offering restricted"`
ServiceOfferingDetails map[string]string `json:"serviceofferingdetails,omitempty" doc:"additional key/value details tied with this service offering"`
StorageType string `json:"storagetype,omitempty" doc:"the storage type for this service offering"`
SystemVMType string `json:"systemvmtype,omitempty" doc:"is this a the systemvm type for system vm offering"`
Tags string `json:"tags,omitempty" doc:"the tags for the service offering"`
}
// ListRequest builds the ListSecurityGroups request
func (so ServiceOffering) ListRequest() (ListCommand, error) {
// Restricted cannot be applied here because it really has three states
req := &ListServiceOfferings{
ID: so.ID,
DomainID: so.DomainID,
IsSystem: &so.IsSystem,
Name: so.Name,
SystemVMType: so.SystemVMType,
}
if so.IsSystem {
req.IsSystem = &so.IsSystem
}
return req, nil
}
// ListServiceOfferings represents a query for service offerings
type ListServiceOfferings struct {
DomainID string `json:"domainid,omitempty" doc:"the ID of the domain associated with the service offering"`
ID string `json:"id,omitempty" doc:"ID of the service offering"`
IsSystem *bool `json:"issystem,omitempty" doc:"is this a system vm offering"`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
Name string `json:"name,omitempty" doc:"name of the service offering"`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
Restricted *bool `json:"restricted,omitempty" doc:"filter by the restriction flag: true to list only the restricted service offerings, false to list non-restricted service offerings, or nothing for all."`
SystemVMType string `json:"systemvmtype,omitempty" doc:"the system VM type. Possible types are \"consoleproxy\", \"secondarystoragevm\" or \"domainrouter\"."`
VirtualMachineID string `json:"virtualmachineid,omitempty" doc:"the ID of the virtual machine. Pass this in if you want to see the available service offering that a virtual machine can be changed to."`
_ bool `name:"listServiceOfferings" description:"Lists all available service offerings."`
}
// ListServiceOfferingsResponse represents a list of service offerings
type ListServiceOfferingsResponse struct {
Count int `json:"count"`
ServiceOffering []ServiceOffering `json:"serviceoffering"`
}
func (ListServiceOfferings) response() interface{} {
return new(ListServiceOfferingsResponse)
}
// SetPage sets the current page
func (lso *ListServiceOfferings) SetPage(page int) {
lso.Page = page
}
// SetPageSize sets the page size
func (lso *ListServiceOfferings) SetPageSize(pageSize int) {
lso.PageSize = pageSize
}
func (ListServiceOfferings) each(resp interface{}, callback IterateItemFunc) {
sos, ok := resp.(*ListServiceOfferingsResponse)
if !ok {
callback(nil, fmt.Errorf("wrong type. ListServiceOfferingsResponse expected, got %T", resp))
return
}
for i := range sos.ServiceOffering {
if !callback(&sos.ServiceOffering[i], nil) {
break
}
}
}

129
vendor/github.com/exoscale/egoscale/snapshots.go generated vendored Normal file
View file

@ -0,0 +1,129 @@
package egoscale
// SnapshotState represents the Snapshot.State enum
//
// See: https://github.com/apache/cloudstack/blob/master/api/src/main/java/com/cloud/storage/Snapshot.java
type SnapshotState int
//go:generate stringer -type SnapshotState
const (
// Allocated ... (TODO)
Allocated SnapshotState = iota
// Creating ... (TODO)
Creating
// CreatedOnPrimary ... (TODO)
CreatedOnPrimary
// BackingUp ... (TODO)
BackingUp
// BackedUp ... (TODO)
BackedUp
// Copying ... (TODO)
Copying
// Destroying ... (TODO)
Destroying
// Destroyed ... (TODO)
Destroyed
// Error ... (TODO)
Error
)
// Snapshot represents a volume snapshot
type Snapshot struct {
Account string `json:"account,omitempty" doc:"the account associated with the snapshot"`
AccountID string `json:"accountid,omitempty" doc:"the account ID associated with the snapshot"`
Created string `json:"created,omitempty" doc:"the date the snapshot was created"`
Domain string `json:"domain,omitempty" doc:"the domain name of the snapshot's account"`
DomainID string `json:"domainid,omitempty" doc:"the domain ID of the snapshot's account"`
ID string `json:"id,omitempty" doc:"ID of the snapshot"`
IntervalType string `json:"intervaltype,omitempty" doc:"valid types are hourly, daily, weekly, monthy, template, and none."`
Name string `json:"name,omitempty" doc:"name of the snapshot"`
PhysicalSize int64 `json:"physicalsize,omitempty" doc:"physical size of the snapshot on image store"`
Revertable *bool `json:"revertable,omitempty" doc:"indicates whether the underlying storage supports reverting the volume to this snapshot"`
Size int64 `json:"size,omitempty" doc:"the size of original volume"`
SnapshotType string `json:"snapshottype,omitempty" doc:"the type of the snapshot"`
State SnapshotState `json:"state,omitempty" doc:"the state of the snapshot. BackedUp means that snapshot is ready to be used; Creating - the snapshot is being allocated on the primary storage; BackingUp - the snapshot is being backed up on secondary storage"`
Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with snapshot"`
VolumeID string `json:"volumeid,omitempty" doc:"ID of the disk volume"`
VolumeName string `json:"volumename,omitempty" doc:"name of the disk volume"`
VolumeType string `json:"volumetype,omitempty" doc:"type of the disk volume"`
ZoneID string `json:"zoneid,omitempty" doc:"id of the availability zone"`
}
// ResourceType returns the type of the resource
func (Snapshot) ResourceType() string {
return "Snapshot"
}
// CreateSnapshot (Async) creates an instant snapshot of a volume
type CreateSnapshot struct {
VolumeID string `json:"volumeid" doc:"The ID of the disk volume"`
Account string `json:"account,omitempty" doc:"The account of the snapshot. The account parameter must be used with the domainId parameter."`
DomainID string `json:"domainid,omitempty" doc:"The domain ID of the snapshot. If used with the account parameter, specifies a domain for the account associated with the disk volume."`
QuiesceVM *bool `json:"quiescevm,omitempty" doc:"quiesce vm if true"`
_ bool `name:"createSnapshot" description:"Creates an instant snapshot of a volume."`
}
func (CreateSnapshot) response() interface{} {
return new(AsyncJobResult)
}
func (CreateSnapshot) asyncResponse() interface{} {
return new(Snapshot)
}
// ListSnapshots lists the volume snapshots
type ListSnapshots struct {
Account string `json:"account,omitempty" doc:"list resources by account. Must be used with the domainId parameter."`
DomainID string `json:"domainid,omitempty" doc:"list only resources belonging to the domain specified"`
ID string `json:"id,omitempty" doc:"lists snapshot by snapshot ID"`
IntervalType string `json:"intervaltype,omitempty" doc:"valid values are HOURLY, DAILY, WEEKLY, and MONTHLY."`
IsRecursive *bool `json:"isrecursive,omitempty" doc:"defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves."`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
ListAll *bool `json:"listall,omitempty" doc:"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"`
Name string `json:"name,omitempty" doc:"lists snapshot by snapshot name"`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
SnapshotType string `json:"snapshottype,omitempty" doc:"valid values are MANUAL or RECURRING."`
Tags []ResourceTag `json:"tags,omitempty" doc:"List resources by tags (key/value pairs)"`
VolumeID string `json:"volumeid,omitempty" doc:"the ID of the disk volume"`
ZoneID string `json:"zoneid,omitempty" doc:"list snapshots by zone id"`
_ bool `name:"listSnapshots" description:"Lists all available snapshots for the account."`
}
// ListSnapshotsResponse represents a list of volume snapshots
type ListSnapshotsResponse struct {
Count int `json:"count"`
Snapshot []Snapshot `json:"snapshot"`
}
func (ListSnapshots) response() interface{} {
return new(ListSnapshotsResponse)
}
// DeleteSnapshot (Async) deletes a snapshot of a disk volume
type DeleteSnapshot struct {
ID string `json:"id" doc:"The ID of the snapshot"`
_ bool `name:"deleteSnapshot" description:"Deletes a snapshot of a disk volume."`
}
func (DeleteSnapshot) response() interface{} {
return new(AsyncJobResult)
}
func (DeleteSnapshot) asyncResponse() interface{} {
return new(booleanResponse)
}
// RevertSnapshot (Async) reverts a volume snapshot
type RevertSnapshot struct {
ID string `json:"id" doc:"The ID of the snapshot"`
_ bool `name:"revertSnapshot" description:"revert a volume snapshot."`
}
func (RevertSnapshot) response() interface{} {
return new(AsyncJobResult)
}
func (RevertSnapshot) asyncResponse() interface{} {
return new(booleanResponse)
}

View file

@ -0,0 +1,16 @@
// Code generated by "stringer -type SnapshotState"; DO NOT EDIT.
package egoscale
import "strconv"
const _SnapshotState_name = "AllocatedCreatingCreatedOnPrimaryBackingUpBackedUpCopyingDestroyingDestroyedError"
var _SnapshotState_index = [...]uint8{0, 9, 17, 33, 42, 50, 57, 67, 76, 81}
func (i SnapshotState) String() string {
if i < 0 || i >= SnapshotState(len(_SnapshotState_index)-1) {
return "SnapshotState(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _SnapshotState_name[_SnapshotState_index[i]:_SnapshotState_index[i+1]]
}

144
vendor/github.com/exoscale/egoscale/ssh_keypairs.go generated vendored Normal file
View file

@ -0,0 +1,144 @@
package egoscale
import (
"context"
"fmt"
)
// SSHKeyPair represents an SSH key pair
//
// See: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/stable/virtual_machines.html#creating-the-ssh-keypair
type SSHKeyPair struct {
Account string `json:"account,omitempty"` // must be used with a Domain ID
DomainID string `json:"domainid,omitempty"`
Fingerprint string `json:"fingerprint,omitempty"`
Name string `json:"name,omitempty"`
PrivateKey string `json:"privatekey,omitempty"`
}
// Delete removes the given SSH key, by Name
func (ssh SSHKeyPair) Delete(ctx context.Context, client *Client) error {
if ssh.Name == "" {
return fmt.Errorf("an SSH Key Pair may only be deleted using Name")
}
return client.BooleanRequestWithContext(ctx, &DeleteSSHKeyPair{
Name: ssh.Name,
Account: ssh.Account,
DomainID: ssh.DomainID,
})
}
// ListRequest builds the ListSSHKeyPairs request
func (ssh SSHKeyPair) ListRequest() (ListCommand, error) {
req := &ListSSHKeyPairs{
Account: ssh.Account,
DomainID: ssh.DomainID,
Fingerprint: ssh.Fingerprint,
Name: ssh.Name,
}
return req, nil
}
// CreateSSHKeyPair represents a new keypair to be created
type CreateSSHKeyPair struct {
Name string `json:"name" doc:"Name of the keypair"`
Account string `json:"account,omitempty" doc:"an optional account for the ssh key. Must be used with domainId."`
DomainID string `json:"domainid,omitempty" doc:"an optional domainId for the ssh key. If the account parameter is used, domainId must also be used."`
_ bool `name:"createSSHKeyPair" description:"Create a new keypair and returns the private key"`
}
func (CreateSSHKeyPair) response() interface{} {
return new(SSHKeyPair)
}
// DeleteSSHKeyPair represents a new keypair to be created
type DeleteSSHKeyPair struct {
Name string `json:"name" doc:"Name of the keypair"`
Account string `json:"account,omitempty" doc:"the account associated with the keypair. Must be used with the domainId parameter."`
DomainID string `json:"domainid,omitempty" doc:"the domain ID associated with the keypair"`
_ bool `name:"deleteSSHKeyPair" description:"Deletes a keypair by name"`
}
func (DeleteSSHKeyPair) response() interface{} {
return new(booleanResponse)
}
// RegisterSSHKeyPair represents a new registration of a public key in a keypair
type RegisterSSHKeyPair struct {
Name string `json:"name" doc:"Name of the keypair"`
PublicKey string `json:"publickey" doc:"Public key material of the keypair"`
Account string `json:"account,omitempty" doc:"an optional account for the ssh key. Must be used with domainId."`
DomainID string `json:"domainid,omitempty" doc:"an optional domainId for the ssh key. If the account parameter is used, domainId must also be used."`
_ bool `name:"registerSSHKeyPair" description:"Register a public key in a keypair under a certain name"`
}
func (RegisterSSHKeyPair) response() interface{} {
return new(SSHKeyPair)
}
// ListSSHKeyPairs represents a query for a list of SSH KeyPairs
type ListSSHKeyPairs struct {
Account string `json:"account,omitempty" doc:"list resources by account. Must be used with the domainId parameter."`
DomainID string `json:"domainid,omitempty" doc:"list only resources belonging to the domain specified"`
Fingerprint string `json:"fingerprint,omitempty" doc:"A public key fingerprint to look for"`
IsRecursive *bool `json:"isrecursive,omitempty" doc:"defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves."`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
ListAll *bool `json:"listall,omitempty" doc:"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"`
Name string `json:"name,omitempty" doc:"A key pair name to look for"`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
_ bool `name:"listSSHKeyPairs" description:"List registered keypairs"`
}
// ListSSHKeyPairsResponse represents a list of SSH key pairs
type ListSSHKeyPairsResponse struct {
Count int `json:"count"`
SSHKeyPair []SSHKeyPair `json:"sshkeypair"`
}
func (ListSSHKeyPairs) response() interface{} {
return new(ListSSHKeyPairsResponse)
}
// SetPage sets the current page
func (ls *ListSSHKeyPairs) SetPage(page int) {
ls.Page = page
}
// SetPageSize sets the page size
func (ls *ListSSHKeyPairs) SetPageSize(pageSize int) {
ls.PageSize = pageSize
}
func (ListSSHKeyPairs) each(resp interface{}, callback IterateItemFunc) {
sshs, ok := resp.(*ListSSHKeyPairsResponse)
if !ok {
callback(nil, fmt.Errorf("wrong type. ListSSHKeyPairsResponse expected, got %T", resp))
return
}
for i := range sshs.SSHKeyPair {
if !callback(&sshs.SSHKeyPair[i], nil) {
break
}
}
}
// ResetSSHKeyForVirtualMachine (Async) represents a change for the key pairs
type ResetSSHKeyForVirtualMachine struct {
ID string `json:"id" doc:"The ID of the virtual machine"`
KeyPair string `json:"keypair" doc:"name of the ssh key pair used to login to the virtual machine"`
Account string `json:"account,omitempty" doc:"an optional account for the ssh key. Must be used with domainId."`
DomainID string `json:"domainid,omitempty" doc:"an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used."`
_ bool `name:"resetSSHKeyForVirtualMachine" description:"Resets the SSH Key for virtual machine. The virtual machine must be in a \"Stopped\" state."`
}
func (ResetSSHKeyForVirtualMachine) response() interface{} {
return new(AsyncJobResult)
}
func (ResetSSHKeyForVirtualMachine) asyncResponse() interface{} {
return new(VirtualMachine)
}

75
vendor/github.com/exoscale/egoscale/tags.go generated vendored Normal file
View file

@ -0,0 +1,75 @@
package egoscale
// ResourceTag is a tag associated with a resource
//
// http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/4.9/management.html
type ResourceTag struct {
Account string `json:"account,omitempty" doc:"the account associated with the tag"`
Customer string `json:"customer,omitempty" doc:"customer associated with the tag"`
Domain string `json:"domain,omitempty" doc:"the domain associated with the tag"`
DomainID string `json:"domainid,omitempty" doc:"the ID of the domain associated with the tag"`
Key string `json:"key,omitempty" doc:"tag key name"`
ResourceID string `json:"resourceid,omitempty" doc:"id of the resource"`
ResourceType string `json:"resourcetype,omitempty" doc:"resource type"`
Value string `json:"value,omitempty" doc:"tag value"`
}
// CreateTags (Async) creates resource tag(s)
type CreateTags struct {
ResourceIDs []string `json:"resourceids" doc:"list of resources to create the tags for"`
ResourceType string `json:"resourcetype" doc:"type of the resource"`
Tags []ResourceTag `json:"tags" doc:"Map of tags (key/value pairs)"`
Customer string `json:"customer,omitempty" doc:"identifies client specific tag. When the value is not null, the tag can't be used by cloudStack code internally"`
_ bool `name:"createTags" description:"Creates resource tag(s)"`
}
func (CreateTags) response() interface{} {
return new(AsyncJobResult)
}
func (CreateTags) asyncResponse() interface{} {
return new(booleanResponse)
}
// DeleteTags (Async) deletes the resource tag(s)
type DeleteTags struct {
ResourceIDs []string `json:"resourceids" doc:"Delete tags for resource id(s)"`
ResourceType string `json:"resourcetype" doc:"Delete tag by resource type"`
Tags []ResourceTag `json:"tags,omitempty" doc:"Delete tags matching key/value pairs"`
_ bool `name:"deleteTags" description:"Deleting resource tag(s)"`
}
func (DeleteTags) response() interface{} {
return new(AsyncJobResult)
}
func (DeleteTags) asyncResponse() interface{} {
return new(booleanResponse)
}
// ListTags list resource tag(s)
type ListTags struct {
Account string `json:"account,omitempty" doc:"list resources by account. Must be used with the domainId parameter."`
Customer string `json:"customer,omitempty" doc:"list by customer name"`
DomainID string `json:"domainid,omitempty" doc:"list only resources belonging to the domain specified"`
IsRecursive *bool `json:"isrecursive,omitempty" doc:"defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves."`
Key string `json:"key,omitempty" doc:"list by key"`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
ListAll *bool `json:"listall,omitempty" doc:"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
ResourceID string `json:"resourceid,omitempty" doc:"list by resource id"`
ResourceType string `json:"resourcetype,omitempty" doc:"list by resource type"`
Value string `json:"value,omitempty" doc:"list by value"`
_ bool `name:"listTags" description:"List resource tag(s)"`
}
// ListTagsResponse represents a list of resource tags
type ListTagsResponse struct {
Count int `json:"count"`
Tag []ResourceTag `json:"tag"`
}
func (ListTags) response() interface{} {
return new(ListTagsResponse)
}

255
vendor/github.com/exoscale/egoscale/templates.go generated vendored Normal file
View file

@ -0,0 +1,255 @@
package egoscale
import (
"fmt"
)
// Template represents a machine to be deployed
//
// See: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/latest/templates.html
type Template struct {
Account string `json:"account,omitempty" doc:"the account name to which the template belongs"`
AccountID string `json:"accountid,omitempty" doc:"the account id to which the template belongs"`
Bootable bool `json:"bootable,omitempty" doc:"true if the ISO is bootable, false otherwise"`
Checksum string `json:"checksum,omitempty" doc:"checksum of the template"`
Created string `json:"created,omitempty" doc:"the date this template was created"`
CrossZones bool `json:"crossZones,omitempty" doc:"true if the template is managed across all Zones, false otherwise"`
Details map[string]string `json:"details,omitempty" doc:"additional key/value details tied with template"`
DisplayText string `json:"displaytext,omitempty" doc:"the template display text"`
Domain string `json:"domain,omitempty" doc:"the name of the domain to which the template belongs"`
DomainID string `json:"domainid,omitempty" doc:"the ID of the domain to which the template belongs"`
Format string `json:"format,omitempty" doc:"the format of the template."`
HostID string `json:"hostid,omitempty" doc:"the ID of the secondary storage host for the template"`
HostName string `json:"hostname,omitempty" doc:"the name of the secondary storage host for the template"`
Hypervisor string `json:"hypervisor,omitempty" doc:"the hypervisor on which the template runs"`
ID string `json:"id,omitempty" doc:"the template ID"`
IsDynamicallyScalable bool `json:"isdynamicallyscalable,omitempty" doc:"true if template contains XS/VMWare tools inorder to support dynamic scaling of VM cpu/memory"`
IsExtractable bool `json:"isextractable,omitempty" doc:"true if the template is extractable, false otherwise"`
IsFeatured bool `json:"isfeatured,omitempty" doc:"true if this template is a featured template, false otherwise"`
IsPublic bool `json:"ispublic,omitempty" doc:"true if this template is a public template, false otherwise"`
IsReady bool `json:"isready,omitempty" doc:"true if the template is ready to be deployed from, false otherwise."`
Name string `json:"name,omitempty" doc:"the template name"`
OsTypeID string `json:"ostypeid,omitempty" doc:"the ID of the OS type for this template."`
OsTypeName string `json:"ostypename,omitempty" doc:"the name of the OS type for this template."`
PasswordEnabled bool `json:"passwordenabled,omitempty" doc:"true if the reset password feature is enabled, false otherwise"`
Removed string `json:"removed,omitempty" doc:"the date this template was removed"`
Size int64 `json:"size,omitempty" doc:"the size of the template"`
SourceTemplateID string `json:"sourcetemplateid,omitempty" doc:"the template ID of the parent template if present"`
SSHKeyEnabled bool `json:"sshkeyenabled,omitempty" doc:"true if template is sshkey enabled, false otherwise"`
Status string `json:"status,omitempty" doc:"the status of the template"`
Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with tempate"`
TemplateDirectory string `json:"templatedirectory,omitempty" doc:"Template directory"`
TemplateTag string `json:"templatetag,omitempty" doc:"the tag of this template"`
TemplateType string `json:"templatetype,omitempty" doc:"the type of the template"`
URL string `json:"url,omitempty" doc:"Original URL of the template where it was downloaded"`
ZoneID string `json:"zoneid,omitempty" doc:"the ID of the zone for this template"`
ZoneName string `json:"zonename,omitempty" doc:"the name of the zone for this template"`
}
// ResourceType returns the type of the resource
func (Template) ResourceType() string {
return "Template"
}
// ListRequest builds the ListTemplates request
func (temp Template) ListRequest() (ListCommand, error) {
req := &ListTemplates{
Name: temp.Name,
Account: temp.Account,
DomainID: temp.DomainID,
ID: temp.ID,
ZoneID: temp.ZoneID,
Hypervisor: temp.Hypervisor,
//TODO Tags
}
if temp.IsFeatured {
req.TemplateFilter = "featured"
}
if temp.Removed != "" {
*req.ShowRemoved = true
}
return req, nil
}
// ListTemplates represents a template query filter
type ListTemplates struct {
TemplateFilter string `json:"templatefilter" doc:"possible values are \"featured\", \"self\", \"selfexecutable\",\"sharedexecutable\",\"executable\", and \"community\". * featured : templates that have been marked as featured and public. * self : templates that have been registered or created by the calling user. * selfexecutable : same as self, but only returns templates that can be used to deploy a new VM. * sharedexecutable : templates ready to be deployed that have been granted to the calling user by another user. * executable : templates that are owned by the calling user, or public templates, that can be used to deploy a VM. * community : templates that have been marked as public but not featured. * all : all templates (only usable by admins)."`
Account string `json:"account,omitempty" doc:"list resources by account. Must be used with the domainId parameter."`
DomainID string `json:"domainid,omitempty" doc:"list only resources belonging to the domain specified"`
Hypervisor string `json:"hypervisor,omitempty" doc:"the hypervisor for which to restrict the search"`
ID string `json:"id,omitempty" doc:"the template ID"`
IsRecursive *bool `json:"isrecursive,omitempty" doc:"defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves."`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
ListAll *bool `json:"listall,omitempty" doc:"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"`
Name string `json:"name,omitempty" doc:"the template name"`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
ShowRemoved *bool `json:"showremoved,omitempty" doc:"show removed templates as well"`
Tags []ResourceTag `json:"tags,omitempty" doc:"List resources by tags (key/value pairs)"`
ZoneID string `json:"zoneid,omitempty" doc:"list templates by zoneId"`
_ bool `name:"listTemplates" description:"List all public, private, and privileged templates."`
}
// ListTemplatesResponse represents a list of templates
type ListTemplatesResponse struct {
Count int `json:"count"`
Template []Template `json:"template"`
}
func (ListTemplates) response() interface{} {
return new(ListTemplatesResponse)
}
func (ListTemplates) each(resp interface{}, callback IterateItemFunc) {
temps, ok := resp.(*ListTemplatesResponse)
if !ok {
callback(nil, fmt.Errorf("wrong type. ListTemplatesResponse expected, got %T", resp))
return
}
for i := range temps.Template {
if !callback(&temps.Template[i], nil) {
break
}
}
}
// SetPage sets the current page
func (ls *ListTemplates) SetPage(page int) {
ls.Page = page
}
// SetPageSize sets the page size
func (ls *ListTemplates) SetPageSize(pageSize int) {
ls.PageSize = pageSize
}
// CreateTemplate (Async) represents a template creation
type CreateTemplate struct {
Bits int `json:"bits,omitempty" doc:"32 or 64 bit"`
Details map[string]string `json:"details,omitempty" doc:"Template details in key/value pairs."`
DisplayText string `json:"displaytext" doc:"the display text of the template. This is usually used for display purposes."`
IsDynamicallyScalable *bool `json:"isdynamicallyscalable,omitempty" doc:"true if template contains XS/VMWare tools inorder to support dynamic scaling of VM cpu/memory"`
IsFeatured *bool `json:"isfeatured,omitempty" doc:"true if this template is a featured template, false otherwise"`
IsPublic *bool `json:"ispublic,omitempty" doc:"true if this template is a public template, false otherwise"`
Name string `json:"name" doc:"the name of the template"`
OsTypeID string `json:"ostypeid" doc:"the ID of the OS Type that best represents the OS of this template."`
PasswordEnabled *bool `json:"passwordenabled,omitempty" doc:"true if the template supports the password reset feature; default is false"`
RequiresHVM *bool `json:"requireshvm,omitempty" doc:"true if the template requres HVM, false otherwise"`
SnapshotID string `json:"snapshotid,omitempty" doc:"the ID of the snapshot the template is being created from. Either this parameter, or volumeId has to be passed in"`
TemplateTag string `json:"templatetag,omitempty" doc:"the tag for this template."`
URL string `json:"url,omitempty" doc:"Optional, only for baremetal hypervisor. The directory name where template stored on CIFS server"`
VirtualMachineID string `json:"virtualmachineid,omitempty" doc:"Optional, VM ID. If this presents, it is going to create a baremetal template for VM this ID refers to. This is only for VM whose hypervisor type is BareMetal"`
VolumeID string `json:"volumeid,omitempty" doc:"the ID of the disk volume the template is being created from. Either this parameter, or snapshotId has to be passed in"`
_ bool `name:"createTemplate" description:"Creates a template of a virtual machine. The virtual machine must be in a STOPPED state. A template created from this command is automatically designated as a private template visible to the account that created it."`
}
func (CreateTemplate) response() interface{} {
return new(AsyncJobResult)
}
func (CreateTemplate) asyncResponse() interface{} {
return new(Template)
}
// CopyTemplate (Async) represents a template copy
type CopyTemplate struct {
DestZoneID string `json:"destzoneid" doc:"ID of the zone the template is being copied to."`
ID string `json:"id" doc:"Template ID."`
SourceZoneID string `json:"sourcezoneid,omitempty" doc:"ID of the zone the template is currently hosted on. If not specified and template is cross-zone, then we will sync this template to region wide image store."`
_ bool `name:"copyTemplate" description:"Copies a template from one zone to another."`
}
func (CopyTemplate) response() interface{} {
return new(AsyncJobResult)
}
func (CopyTemplate) asyncResponse() interface{} {
return new(Template)
}
// UpdateTemplate represents a template change
type UpdateTemplate struct {
Bootable *bool `json:"bootable,omitempty" doc:"true if image is bootable, false otherwise"`
Details map[string]string `json:"details,omitempty" doc:"Details in key/value pairs."`
DisplayText string `json:"displaytext,omitempty" doc:"the display text of the image"`
Format string `json:"format,omitempty" doc:"the format for the image"`
ID string `json:"id" doc:"the ID of the image file"`
IsDynamicallyScalable *bool `json:"isdynamicallyscalable,omitempty" doc:"true if template/ISO contains XS/VMWare tools inorder to support dynamic scaling of VM cpu/memory"`
IsRouting *bool `json:"isrouting,omitempty" doc:"true if the template type is routing i.e., if template is used to deploy router"`
Name string `json:"name,omitempty" doc:"the name of the image file"`
OsTypeID string `json:"ostypeid,omitempty" doc:"the ID of the OS type that best represents the OS of this image."`
PasswordEnabled *bool `json:"passwordenabled,omitempty" doc:"true if the image supports the password reset feature; default is false"`
SortKey int `json:"sortkey,omitempty" doc:"sort key of the template, integer"`
_ bool `name:"updateTemplate" description:"Updates attributes of a template."`
}
func (UpdateTemplate) response() interface{} {
return new(AsyncJobResult)
}
func (UpdateTemplate) asyncResponse() interface{} {
return new(Template)
}
// DeleteTemplate (Async) represents the deletion of a template
type DeleteTemplate struct {
ID string `json:"id" doc:"the ID of the template"`
ZoneID string `json:"zoneid,omitempty" doc:"the ID of zone of the template"`
_ bool `name:"deleteTemplate" description:"Deletes a template from the system. All virtual machines using the deleted template will not be affected."`
}
func (DeleteTemplate) response() interface{} {
return new(AsyncJobResult)
}
func (DeleteTemplate) asyncResponse() interface{} {
return new(booleanResponse)
}
// PrepareTemplate represents a template preparation
type PrepareTemplate struct {
TemplateID string `json:"templateid" doc:"template ID of the template to be prepared in primary storage(s)."`
ZoneID string `json:"zoneid" doc:"zone ID of the template to be prepared in primary storage(s)."`
_ bool `name:"prepareTemplate" description:"load template into primary storage"`
}
func (PrepareTemplate) response() interface{} {
return new(AsyncJobResult)
}
func (PrepareTemplate) asyncResponse() interface{} {
return new(Template)
}
// RegisterTemplate represents a template registration
type RegisterTemplate struct {
Account string `json:"account,omitempty" doc:"an optional accountName. Must be used with domainId."`
Bits int `json:"bits,omitempty" doc:"32 or 64 bits support. 64 by default"`
Checksum string `json:"checksum,omitempty" doc:"the MD5 checksum value of this template"`
Details map[string]string `json:"details,omitempty" doc:"Template details in key/value pairs."`
DisplayText string `json:"displaytext" doc:"the display text of the template. This is usually used for display purposes."`
DomainID string `json:"domainid,omitempty" doc:"an optional domainId. If the account parameter is used, domainId must also be used."`
Format string `json:"format" doc:"the format for the template. Possible values include QCOW2, RAW, and VHD."`
Hypervisor string `json:"hypervisor" doc:"the target hypervisor for the template"`
IsDynamicallyScalable *bool `json:"isdynamicallyscalable,omitempty" doc:"true if template contains XS/VMWare tools inorder to support dynamic scaling of VM cpu/memory"`
IsExtractable *bool `json:"isextractable,omitempty" doc:"true if the template or its derivatives are extractable; default is false"`
IsFeatured *bool `json:"isfeatured,omitempty" doc:"true if this template is a featured template, false otherwise"`
IsPublic *bool `json:"ispublic,omitempty" doc:"true if the template is available to all accounts; default is true"`
IsRouting *bool `json:"isrouting,omitempty" doc:"true if the template type is routing i.e., if template is used to deploy router"`
IsSystem *bool `json:"issystem,omitempty" doc:"true if the template type is system i.e., if template is used to deploy system VM"`
Name string `json:"name" doc:"the name of the template"`
OsTypeID string `json:"ostypeid" doc:"the ID of the OS Type that best represents the OS of this template."`
PasswordEnabled *bool `json:"passwordenabled,omitempty" doc:"true if the template supports the password reset feature; default is false"`
RequiresHVM *bool `json:"requireshvm,omitempty" doc:"true if this template requires HVM"`
SSHKeyEnabled *bool `json:"sshkeyenabled,omitempty" doc:"true if the template supports the sshkey upload feature; default is false"`
TemplateTag string `json:"templatetag,omitempty" doc:"the tag for this template."`
URL string `json:"url" doc:"the URL of where the template is hosted. Possible URL include http:// and https://"`
ZoneID string `json:"zoneid" doc:"the ID of the zone the template is to be hosted on"`
_ bool `name:"registerTemplate" description:"Registers an existing template into the CloudStack cloud."`
}
func (RegisterTemplate) response() interface{} {
return new(Template)
}

109
vendor/github.com/exoscale/egoscale/users.go generated vendored Normal file
View file

@ -0,0 +1,109 @@
package egoscale
// User represents a User
type User struct {
APIKey string `json:"apikey,omitempty" doc:"the api key of the user"`
Account string `json:"account,omitempty" doc:"the account name of the user"`
AccountID string `json:"accountid,omitempty" doc:"the account ID of the user"`
AccountType int16 `json:"accounttype,omitempty" doc:"the account type of the user"`
Created string `json:"created,omitempty" doc:"the date and time the user account was created"`
Domain string `json:"domain,omitempty" doc:"the domain name of the user"`
DomainID string `json:"domainid,omitempty" doc:"the domain ID of the user"`
Email string `json:"email,omitempty" doc:"the user email address"`
FirstName string `json:"firstname,omitempty" doc:"the user firstname"`
ID string `json:"id,omitempty" doc:"the user ID"`
IsCallerChildDomain bool `json:"iscallerchilddomain,omitempty" doc:"the boolean value representing if the updating target is in caller's child domain"`
IsDefault bool `json:"isdefault,omitempty" doc:"true if user is default, false otherwise"`
LastName string `json:"lastname,omitempty" doc:"the user lastname"`
RoleID string `json:"roleid,omitempty" doc:"the ID of the role"`
RoleName string `json:"rolename,omitempty" doc:"the name of the role"`
RoleType string `json:"roletype,omitempty" doc:"the type of the role"`
SecretKey string `json:"secretkey,omitempty" doc:"the secret key of the user"`
State string `json:"state,omitempty" doc:"the user state"`
Timezone string `json:"timezone,omitempty" doc:"the timezone user was created in"`
UserName string `json:"username,omitempty" doc:"the user name"`
}
// RegisterUserKeys registers a new set of key of the given user
//
// NB: only the APIKey and SecretKey will be filled
type RegisterUserKeys struct {
ID string `json:"id" doc:"User id"`
_ bool `name:"registerUserKeys" description:"This command allows a user to register for the developer API, returning a secret key and an API key. This request is made through the integration API port, so it is a privileged command and must be made on behalf of a user. It is up to the implementer just how the username and password are entered, and then how that translates to an integration API request. Both secret key and API key should be returned to the user"`
}
func (RegisterUserKeys) response() interface{} {
return new(User)
}
// CreateUser represents the creation of a User
type CreateUser struct {
Account string `json:"account" doc:"Creates the user under the specified account. If no account is specified, the username will be used as the account name."`
Email string `json:"email" doc:"email"`
FirstName string `json:"firstname" doc:"firstname"`
LastName string `json:"lastname" doc:"lastname"`
Password string `json:"password" doc:"Clear text password (Default hashed to SHA256SALT). If you wish to use any other hashing algorithm, you would need to write a custom authentication adapter See Docs section."`
UserName string `json:"username" doc:"Unique username."`
DomainID string `json:"domainid,omitempty" doc:"Creates the user under the specified domain. Has to be accompanied with the account parameter"`
Timezone string `json:"timezone,omitempty" doc:"Specifies a timezone for this command. For more information on the timezone parameter, see Time Zone Format."`
UserID string `json:"userid,omitempty" doc:"User UUID, required for adding account from external provisioning system"`
_ bool `name:"createUser" description:"Creates a user for an account that already exists"`
}
func (CreateUser) response() interface{} {
return new(User)
}
// UpdateUser represents the modification of a User
type UpdateUser struct {
ID string `json:"id" doc:"User uuid"`
Email string `json:"email,omitempty" doc:"email"`
FirstName string `json:"firstname,omitempty" doc:"first name"`
LastName string `json:"lastname,omitempty" doc:"last name"`
Password string `json:"password,omitempty" doc:"Clear text password (default hashed to SHA256SALT). If you wish to use any other hashing algorithm, you would need to write a custom authentication adapter"`
Timezone string `json:"timezone,omitempty" doc:"Specifies a timezone for this command. For more information on the timezone parameter, see Time Zone Format."`
UserAPIKey string `json:"userapikey,omitempty" doc:"The API key for the user. Must be specified with userSecretKey"`
UserName string `json:"username,omitempty" doc:"Unique username"`
UserSecretKey string `json:"usersecretkey,omitempty" doc:"The secret key for the user. Must be specified with userApiKey"`
_ bool `name:"updateUser" description:"Updates a user account"`
}
func (UpdateUser) response() interface{} {
return new(User)
}
// ListUsers represents the search for Users
type ListUsers struct {
Account string `json:"account,omitempty" doc:"list resources by account. Must be used with the domainId parameter."`
AccountType int64 `json:"accounttype,omitempty" doc:"List users by account type. Valid types include admin, domain-admin, read-only-admin, or user."`
DomainID string `json:"domainid,omitempty" doc:"list only resources belonging to the domain specified"`
ID string `json:"id,omitempty" doc:"List user by ID."`
IsRecursive bool `json:"isrecursive,omitempty" doc:"defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves."`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
ListAll bool `json:"listall,omitempty" doc:"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
State string `json:"state,omitempty" doc:"List users by state of the user account."`
Username string `json:"username,omitempty" doc:"List user by the username"`
_ bool `name:"listUsers" description:"Lists user accounts"`
}
// ListUsersResponse represents a list of users
type ListUsersResponse struct {
Count int `json:"count"`
User []User `json:"user"`
}
func (ListUsers) response() interface{} {
return new(ListUsersResponse)
}
// DeleteUser deletes a user for an account
type DeleteUser struct {
ID string `json:"id" doc:"id of the user to be deleted"`
_ bool `name:"deleteUser" description:"Deletes a user for an account"`
}
func (DeleteUser) response() interface{} {
return new(booleanResponse)
}

4
vendor/github.com/exoscale/egoscale/version.go generated vendored Normal file
View file

@ -0,0 +1,4 @@
package egoscale
// Version of the library
const Version = "0.10.5"

600
vendor/github.com/exoscale/egoscale/virtual_machines.go generated vendored Normal file
View file

@ -0,0 +1,600 @@
package egoscale
import (
"bytes"
"compress/gzip"
"context"
"encoding/base64"
"fmt"
"io/ioutil"
"net"
"net/url"
)
// VirtualMachine represents a virtual machine
//
// See: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/stable/virtual_machines.html
type VirtualMachine struct {
Account string `json:"account,omitempty" doc:"the account associated with the virtual machine"`
AccountID string `json:"accountid,omitempty" doc:"the account ID associated with the virtual machine"`
AffinityGroup []AffinityGroup `json:"affinitygroup,omitempty" doc:"list of affinity groups associated with the virtual machine"`
ClusterID string `json:"clusterid,omitempty" doc:"the ID of the vm's cluster"`
ClusterName string `json:"clustername,omitempty" doc:"the name of the vm's cluster"`
CPUNumber int `json:"cpunumber,omitempty" doc:"the number of cpu this virtual machine is running with"`
CPUSpeed int `json:"cpuspeed,omitempty" doc:"the speed of each cpu"`
CPUUsed string `json:"cpuused,omitempty" doc:"the amount of the vm's CPU currently used"`
Created string `json:"created,omitempty" doc:"the date when this virtual machine was created"`
Details map[string]string `json:"details,omitempty" doc:"Vm details in key/value pairs."`
DiskIoRead int64 `json:"diskioread,omitempty" doc:"the read (io) of disk on the vm"`
DiskIoWrite int64 `json:"diskiowrite,omitempty" doc:"the write (io) of disk on the vm"`
DiskKbsRead int64 `json:"diskkbsread,omitempty" doc:"the read (bytes) of disk on the vm"`
DiskKbsWrite int64 `json:"diskkbswrite,omitempty" doc:"the write (bytes) of disk on the vm"`
DiskOfferingID string `json:"diskofferingid,omitempty" doc:"the ID of the disk offering of the virtual machine"`
DiskOfferingName string `json:"diskofferingname,omitempty" doc:"the name of the disk offering of the virtual machine"`
DisplayName string `json:"displayname,omitempty" doc:"user generated name. The name of the virtual machine is returned if no displayname exists."`
DisplayVM bool `json:"displayvm,omitempty" doc:"an optional field whether to the display the vm to the end user or not."`
Domain string `json:"domain,omitempty" doc:"the name of the domain in which the virtual machine exists"`
DomainID string `json:"domainid,omitempty" doc:"the ID of the domain in which the virtual machine exists"`
ForVirtualNetwork bool `json:"forvirtualnetwork,omitempty" doc:"the virtual network for the service offering"`
Group string `json:"group,omitempty" doc:"the group name of the virtual machine"`
GroupID string `json:"groupid,omitempty" doc:"the group ID of the virtual machine"`
HAEnable bool `json:"haenable,omitempty" doc:"true if high-availability is enabled, false otherwise"`
HostID string `json:"hostid,omitempty" doc:"the ID of the host for the virtual machine"`
HostName string `json:"hostname,omitempty" doc:"the name of the host for the virtual machine"`
Hypervisor string `json:"hypervisor,omitempty" doc:"the hypervisor on which the template runs"`
ID string `json:"id,omitempty" doc:"the ID of the virtual machine"`
InstanceName string `json:"instancename,omitempty" doc:"instance name of the user vm; this parameter is returned to the ROOT admin only"`
IsDynamicallyScalable bool `json:"isdynamicallyscalable,omitempty" doc:"true if vm contains XS/VMWare tools inorder to support dynamic scaling of VM cpu/memory."`
IsoDisplayText string `json:"isodisplaytext,omitempty" doc:"an alternate display text of the ISO attached to the virtual machine"`
IsoID string `json:"isoid,omitempty" doc:"the ID of the ISO attached to the virtual machine"`
IsoName string `json:"isoname,omitempty" doc:"the name of the ISO attached to the virtual machine"`
KeyPair string `json:"keypair,omitempty" doc:"ssh key-pair"`
Memory int `json:"memory,omitempty" doc:"the memory allocated for the virtual machine"`
Name string `json:"name,omitempty" doc:"the name of the virtual machine"`
NetworkKbsRead int64 `json:"networkkbsread,omitempty" doc:"the incoming network traffic on the vm"`
NetworkKbsWrite int64 `json:"networkkbswrite,omitempty" doc:"the outgoing network traffic on the host"`
Nic []Nic `json:"nic,omitempty" doc:"the list of nics associated with vm"`
OsCategoryID string `json:"oscategoryid,omitempty" doc:"Os category ID of the virtual machine"`
OsCategoryName string `json:"oscategoryname,omitempty" doc:"Os category name of the virtual machine"`
Password string `json:"password,omitempty" doc:"the password (if exists) of the virtual machine"`
PasswordEnabled bool `json:"passwordenabled,omitempty" doc:"true if the password rest feature is enabled, false otherwise"`
PCIDevices []PCIDevice `json:"pcidevices,omitempty" doc:"list of PCI devices"`
PodID string `json:"podid,omitempty" doc:"the ID of the vm's pod"`
PodName string `json:"podname,omitempty" doc:"the name of the vm's pod"`
PublicIP string `json:"publicip,omitempty" doc:"public IP address id associated with vm via Static nat rule"`
PublicIPID string `json:"publicipid,omitempty" doc:"public IP address id associated with vm via Static nat rule"`
RootDeviceID int64 `json:"rootdeviceid,omitempty" doc:"device ID of the root volume"`
RootDeviceType string `json:"rootdevicetype,omitempty" doc:"device type of the root volume"`
SecurityGroup []SecurityGroup `json:"securitygroup,omitempty" doc:"list of security groups associated with the virtual machine"`
ServiceOfferingID string `json:"serviceofferingid,omitempty" doc:"the ID of the service offering of the virtual machine"`
ServiceOfferingName string `json:"serviceofferingname,omitempty" doc:"the name of the service offering of the virtual machine"`
ServiceState string `json:"servicestate,omitempty" doc:"State of the Service from LB rule"`
State string `json:"state,omitempty" doc:"the state of the virtual machine"`
Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with vm"`
TemplateDisplayText string `json:"templatedisplaytext,omitempty" doc:"an alternate display text of the template for the virtual machine"`
TemplateID string `json:"templateid,omitempty" doc:"the ID of the template for the virtual machine. A -1 is returned if the virtual machine was created from an ISO file."`
TemplateName string `json:"templatename,omitempty" doc:"the name of the template for the virtual machine"`
ZoneID string `json:"zoneid,omitempty" doc:"the ID of the availablility zone for the virtual machine"`
ZoneName string `json:"zonename,omitempty" doc:"the name of the availability zone for the virtual machine"`
}
// ResourceType returns the type of the resource
func (VirtualMachine) ResourceType() string {
return "UserVM"
}
// Delete destroys the VM
func (vm VirtualMachine) Delete(ctx context.Context, client *Client) error {
_, err := client.RequestWithContext(ctx, &DestroyVirtualMachine{
ID: vm.ID,
})
return err
}
// ListRequest builds the ListVirtualMachines request
func (vm VirtualMachine) ListRequest() (ListCommand, error) {
// XXX: AffinityGroupID, SecurityGroupID, Tags
req := &ListVirtualMachines{
Account: vm.Account,
DomainID: vm.DomainID,
GroupID: vm.GroupID,
ID: vm.ID,
Name: vm.Name,
State: vm.State,
TemplateID: vm.TemplateID,
ZoneID: vm.ZoneID,
}
nic := vm.DefaultNic()
if nic != nil {
req.IPAddress = nic.IPAddress
}
return req, nil
}
// DefaultNic returns the default nic
func (vm VirtualMachine) DefaultNic() *Nic {
for _, nic := range vm.Nic {
if nic.IsDefault {
return &nic
}
}
return nil
}
// IP returns the default nic IP address
func (vm VirtualMachine) IP() *net.IP {
nic := vm.DefaultNic()
if nic != nil {
ip := nic.IPAddress
return &ip
}
return nil
}
// NicsByType returns the corresponding interfaces base on the given type
func (vm VirtualMachine) NicsByType(nicType string) []Nic {
nics := make([]Nic, 0)
for _, nic := range vm.Nic {
if nic.Type == nicType {
// XXX The API forgets to specify it
nic.VirtualMachineID = vm.ID
nics = append(nics, nic)
}
}
return nics
}
// NicByNetworkID returns the corresponding interface based on the given NetworkID
//
// A VM cannot be connected twice to a same network.
func (vm VirtualMachine) NicByNetworkID(networkID string) *Nic {
for _, nic := range vm.Nic {
if nic.NetworkID == networkID {
nic.VirtualMachineID = vm.ID
return &nic
}
}
return nil
}
// NicByID returns the corresponding interface base on its ID
func (vm VirtualMachine) NicByID(nicID string) *Nic {
for _, nic := range vm.Nic {
if nic.ID == nicID {
nic.VirtualMachineID = vm.ID
return &nic
}
}
return nil
}
// IPToNetwork represents a mapping between ip and networks
type IPToNetwork struct {
IP string `json:"ip,omitempty"`
Ipv6 string `json:"ipv6,omitempty"`
NetworkID string `json:"networkid,omitempty"`
}
// PCIDevice represents a PCI card present in the host
type PCIDevice struct {
PCIVendorName string `json:"pcivendorname,omitempty" doc:"Device vendor name of pci card"`
DeviceID string `json:"deviceid,omitempty" doc:"Device model ID of pci card"`
RemainingCapacity int `json:"remainingcapacity,omitempty" doc:"Remaining capacity in terms of no. of more VMs that can be deployped with this vGPU type"`
MaxCapacity int `json:"maxcapacity,omitempty" doc:"Maximum vgpu can be created with this vgpu type on the given pci group"`
PCIVendorID string `json:"pcivendorid,omitempty" doc:"Device vendor ID of pci card"`
PCIDeviceName string `json:"pcidevicename,omitempty" doc:"Device model name of pci card"`
}
// Password represents an encrypted password
//
// TODO: method to decrypt it, https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=34014652
type Password struct {
EncryptedPassword string `json:"encryptedpassword"`
}
// VirtualMachineUserData represents the base64 encoded user-data
type VirtualMachineUserData struct {
UserData string `json:"userdata,omitempty" doc:"Base 64 encoded VM user data"`
VirtualMachineID string `json:"virtualmachineid,omitempty" doc:"the ID of the virtual machine"`
}
// Decode decodes as a readable string the content of the user-data (base64 · gzip)
func (userdata VirtualMachineUserData) Decode() (string, error) {
data, err := base64.StdEncoding.DecodeString(userdata.UserData)
if err != nil {
return "", err
}
// 0x1f8b is the magic number for gzip
if len(data) < 2 || data[0] != 0x1f || data[1] != 0x8b {
return string(data), nil
}
gr, err := gzip.NewReader(bytes.NewBuffer(data))
if err != nil {
return "", err
}
defer gr.Close() // nolint: errcheck
str, err := ioutil.ReadAll(gr)
if err != nil {
return "", err
}
return string(str), nil
}
// DeployVirtualMachine (Async) represents the machine creation
//
// Regarding the UserData field, the client is responsible to base64 (and probably gzip) it. Doing it within this library would make the integration with other tools, e.g. Terraform harder.
type DeployVirtualMachine struct {
Account string `json:"account,omitempty" doc:"an optional account for the virtual machine. Must be used with domainId."`
AffinityGroupIDs []string `json:"affinitygroupids,omitempty" doc:"comma separated list of affinity groups id that are going to be applied to the virtual machine. Mutually exclusive with affinitygroupnames parameter"`
AffinityGroupNames []string `json:"affinitygroupnames,omitempty" doc:"comma separated list of affinity groups names that are going to be applied to the virtual machine.Mutually exclusive with affinitygroupids parameter"`
CustomID string `json:"customid,omitempty" doc:"an optional field, in case you want to set a custom id to the resource. Allowed to Root Admins only"`
DeploymentPlanner string `json:"deploymentplanner,omitempty" doc:"Deployment planner to use for vm allocation. Available to ROOT admin only"`
Details map[string]string `json:"details,omitempty" doc:"used to specify the custom parameters."`
DiskOfferingID string `json:"diskofferingid,omitempty" doc:"the ID of the disk offering for the virtual machine. If the template is of ISO format, the diskOfferingId is for the root disk volume. Otherwise this parameter is used to indicate the offering for the data disk volume. If the templateId parameter passed is from a Template object, the diskOfferingId refers to a DATA Disk Volume created. If the templateId parameter passed is from an ISO object, the diskOfferingId refers to a ROOT Disk Volume created."`
DisplayName string `json:"displayname,omitempty" doc:"an optional user generated name for the virtual machine"`
DisplayVM *bool `json:"displayvm,omitempty" doc:"an optional field, whether to the display the vm to the end user or not."`
DomainID string `json:"domainid,omitempty" doc:"an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used."`
Group string `json:"group,omitempty" doc:"an optional group for the virtual machine"`
HostID string `json:"hostid,omitempty" doc:"destination Host ID to deploy the VM to - parameter available for root admin only"`
Hypervisor string `json:"hypervisor,omitempty" doc:"the hypervisor on which to deploy the virtual machine"`
IP4 *bool `json:"ip4,omitempty" doc:"True to set an IPv4 to the default interface"`
IP6 *bool `json:"ip6,omitempty" doc:"True to set an IPv6 to the default interface"`
IP6Address net.IP `json:"ip6address,omitempty" doc:"the ipv6 address for default vm's network"`
IPAddress net.IP `json:"ipaddress,omitempty" doc:"the ip address for default vm's network"`
IPToNetworkList []IPToNetwork `json:"iptonetworklist,omitempty" doc:"ip to network mapping. Can't be specified with networkIds parameter. Example: iptonetworklist[0].ip=10.10.10.11&iptonetworklist[0].ipv6=fc00:1234:5678::abcd&iptonetworklist[0].networkid=uuid - requests to use ip 10.10.10.11 in network id=uuid"`
Keyboard string `json:"keyboard,omitempty" doc:"an optional keyboard device type for the virtual machine. valid value can be one of de,de-ch,es,fi,fr,fr-be,fr-ch,is,it,jp,nl-be,no,pt,uk,us"`
KeyPair string `json:"keypair,omitempty" doc:"name of the ssh key pair used to login to the virtual machine"`
Name string `json:"name,omitempty" doc:"host name for the virtual machine"`
NetworkIDs []string `json:"networkids,omitempty" doc:"list of network ids used by virtual machine. Can't be specified with ipToNetworkList parameter"`
RootDiskSize int64 `json:"rootdisksize,omitempty" doc:"Optional field to resize root disk on deploy. Value is in GB. Only applies to template-based deployments. Analogous to details[0].rootdisksize, which takes precedence over this parameter if both are provided"`
SecurityGroupIDs []string `json:"securitygroupids,omitempty" doc:"comma separated list of security groups id that going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupnames parameter"`
SecurityGroupNames []string `json:"securitygroupnames,omitempty" doc:"comma separated list of security groups names that going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupids parameter"`
ServiceOfferingID string `json:"serviceofferingid" doc:"the ID of the service offering for the virtual machine"`
Size int64 `json:"size,omitempty" doc:"the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId"`
StartVM *bool `json:"startvm,omitempty" doc:"true if start vm after creating. Default value is true"`
TemplateID string `json:"templateid" doc:"the ID of the template for the virtual machine"`
UserData string `json:"userdata,omitempty" doc:"an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary data must be base64 encoded before adding it to the request. Using HTTP GET (via querystring), you can send up to 2KB of data after base64 encoding. Using HTTP POST(via POST body), you can send up to 32K of data after base64 encoding."`
ZoneID string `json:"zoneid" doc:"availability zone for the virtual machine"`
_ bool `name:"deployVirtualMachine" description:"Creates and automatically starts a virtual machine based on a service offering, disk offering, and template."`
}
func (req DeployVirtualMachine) onBeforeSend(params url.Values) error {
// Either AffinityGroupIDs or AffinityGroupNames must be set
if len(req.AffinityGroupIDs) > 0 && len(req.AffinityGroupNames) > 0 {
return fmt.Errorf("either AffinityGroupIDs or AffinityGroupNames must be set")
}
// Either SecurityGroupIDs or SecurityGroupNames must be set
if len(req.SecurityGroupIDs) > 0 && len(req.SecurityGroupNames) > 0 {
return fmt.Errorf("either SecurityGroupIDs or SecurityGroupNames must be set")
}
return nil
}
func (DeployVirtualMachine) response() interface{} {
return new(AsyncJobResult)
}
func (DeployVirtualMachine) asyncResponse() interface{} {
return new(VirtualMachine)
}
// StartVirtualMachine (Async) represents the creation of the virtual machine
type StartVirtualMachine struct {
ID string `json:"id" doc:"The ID of the virtual machine"`
DeploymentPlanner string `json:"deploymentplanner,omitempty" doc:"Deployment planner to use for vm allocation. Available to ROOT admin only"`
HostID string `json:"hostid,omitempty" doc:"destination Host ID to deploy the VM to - parameter available for root admin only"`
_ bool `name:"startVirtualMachine" description:"Starts a virtual machine."`
}
func (StartVirtualMachine) response() interface{} {
return new(AsyncJobResult)
}
func (StartVirtualMachine) asyncResponse() interface{} {
return new(VirtualMachine)
}
// StopVirtualMachine (Async) represents the stopping of the virtual machine
type StopVirtualMachine struct {
ID string `json:"id" doc:"The ID of the virtual machine"`
Forced *bool `json:"forced,omitempty" doc:"Force stop the VM (vm is marked as Stopped even when command fails to be send to the backend). The caller knows the VM is stopped."`
_ bool `name:"stopVirtualMachine" description:"Stops a virtual machine."`
}
func (StopVirtualMachine) response() interface{} {
return new(AsyncJobResult)
}
func (StopVirtualMachine) asyncResponse() interface{} {
return new(VirtualMachine)
}
// RebootVirtualMachine (Async) represents the rebooting of the virtual machine
type RebootVirtualMachine struct {
ID string `json:"id" doc:"The ID of the virtual machine"`
_ bool `name:"rebootVirtualMachine" description:"Reboots a virtual machine."`
}
func (RebootVirtualMachine) response() interface{} {
return new(AsyncJobResult)
}
func (RebootVirtualMachine) asyncResponse() interface{} {
return new(VirtualMachine)
}
// RestoreVirtualMachine (Async) represents the restoration of the virtual machine
type RestoreVirtualMachine struct {
VirtualMachineID string `json:"virtualmachineid" doc:"Virtual Machine ID"`
TemplateID string `json:"templateid,omitempty" doc:"an optional template Id to restore vm from the new template. This can be an ISO id in case of restore vm deployed using ISO"`
RootDiskSize int64 `json:"rootdisksize,omitempty" doc:"Optional field to resize root disk on restore. Value is in GB. Only applies to template-based deployments."`
_ bool `name:"restoreVirtualMachine" description:"Restore a VM to original template/ISO or new template/ISO"`
}
func (RestoreVirtualMachine) response() interface{} {
return new(AsyncJobResult)
}
func (RestoreVirtualMachine) asyncResponse() interface{} {
return new(VirtualMachine)
}
// RecoverVirtualMachine represents the restoration of the virtual machine
type RecoverVirtualMachine struct {
ID string `json:"id" doc:"The ID of the virtual machine"`
_ bool `name:"recoverVirtualMachine" description:"Recovers a virtual machine."`
}
func (RecoverVirtualMachine) response() interface{} {
return new(VirtualMachine)
}
// DestroyVirtualMachine (Async) represents the destruction of the virtual machine
type DestroyVirtualMachine struct {
ID string `json:"id" doc:"The ID of the virtual machine"`
Expunge *bool `json:"expunge,omitempty" doc:"If true is passed, the vm is expunged immediately. False by default."`
_ bool `name:"destroyVirtualMachine" description:"Destroys a virtual machine."`
}
func (DestroyVirtualMachine) response() interface{} {
return new(AsyncJobResult)
}
func (DestroyVirtualMachine) asyncResponse() interface{} {
return new(VirtualMachine)
}
// UpdateVirtualMachine represents the update of the virtual machine
type UpdateVirtualMachine struct {
ID string `json:"id" doc:"The ID of the virtual machine"`
CustomID string `json:"customid,omitempty" doc:"an optional field, in case you want to set a custom id to the resource. Allowed to Root Admins only"`
Details map[string]string `json:"details,omitempty" doc:"Details in key/value pairs."`
DisplayName string `json:"displayname,omitempty" doc:"user generated name"`
DisplayVM *bool `json:"displayvm,omitempty" doc:"an optional field, whether to the display the vm to the end user or not."`
Group string `json:"group,omitempty" doc:"group of the virtual machine"`
HAEnable *bool `json:"haenable,omitempty" doc:"true if high-availability is enabled for the virtual machine, false otherwise"`
IsDynamicallyScalable *bool `json:"isdynamicallyscalable,omitempty" doc:"true if VM contains XS/VMWare tools inorder to support dynamic scaling of VM cpu/memory"`
Name string `json:"name,omitempty" doc:"new host name of the vm. The VM has to be stopped/started for this update to take affect"`
SecurityGroupIDs []string `json:"securitygroupids,omitempty" doc:"list of security group ids to be applied on the virtual machine."`
UserData string `json:"userdata,omitempty" doc:"an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary data must be base64 encoded before adding it to the request. Using HTTP GET (via querystring), you can send up to 2KB of data after base64 encoding. Using HTTP POST(via POST body), you can send up to 32K of data after base64 encoding."`
_ bool `name:"updateVirtualMachine" description:"Updates properties of a virtual machine. The VM has to be stopped and restarted for the new properties to take effect. UpdateVirtualMachine does not first check whether the VM is stopped. Therefore, stop the VM manually before issuing this call."`
}
func (UpdateVirtualMachine) response() interface{} {
return new(VirtualMachine)
}
// ExpungeVirtualMachine represents the annihilation of a VM
type ExpungeVirtualMachine struct {
ID string `json:"id" doc:"The ID of the virtual machine"`
_ bool `name:"expungeVirtualMachine" description:"Expunge a virtual machine. Once expunged, it cannot be recoverd."`
}
func (ExpungeVirtualMachine) response() interface{} {
return new(AsyncJobResult)
}
func (ExpungeVirtualMachine) asyncResponse() interface{} {
return new(booleanResponse)
}
// ScaleVirtualMachine (Async) scales the virtual machine to a new service offering.
//
// ChangeServiceForVirtualMachine does the same thing but returns the
// new Virtual Machine which is more consistent with the rest of the API.
type ScaleVirtualMachine struct {
ID string `json:"id" doc:"The ID of the virtual machine"`
ServiceOfferingID string `json:"serviceofferingid" doc:"the ID of the service offering for the virtual machine"`
Details map[string]string `json:"details,omitempty" doc:"name value pairs of custom parameters for cpu,memory and cpunumber. example details[i].name=value"`
_ bool `name:"scaleVirtualMachine" description:"Scales the virtual machine to a new service offering."`
}
func (ScaleVirtualMachine) response() interface{} {
return new(AsyncJobResult)
}
func (ScaleVirtualMachine) asyncResponse() interface{} {
return new(booleanResponse)
}
// ChangeServiceForVirtualMachine changes the service offering for a virtual machine. The virtual machine must be in a "Stopped" state for this command to take effect.
type ChangeServiceForVirtualMachine struct {
ID string `json:"id" doc:"The ID of the virtual machine"`
ServiceOfferingID string `json:"serviceofferingid" doc:"the service offering ID to apply to the virtual machine"`
Details map[string]string `json:"details,omitempty" doc:"name value pairs of custom parameters for cpu, memory and cpunumber. example details[i].name=value"`
_ bool `name:"changeServiceForVirtualMachine" description:"Changes the service offering for a virtual machine. The virtual machine must be in a \"Stopped\" state for this command to take effect."`
}
func (ChangeServiceForVirtualMachine) response() interface{} {
return new(VirtualMachine)
}
// ResetPasswordForVirtualMachine resets the password for virtual machine. The virtual machine must be in a "Stopped" state...
type ResetPasswordForVirtualMachine struct {
ID string `json:"id" doc:"The ID of the virtual machine"`
_ bool `name:"resetPasswordForVirtualMachine" description:"Resets the password for virtual machine. The virtual machine must be in a \"Stopped\" state and the template must already support this feature for this command to take effect."`
}
func (ResetPasswordForVirtualMachine) response() interface{} {
return new(AsyncJobResult)
}
func (ResetPasswordForVirtualMachine) asyncResponse() interface{} {
return new(VirtualMachine)
}
// GetVMPassword asks for an encrypted password
type GetVMPassword struct {
ID string `json:"id" doc:"The ID of the virtual machine"`
_ bool `name:"getVMPassword" description:"Returns an encrypted password for the VM"`
}
func (GetVMPassword) response() interface{} {
return new(Password)
}
// ListVirtualMachines represents a search for a VM
type ListVirtualMachines struct {
Account string `json:"account,omitempty" doc:"list resources by account. Must be used with the domainId parameter."`
AffinityGroupID string `json:"affinitygroupid,omitempty" doc:"list vms by affinity group"`
Details []string `json:"details,omitempty" doc:"comma separated list of host details requested, value can be a list of [all, group, nics, stats, secgrp, tmpl, servoff, diskoff, iso, volume, min, affgrp]. If no parameter is passed in, the details will be defaulted to all"`
DisplayVM *bool `json:"displayvm,omitempty" doc:"list resources by display flag; only ROOT admin is eligible to pass this parameter"`
DomainID string `json:"domainid,omitempty" doc:"list only resources belonging to the domain specified"`
ForVirtualNetwork *bool `json:"forvirtualnetwork,omitempty" doc:"list by network type; true if need to list vms using Virtual Network, false otherwise"`
GroupID string `json:"groupid,omitempty" doc:"the group ID"`
HostID string `json:"hostid,omitempty" doc:"the host ID"`
Hypervisor string `json:"hypervisor,omitempty" doc:"the target hypervisor for the template"`
ID string `json:"id,omitempty" doc:"the ID of the virtual machine"`
IDs []string `json:"ids,omitempty" doc:"the IDs of the virtual machines, mutually exclusive with id"`
IPAddress net.IP `json:"ipaddress,omitempty" doc:"an IP address to filter the result"`
IsoID string `json:"isoid,omitempty" doc:"list vms by iso"`
IsRecursive *bool `json:"isrecursive,omitempty" doc:"defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves."`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
ListAll *bool `json:"listall,omitempty" doc:"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"`
Name string `json:"name,omitempty" doc:"name of the virtual machine"`
NetworkID string `json:"networkid,omitempty" doc:"list by network id"`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
ServiceOfferindID string `json:"serviceofferingid,omitempty" doc:"list by the service offering"`
State string `json:"state,omitempty" doc:"state of the virtual machine"`
Tags []ResourceTag `json:"tags,omitempty" doc:"List resources by tags (key/value pairs)"`
TemplateID string `json:"templateid,omitempty" doc:"list vms by template"`
ZoneID string `json:"zoneid,omitempty" doc:"the availability zone ID"`
_ bool `name:"listVirtualMachines" description:"List the virtual machines owned by the account."`
}
// ListVirtualMachinesResponse represents a list of virtual machines
type ListVirtualMachinesResponse struct {
Count int `json:"count"`
VirtualMachine []VirtualMachine `json:"virtualmachine"`
}
func (ListVirtualMachines) response() interface{} {
return new(ListVirtualMachinesResponse)
}
// SetPage sets the current page
func (ls *ListVirtualMachines) SetPage(page int) {
ls.Page = page
}
// SetPageSize sets the page size
func (ls *ListVirtualMachines) SetPageSize(pageSize int) {
ls.PageSize = pageSize
}
func (ListVirtualMachines) each(resp interface{}, callback IterateItemFunc) {
vms, ok := resp.(*ListVirtualMachinesResponse)
if !ok {
callback(nil, fmt.Errorf("wrong type. ListVirtualMachinesResponse expected, got %T", resp))
return
}
for i := range vms.VirtualMachine {
if !callback(&vms.VirtualMachine[i], nil) {
break
}
}
}
// AddNicToVirtualMachine (Async) adds a NIC to a VM
type AddNicToVirtualMachine struct {
NetworkID string `json:"networkid" doc:"Network ID"`
VirtualMachineID string `json:"virtualmachineid" doc:"Virtual Machine ID"`
IPAddress net.IP `json:"ipaddress,omitempty" doc:"IP Address for the new network"`
_ bool `name:"addNicToVirtualMachine" description:"Adds VM to specified network by creating a NIC"`
}
func (AddNicToVirtualMachine) response() interface{} {
return new(AsyncJobResult)
}
func (AddNicToVirtualMachine) asyncResponse() interface{} {
return new(VirtualMachine)
}
// RemoveNicFromVirtualMachine (Async) removes a NIC from a VM
type RemoveNicFromVirtualMachine struct {
NicID string `json:"nicid" doc:"NIC ID"`
VirtualMachineID string `json:"virtualmachineid" doc:"Virtual Machine ID"`
_ bool `name:"removeNicFromVirtualMachine" description:"Removes VM from specified network by deleting a NIC"`
}
func (RemoveNicFromVirtualMachine) response() interface{} {
return new(AsyncJobResult)
}
func (RemoveNicFromVirtualMachine) asyncResponse() interface{} {
return new(VirtualMachine)
}
// UpdateDefaultNicForVirtualMachine (Async) adds a NIC to a VM
type UpdateDefaultNicForVirtualMachine struct {
NicID string `json:"nicid" doc:"NIC ID"`
VirtualMachineID string `json:"virtualmachineid" doc:"Virtual Machine ID"`
_ bool `name:"updateDefaultNicForVirtualMachine" description:"Changes the default NIC on a VM"`
}
func (UpdateDefaultNicForVirtualMachine) response() interface{} {
return new(AsyncJobResult)
}
func (UpdateDefaultNicForVirtualMachine) asyncResponse() interface{} {
return new(VirtualMachine)
}
// GetVirtualMachineUserData returns the user-data of the given VM
type GetVirtualMachineUserData struct {
VirtualMachineID string `json:"virtualmachineid" doc:"The ID of the virtual machine"`
_ bool `name:"getVirtualMachineUserData" description:"Returns user data associated with the VM"`
}
func (GetVirtualMachineUserData) response() interface{} {
return new(VirtualMachineUserData)
}
// Decode decodes the base64 / gzipped encoded user data
// MigrateVirtualMachine (Async) attempts migration of a VM to a different host or Root volume of the vm to a different storage pool
type MigrateVirtualMachine struct {
HostID string `json:"hostid,omitempty" doc:"Destination Host ID to migrate VM to. Required for live migrating a VM from host to host"`
StorageID string `json:"storageid,omitempty" doc:"Destination storage pool ID to migrate VM volumes to. Required for migrating the root disk volume"`
VirtualMachineID string `json:"virtualmachineid" doc:"the ID of the virtual machine"`
_ bool `name:"migrateVirtualMachine" description:"Attempts Migration of a VM to a different host or Root volume of the vm to a different storage pool"`
}
func (MigrateVirtualMachine) response() interface{} {
return new(AsyncJobResult)
}
func (MigrateVirtualMachine) asyncResponse() interface{} {
return new(VirtualMachine)
}

68
vendor/github.com/exoscale/egoscale/vm_groups.go generated vendored Normal file
View file

@ -0,0 +1,68 @@
package egoscale
// InstanceGroup represents a group of VM
type InstanceGroup struct {
Account string `json:"account,omitempty" doc:"the account owning the instance group"`
Created string `json:"created,omitempty" doc:"time and date the instance group was created"`
Domain string `json:"domain,omitempty" doc:"the domain name of the instance group"`
DomainID string `json:"domainid,omitempty" doc:"the domain ID of the instance group"`
ID string `json:"id,omitempty" doc:"the id of the instance group"`
Name string `json:"name,omitempty" doc:"the name of the instance group"`
}
// CreateInstanceGroup creates a VM group
type CreateInstanceGroup struct {
Name string `json:"name" doc:"the name of the instance group"`
Account string `json:"account,omitempty" doc:"the account of the instance group. The account parameter must be used with the domainId parameter."`
DomainID string `json:"domainid,omitempty" doc:"the domain ID of account owning the instance group"`
_ bool `name:"createInstanceGroup" description:"Creates a vm group"`
}
func (CreateInstanceGroup) response() interface{} {
return new(InstanceGroup)
}
// UpdateInstanceGroup updates a VM group
type UpdateInstanceGroup struct {
ID string `json:"id" doc:"Instance group ID"`
Name string `json:"name,omitempty" doc:"new instance group name"`
_ bool `name:"updateInstanceGroup" description:"Updates a vm group"`
}
func (UpdateInstanceGroup) response() interface{} {
return new(InstanceGroup)
}
// DeleteInstanceGroup deletes a VM group
type DeleteInstanceGroup struct {
ID string `json:"id" doc:"the ID of the instance group"`
_ bool `name:"deleteInstanceGroup" description:"Deletes a vm group"`
}
func (DeleteInstanceGroup) response() interface{} {
return new(booleanResponse)
}
// ListInstanceGroups lists VM groups
type ListInstanceGroups struct {
Account string `json:"account,omitempty" doc:"list resources by account. Must be used with the domainId parameter."`
DomainID string `json:"domainid,omitempty" doc:"list only resources belonging to the domain specified"`
ID string `json:"id,omitempty" doc:"list instance groups by ID"`
IsRecursive *bool `json:"isrecursive,omitempty" doc:"defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves."`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
ListAll *bool `json:"listall,omitempty" doc:"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"`
Name string `json:"name,omitempty" doc:"list instance groups by name"`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
_ bool `name:"listInstanceGroups" description:"Lists vm groups"`
}
// ListInstanceGroupsResponse represents a list of instance groups
type ListInstanceGroupsResponse struct {
Count int `json:"count"`
InstanceGroup []InstanceGroup `json:"instancegroup"`
}
func (ListInstanceGroups) response() interface{} {
return new(ListInstanceGroupsResponse)
}

154
vendor/github.com/exoscale/egoscale/volumes.go generated vendored Normal file
View file

@ -0,0 +1,154 @@
package egoscale
import (
"fmt"
)
// Volume represents a volume linked to a VM
type Volume struct {
Account string `json:"account,omitempty" doc:"the account associated with the disk volume"`
Attached string `json:"attached,omitempty" doc:"the date the volume was attached to a VM instance"`
ChainInfo string `json:"chaininfo,omitempty" doc:"the chain info of the volume"`
ClusterID string `json:"clusterid,omitempty" doc:"ID of the cluster"`
ClusterName string `json:"clustername,omitempty" doc:"name of the cluster"`
Created string `json:"created,omitempty" doc:"the date the disk volume was created"`
Destroyed bool `json:"destroyed,omitempty" doc:"the boolean state of whether the volume is destroyed or not"`
DeviceID int64 `json:"deviceid,omitempty" doc:"the ID of the device on user vm the volume is attahed to. This tag is not returned when the volume is detached."`
DiskBytesReadRate int64 `json:"diskBytesReadRate,omitempty" doc:"bytes read rate of the disk volume"`
DiskBytesWriteRate int64 `json:"diskBytesWriteRate,omitempty" doc:"bytes write rate of the disk volume"`
DiskIopsReadRate int64 `json:"diskIopsReadRate,omitempty" doc:"io requests read rate of the disk volume"`
DiskIopsWriteRate int64 `json:"diskIopsWriteRate,omitempty" doc:"io requests write rate of the disk volume"`
DiskOfferingDisplayText string `json:"diskofferingdisplaytext,omitempty" doc:"the display text of the disk offering"`
DiskOfferingID string `json:"diskofferingid,omitempty" doc:"ID of the disk offering"`
DiskOfferingName string `json:"diskofferingname,omitempty" doc:"name of the disk offering"`
DisplayVolume bool `json:"displayvolume,omitempty" doc:"an optional field whether to the display the volume to the end user or not."`
Domain string `json:"domain,omitempty" doc:"the domain associated with the disk volume"`
DomainID string `json:"domainid,omitempty" doc:"the ID of the domain associated with the disk volume"`
Hypervisor string `json:"hypervisor,omitempty" doc:"Hypervisor the volume belongs to"`
ID string `json:"id,omitempty" doc:"ID of the disk volume"`
IsExtractable *bool `json:"isextractable,omitempty" doc:"true if the volume is extractable, false otherwise"`
IsoDisplayText string `json:"isodisplaytext,omitempty" doc:"an alternate display text of the ISO attached to the virtual machine"`
IsoID string `json:"isoid,omitempty" doc:"the ID of the ISO attached to the virtual machine"`
IsoName string `json:"isoname,omitempty" doc:"the name of the ISO attached to the virtual machine"`
MaxIops int64 `json:"maxiops,omitempty" doc:"max iops of the disk volume"`
MinIops int64 `json:"miniops,omitempty" doc:"min iops of the disk volume"`
Name string `json:"name,omitempty" doc:"name of the disk volume"`
Path string `json:"path,omitempty" doc:"the path of the volume"`
PodID string `json:"podid,omitempty" doc:"ID of the pod"`
PodName string `json:"podname,omitempty" doc:"name of the pod"`
QuiesceVM bool `json:"quiescevm,omitempty" doc:"need quiesce vm or not when taking snapshot"`
ServiceOfferingDisplayText string `json:"serviceofferingdisplaytext,omitempty" doc:"the display text of the service offering for root disk"`
ServiceOfferingID string `json:"serviceofferingid,omitempty" doc:"ID of the service offering for root disk"`
ServiceOfferingName string `json:"serviceofferingname,omitempty" doc:"name of the service offering for root disk"`
Size uint64 `json:"size,omitempty" doc:"size of the disk volume"`
SnapshotID string `json:"snapshotid,omitempty" doc:"ID of the snapshot from which this volume was created"`
State string `json:"state,omitempty" doc:"the state of the disk volume"`
Status string `json:"status,omitempty" doc:"the status of the volume"`
Storage string `json:"storage,omitempty" doc:"name of the primary storage hosting the disk volume"`
StorageID string `json:"storageid,omitempty" doc:"id of the primary storage hosting the disk volume; returned to admin user only"`
StorageType string `json:"storagetype,omitempty" doc:"shared or local storage"`
Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with volume"`
TemplateDisplayText string `json:"templatedisplaytext,omitempty" doc:"an alternate display text of the template for the virtual machine"`
TemplateID string `json:"templateid,omitempty" doc:"the ID of the template for the virtual machine. A -1 is returned if the virtual machine was created from an ISO file."`
TemplateName string `json:"templatename,omitempty" doc:"the name of the template for the virtual machine"`
Type string `json:"type,omitempty" doc:"type of the disk volume (ROOT or DATADISK)"`
VirtualMachineID string `json:"virtualmachineid,omitempty" doc:"id of the virtual machine"`
VMDisplayName string `json:"vmdisplayname,omitempty" doc:"display name of the virtual machine"`
VMName string `json:"vmname,omitempty" doc:"name of the virtual machine"`
VMState string `json:"vmstate,omitempty" doc:"state of the virtual machine"`
ZoneID string `json:"zoneid,omitempty" doc:"ID of the availability zone"`
ZoneName string `json:"zonename,omitempty" doc:"name of the availability zone"`
}
// ResourceType returns the type of the resource
func (Volume) ResourceType() string {
return "Volume"
}
// ListRequest builds the ListVolumes request
func (vol Volume) ListRequest() (ListCommand, error) {
req := &ListVolumes{
Account: vol.Account,
DomainID: vol.DomainID,
Name: vol.Name,
Type: vol.Type,
VirtualMachineID: vol.VirtualMachineID,
ZoneID: vol.ZoneID,
}
return req, nil
}
// ResizeVolume (Async) resizes a volume
type ResizeVolume struct {
ID string `json:"id" doc:"the ID of the disk volume"`
DiskOfferingID string `json:"diskofferingid,omitempty" doc:"new disk offering id"`
ShrinkOk *bool `json:"shrinkok,omitempty" doc:"Verify OK to Shrink"`
Size int64 `json:"size,omitempty" doc:"New volume size in G"`
_ bool `name:"resizeVolume" description:"Resizes a volume"`
}
func (ResizeVolume) response() interface{} {
return new(AsyncJobResult)
}
func (ResizeVolume) asyncResponse() interface{} {
return new(Volume)
}
// ListVolumes represents a query listing volumes
type ListVolumes struct {
Account string `json:"account,omitempty" doc:"list resources by account. Must be used with the domainId parameter."`
DiskOfferingID string `json:"diskofferingid,omitempty" doc:"list volumes by disk offering"`
DisplayVolume *bool `json:"displayvolume,omitempty" doc:"list resources by display flag; only ROOT admin is eligible to pass this parameter"`
DomainID string `json:"domainid,omitempty" doc:"list only resources belonging to the domain specified"`
HostID string `json:"hostid,omitempty" doc:"list volumes on specified host"`
ID string `json:"id,omitempty" doc:"the ID of the disk volume"`
IsRecursive *bool `json:"isrecursive,omitempty" doc:"defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves."`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
ListAll *bool `json:"listall,omitempty" doc:"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"`
Name string `json:"name,omitempty" doc:"the name of the disk volume"`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
PodID string `json:"podid,omitempty" doc:"the pod id the disk volume belongs to"`
StorageID string `json:"storageid,omitempty" doc:"the ID of the storage pool, available to ROOT admin only"`
Tags []ResourceTag `json:"tags,omitempty" doc:"List resources by tags (key/value pairs)"`
Type string `json:"type,omitempty" doc:"the type of disk volume"`
VirtualMachineID string `json:"virtualmachineid,omitempty" doc:"the ID of the virtual machine"`
ZoneID string `json:"zoneid,omitempty" doc:"the ID of the availability zone"`
_ bool `name:"listVolumes" description:"Lists all volumes."`
}
// ListVolumesResponse represents a list of volumes
type ListVolumesResponse struct {
Count int `json:"count"`
Volume []Volume `json:"volume"`
}
func (ListVolumes) response() interface{} {
return new(ListVolumesResponse)
}
// SetPage sets the current page
func (ls *ListVolumes) SetPage(page int) {
ls.Page = page
}
// SetPageSize sets the page size
func (ls *ListVolumes) SetPageSize(pageSize int) {
ls.PageSize = pageSize
}
func (ListVolumes) each(resp interface{}, callback IterateItemFunc) {
volumes, ok := resp.(*ListVolumesResponse)
if !ok {
callback(nil, fmt.Errorf("wrong type. ListVolumesResponse expected, got %T", resp))
return
}
for i := range volumes.Volume {
if !callback(&volumes.Volume[i], nil) {
break
}
}
}

94
vendor/github.com/exoscale/egoscale/zones.go generated vendored Normal file
View file

@ -0,0 +1,94 @@
package egoscale
import (
"fmt"
"net"
)
// Zone represents a data center
//
// TODO: represent correctly the capacity field.
type Zone struct {
AllocationState string `json:"allocationstate,omitempty" doc:"the allocation state of the cluster"`
Description string `json:"description,omitempty" doc:"Zone description"`
DhcpProvider string `json:"dhcpprovider,omitempty" doc:"the dhcp Provider for the Zone"`
DisplayText string `json:"displaytext,omitempty" doc:"the display text of the zone"`
DNS1 net.IP `json:"dns1,omitempty" doc:"the first DNS for the Zone"`
DNS2 net.IP `json:"dns2,omitempty" doc:"the second DNS for the Zone"`
Domain string `json:"domain,omitempty" doc:"Network domain name for the networks in the zone"`
DomainID string `json:"domainid,omitempty" doc:"the UUID of the containing domain, null for public zones"`
DomainName string `json:"domainname,omitempty" doc:"the name of the containing domain, null for public zones"`
GuestCidrAddress string `json:"guestcidraddress,omitempty" doc:"the guest CIDR address for the Zone"`
ID string `json:"id,omitempty" doc:"Zone id"`
InternalDNS1 net.IP `json:"internaldns1,omitempty" doc:"the first internal DNS for the Zone"`
InternalDNS2 net.IP `json:"internaldns2,omitempty" doc:"the second internal DNS for the Zone"`
IP6DNS1 net.IP `json:"ip6dns1,omitempty" doc:"the first IPv6 DNS for the Zone"`
IP6DNS2 net.IP `json:"ip6dns2,omitempty" doc:"the second IPv6 DNS for the Zone"`
LocalStorageEnabled *bool `json:"localstorageenabled,omitempty" doc:"true if local storage offering enabled, false otherwise"`
Name string `json:"name,omitempty" doc:"Zone name"`
NetworkType string `json:"networktype,omitempty" doc:"the network type of the zone; can be Basic or Advanced"`
ResourceDetails map[string]string `json:"resourcedetails,omitempty" doc:"Meta data associated with the zone (key/value pairs)"`
SecurityGroupsEnabled *bool `json:"securitygroupsenabled,omitempty" doc:"true if security groups support is enabled, false otherwise"`
Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with zone."`
Vlan string `json:"vlan,omitempty" doc:"the vlan range of the zone"`
ZoneToken string `json:"zonetoken,omitempty" doc:"Zone Token"`
}
// ListRequest builds the ListZones request
func (zone Zone) ListRequest() (ListCommand, error) {
req := &ListZones{
DomainID: zone.DomainID,
ID: zone.ID,
Name: zone.Name,
}
return req, nil
}
// ListZones represents a query for zones
type ListZones struct {
Available *bool `json:"available,omitempty" doc:"true if you want to retrieve all available Zones. False if you only want to return the Zones from which you have at least one VM. Default is false."`
DomainID string `json:"domainid,omitempty" doc:"the ID of the domain associated with the zone"`
ID string `json:"id,omitempty" doc:"the ID of the zone"`
Keyword string `json:"keyword,omitempty" doc:"List by keyword"`
Name string `json:"name,omitempty" doc:"the name of the zone"`
Page int `json:"page,omitempty"`
PageSize int `json:"pagesize,omitempty"`
ShowCapacities *bool `json:"showcapacities,omitempty" doc:"flag to display the capacity of the zones"`
Tags []ResourceTag `json:"tags,omitempty" doc:"List zones by resource tags (key/value pairs)"`
_ bool `name:"listZones" description:"Lists zones"`
}
// ListZonesResponse represents a list of zones
type ListZonesResponse struct {
Count int `json:"count"`
Zone []Zone `json:"zone"`
}
func (ListZones) response() interface{} {
return new(ListZonesResponse)
}
// SetPage sets the current page
func (ls *ListZones) SetPage(page int) {
ls.Page = page
}
// SetPageSize sets the page size
func (ls *ListZones) SetPageSize(pageSize int) {
ls.PageSize = pageSize
}
func (ListZones) each(resp interface{}, callback IterateItemFunc) {
zones, ok := resp.(*ListZonesResponse)
if !ok {
callback(nil, fmt.Errorf("wrong type. ListZonesResponse was expected, got %T", resp))
return
}
for i := range zones.Zone {
if !callback(&zones.Zone[i], nil) {
break
}
}
}

6
vendor/vendor.json vendored
View file

@ -223,6 +223,12 @@
"revision": "234ec949d37c6b7f18d669d45191d30db2c49fb3",
"revisionTime": "2018-10-01T13:03:57Z"
},
{
"checksumSHA1": "qMqL9tE//Z4n/4BQqyjSQ9RdoB8=",
"path": "github.com/exoscale/egoscale",
"revision": "d0b97c5313da1645585ba6c860e29161299849e1",
"revisionTime": "2018-08-02T11:57:13Z"
},
{
"checksumSHA1": "oSwR5RN8idtBQrpnQSy13t8ruoU=",
"path": "github.com/go-ini/ini",