Merge pull request #3660 from StackPointCloud/packer-builder-profitbricks

Packer Builder ProfitBricks
This commit is contained in:
Matthew Hooker 2016-10-31 15:45:24 -07:00 committed by GitHub
commit 01be917450
33 changed files with 3156 additions and 0 deletions

View File

@ -0,0 +1,33 @@
package profitbricks
import (
"fmt"
)
type Artifact struct {
snapshotData string
}
func (*Artifact) BuilderId() string {
return BuilderId
}
func (a *Artifact) Files() []string {
return []string{}
}
func (*Artifact) Id() string {
return "Null"
}
func (a *Artifact) String() string {
return fmt.Sprintf("A snapshot was created: '%v'", a.snapshotData)
}
func (a *Artifact) State(name string) interface{} {
return nil
}
func (a *Artifact) Destroy() error {
return nil
}

View File

@ -0,0 +1,24 @@
package profitbricks
import (
"testing"
"github.com/mitchellh/packer/packer"
)
func TestArtifact_Impl(t *testing.T) {
var raw interface{}
raw = &Artifact{}
if _, ok := raw.(packer.Artifact); !ok {
t.Fatalf("Artifact should be artifact")
}
}
func TestArtifactString(t *testing.T) {
a := &Artifact{"packer-foobar"}
expected := "A snapshot was created: 'packer-foobar'"
if a.String() != expected {
t.Fatalf("artifact string should match: %v", expected)
}
}

View File

@ -0,0 +1,79 @@
package profitbricks
import (
"fmt"
"github.com/mitchellh/multistep"
"github.com/mitchellh/packer/common"
"github.com/mitchellh/packer/helper/communicator"
"github.com/mitchellh/packer/packer"
"log"
)
const BuilderId = "packer.profitbricks"
type Builder struct {
config *Config
runner multistep.Runner
}
func (b *Builder) Prepare(raws ...interface{}) ([]string, error) {
c, warnings, errs := NewConfig(raws...)
if errs != nil {
return warnings, errs
}
b.config = c
return warnings, nil
}
func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) {
steps := []multistep.Step{
&StepCreateSSHKey{
Debug: b.config.PackerDebug,
DebugKeyPath: fmt.Sprintf("pb_%s", b.config.SnapshotName),
},
new(stepCreateServer),
&communicator.StepConnect{
Config: &b.config.Comm,
Host: commHost,
SSHConfig: sshConfig,
},
&common.StepProvision{},
new(stepTakeSnapshot),
}
state := new(multistep.BasicStateBag)
state.Put("config", b.config)
state.Put("hook", hook)
state.Put("ui", ui)
config := state.Get("config").(*Config)
if b.config.PackerDebug {
b.runner = &multistep.DebugRunner{
Steps: steps,
PauseFn: common.MultistepDebugFn(ui),
}
} else {
b.runner = &multistep.BasicRunner{Steps: steps}
}
b.runner.Run(state)
if rawErr, ok := state.GetOk("error"); ok {
return nil, rawErr.(error)
}
artifact := &Artifact{
snapshotData: config.SnapshotName,
}
return artifact, nil
}
func (b *Builder) Cancel() {
if b.runner != nil {
log.Println("Cancelling the step runner...")
b.runner.Cancel()
}
}

View File

@ -0,0 +1,38 @@
package profitbricks
import (
"os"
"testing"
builderT "github.com/mitchellh/packer/helper/builder/testing"
)
func TestBuilderAcc_basic(t *testing.T) {
builderT.Test(t, builderT.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Builder: &Builder{},
Template: testBuilderAccBasic,
})
}
func testAccPreCheck(t *testing.T) {
if v := os.Getenv("PROFITBRICKS_USERNAME"); v == "" {
t.Fatal("PROFITBRICKS_USERNAME must be set for acceptance tests")
}
if v := os.Getenv("PROFITBRICKS_PASSWORD"); v == "" {
t.Fatal("PROFITBRICKS_PASSWORD must be set for acceptance tests")
}
}
const testBuilderAccBasic = `
{
"builders": [{
"image": "Ubuntu-16.04",
"password": "password",
"username": "username",
"snapshot_name": "packer",
"type": "profitbricks"
}]
}
`

View File

@ -0,0 +1,56 @@
package profitbricks
import (
"fmt"
"github.com/mitchellh/packer/packer"
"testing"
)
func testConfig() map[string]interface{} {
return map[string]interface{}{
"image": "Ubuntu-16.04",
"password": "password",
"username": "username",
"snapshot_name": "packer",
"type": "profitbricks",
}
}
func TestImplementsBuilder(t *testing.T) {
var raw interface{}
raw = &Builder{}
if _, ok := raw.(packer.Builder); !ok {
t.Fatalf("Builder should be a builder")
}
}
func TestBuilder_Prepare_BadType(t *testing.T) {
b := &Builder{}
c := map[string]interface{}{
"api_key": []string{},
}
warns, err := b.Prepare(c)
if len(warns) > 0 {
t.Fatalf("bad: %#v", warns)
}
if err == nil {
fmt.Println(err)
fmt.Println(warns)
t.Fatalf("prepare should fail")
}
}
func TestBuilderPrepare_InvalidKey(t *testing.T) {
var b Builder
config := testConfig()
config["i_should_not_be_valid"] = true
warnings, err := b.Prepare(config)
if len(warnings) > 0 {
t.Fatalf("bad: %#v", warnings)
}
if err == nil {
t.Fatal("should have error")
}
}

View File

@ -0,0 +1,129 @@
package profitbricks
import (
"errors"
"github.com/mitchellh/mapstructure"
"github.com/mitchellh/packer/common"
"github.com/mitchellh/packer/helper/communicator"
"github.com/mitchellh/packer/helper/config"
"github.com/mitchellh/packer/packer"
"github.com/mitchellh/packer/template/interpolate"
"os"
)
type Config struct {
common.PackerConfig `mapstructure:",squash"`
Comm communicator.Config `mapstructure:",squash"`
PBUsername string `mapstructure:"username"`
PBPassword string `mapstructure:"password"`
PBUrl string `mapstructure:"url"`
Region string `mapstructure:"location"`
Image string `mapstructure:"image"`
SSHKey string
SSHKey_path string `mapstructure:"ssh_key_path"`
SnapshotName string `mapstructure:"snapshot_name"`
SnapshotPassword string `mapstructure:"snapshot_password"`
DiskSize int `mapstructure:"disk_size"`
DiskType string `mapstructure:"disk_type"`
Cores int `mapstructure:"cores"`
Ram int `mapstructure:"ram"`
Timeout int `mapstructure:"timeout"`
CommConfig communicator.Config `mapstructure:",squash"`
ctx interpolate.Context
}
func NewConfig(raws ...interface{}) (*Config, []string, error) {
var c Config
var md mapstructure.Metadata
err := config.Decode(&c, &config.DecodeOpts{
Metadata: &md,
Interpolate: true,
InterpolateContext: &c.ctx,
InterpolateFilter: &interpolate.RenderFilter{
Exclude: []string{
"run_command",
},
},
}, raws...)
if err != nil {
return nil, nil, err
}
var errs *packer.MultiError
if c.Comm.SSHUsername == "" {
c.Comm.SSHUsername = "root"
}
c.Comm.SSHPort = 22
if c.SnapshotName == "" {
def, err := interpolate.Render("packer-{{timestamp}}", nil)
if err != nil {
panic(err)
}
// Default to packer-{{ unix timestamp (utc) }}
c.SnapshotName = def
}
if c.PBUsername == "" {
c.PBUsername = os.Getenv("PROFITBRICKS_USERNAME")
}
if c.PBPassword == "" {
c.PBPassword = os.Getenv("PROFITBRICKS_PASSWORD")
}
if c.PBUrl == "" {
c.PBUrl = "https://api.profitbricks.com/rest/v2"
}
if c.Image == "" {
c.Image = "Ubuntu-16.04"
}
if c.Cores == 0 {
c.Cores = 4
}
if c.Ram == 0 {
c.Ram = 2048
}
if c.DiskSize == 0 {
c.DiskSize = 50
}
if c.Region == "" {
c.Region = "us/las"
}
if c.DiskType == "" {
c.DiskType = "HDD"
}
if es := c.Comm.Prepare(&c.ctx); len(es) > 0 {
errs = packer.MultiErrorAppend(errs, es...)
}
c.Comm.SSHPort = 22
if c.PBUsername == "" {
errs = packer.MultiErrorAppend(
errs, errors.New("ProfitBricks username is required"))
}
if c.PBPassword == "" {
errs = packer.MultiErrorAppend(
errs, errors.New("ProfitBricks password is required"))
}
if errs != nil && len(errs.Errors) > 0 {
return nil, nil, errs
}
common.ScrubConfig(c, c.PBUsername)
return &c, nil, nil
}

View File

@ -0,0 +1,29 @@
package profitbricks
import (
"fmt"
"github.com/mitchellh/multistep"
"golang.org/x/crypto/ssh"
)
func commHost(state multistep.StateBag) (string, error) {
ipAddress := state.Get("server_ip").(string)
return ipAddress, nil
}
func sshConfig(state multistep.StateBag) (*ssh.ClientConfig, error) {
config := state.Get("config").(*Config)
privateKey := state.Get("privateKey").(string)
signer, err := ssh.ParsePrivateKey([]byte(privateKey))
if err != nil {
return nil, fmt.Errorf("Error setting up SSH config: %s", err)
}
return &ssh.ClientConfig{
User: config.Comm.SSHUsername,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
}, nil
}

View File

@ -0,0 +1,214 @@
package profitbricks
import (
"encoding/json"
"errors"
"fmt"
"github.com/mitchellh/multistep"
"github.com/mitchellh/packer/packer"
"github.com/profitbricks/profitbricks-sdk-go"
"strconv"
"strings"
"time"
)
type stepCreateServer struct{}
func (s *stepCreateServer) Run(state multistep.StateBag) multistep.StepAction {
ui := state.Get("ui").(packer.Ui)
c := state.Get("config").(*Config)
profitbricks.SetAuth(c.PBUsername, c.PBPassword)
profitbricks.SetDepth("5")
c.SSHKey = state.Get("publicKey").(string)
ui.Say("Creating Virtual Data Center...")
img := s.getImageId(c.Image, c)
datacenter := profitbricks.Datacenter{
Properties: profitbricks.DatacenterProperties{
Name: c.SnapshotName,
Location: c.Region,
},
Entities: profitbricks.DatacenterEntities{
Servers: &profitbricks.Servers{
Items: []profitbricks.Server{
{
Properties: profitbricks.ServerProperties{
Name: c.SnapshotName,
Ram: c.Ram,
Cores: c.Cores,
},
Entities: &profitbricks.ServerEntities{
Volumes: &profitbricks.Volumes{
Items: []profitbricks.Volume{
{
Properties: profitbricks.VolumeProperties{
Type: c.DiskType,
Size: c.DiskSize,
Name: c.SnapshotName,
Image: img,
SshKeys: []string{c.SSHKey},
ImagePassword: c.SnapshotPassword,
},
},
},
},
},
},
},
},
},
}
datacenter = profitbricks.CompositeCreateDatacenter(datacenter)
if datacenter.StatusCode > 299 {
if datacenter.StatusCode > 299 {
var restError RestError
json.Unmarshal([]byte(datacenter.Response), &restError)
if ( len(restError.Messages) > 0) {
ui.Error(restError.Messages[0].Message)
} else {
ui.Error(datacenter.Response)
}
return multistep.ActionHalt
}
}
s.waitTillProvisioned(datacenter.Headers.Get("Location"), *c)
state.Put("datacenter_id", datacenter.Id)
lan := profitbricks.CreateLan(datacenter.Id, profitbricks.Lan{
Properties: profitbricks.LanProperties{
Public: true,
Name: c.SnapshotName,
},
})
if lan.StatusCode > 299 {
ui.Error(fmt.Sprintf("Error occured %s", parseErrorMessage(lan.Response)))
return multistep.ActionHalt
}
s.waitTillProvisioned(lan.Headers.Get("Location"), *c)
lanId, _ := strconv.Atoi(lan.Id)
nic := profitbricks.CreateNic(datacenter.Id, datacenter.Entities.Servers.Items[0].Id, profitbricks.Nic{
Properties: profitbricks.NicProperties{
Name: c.SnapshotName,
Lan: lanId,
Dhcp: true,
},
})
if lan.StatusCode > 299 {
ui.Error(fmt.Sprintf("Error occured %s", parseErrorMessage(nic.Response)))
return multistep.ActionHalt
}
s.waitTillProvisioned(nic.Headers.Get("Location"), *c)
state.Put("volume_id", datacenter.Entities.Servers.Items[0].Entities.Volumes.Items[0].Id)
server := profitbricks.GetServer(datacenter.Id, datacenter.Entities.Servers.Items[0].Id)
state.Put("server_ip", server.Entities.Nics.Items[0].Properties.Ips[0])
return multistep.ActionContinue
}
func (s *stepCreateServer) Cleanup(state multistep.StateBag) {
c := state.Get("config").(*Config)
ui := state.Get("ui").(packer.Ui)
ui.Say("Removing Virtual Data Center...")
profitbricks.SetAuth(c.PBUsername, c.PBPassword)
if dcId, ok := state.GetOk("datacenter_id"); ok {
resp := profitbricks.DeleteDatacenter(dcId.(string))
s.checkForErrors(resp)
err := s.waitTillProvisioned(resp.Headers.Get("Location"), *c)
if err != nil {
ui.Error(fmt.Sprintf(
"Error deleting Virtual Data Center. Please destroy it manually: %s", err))
}
}
}
func (d *stepCreateServer) waitTillProvisioned(path string, config Config) error {
d.setPB(config.PBUsername, config.PBPassword, config.PBUrl)
waitCount := 120
if config.Timeout > 0 {
waitCount = config.Timeout
}
for i := 0; i < waitCount; i++ {
request := profitbricks.GetRequestStatus(path)
if request.Metadata.Status == "DONE" {
return nil
}
if request.Metadata.Status == "FAILED" {
return errors.New(request.Metadata.Message)
}
time.Sleep(1 * time.Second)
i++
}
return nil
}
func (d *stepCreateServer) setPB(username string, password string, url string) {
profitbricks.SetAuth(username, password)
profitbricks.SetEndpoint(url)
}
func (d *stepCreateServer) checkForErrors(instance profitbricks.Resp) error {
if instance.StatusCode > 299 {
return errors.New(fmt.Sprintf("Error occured %s", string(instance.Body)))
}
return nil
}
type RestError struct {
HttpStatus int `json:"httpStatus,omitempty"`
Messages []Message`json:"messages,omitempty"`
}
type Message struct {
ErrorCode string `json:"errorCode,omitempty"`
Message string`json:"message,omitempty"`
}
func (d *stepCreateServer) getImageId(imageName string, c *Config) string {
d.setPB(c.PBUsername, c.PBPassword, c.PBUrl)
images := profitbricks.ListImages()
for i := 0; i < len(images.Items); i++ {
imgName := ""
if images.Items[i].Properties.Name != "" {
imgName = images.Items[i].Properties.Name
}
diskType := c.DiskType
if c.DiskType == "SSD" {
diskType = "HDD"
}
if imgName != "" && strings.Contains(strings.ToLower(imgName), strings.ToLower(imageName)) && images.Items[i].Properties.ImageType == diskType && images.Items[i].Properties.Location == c.Region && images.Items[i].Properties.Public == true {
return images.Items[i].Id
}
}
return ""
}
func parseErrorMessage(raw string) (toreturn string) {
var tmp map[string]interface{}
json.Unmarshal([]byte(raw), &tmp)
for _, v := range tmp["messages"].([]interface{}) {
for index, i := range v.(map[string]interface{}) {
if index == "message" {
toreturn = toreturn + i.(string) + "\n"
}
}
}
return toreturn
}

View File

@ -0,0 +1,105 @@
package profitbricks
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"os"
"github.com/mitchellh/multistep"
"github.com/mitchellh/packer/packer"
"golang.org/x/crypto/ssh"
"io/ioutil"
)
type StepCreateSSHKey struct {
Debug bool
DebugKeyPath string
}
func (s *StepCreateSSHKey) Run(state multistep.StateBag) multistep.StepAction {
ui := state.Get("ui").(packer.Ui)
c := state.Get("config").(*Config)
if c.SSHKey_path == "" {
ui.Say("Creating temporary SSH key for instance...")
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
err := fmt.Errorf("Error creating temporary ssh key: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
priv_blk := pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: x509.MarshalPKCS1PrivateKey(priv),
}
pub, err := ssh.NewPublicKey(&priv.PublicKey)
if err != nil {
err := fmt.Errorf("Error creating temporary ssh key: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
state.Put("privateKey", string(pem.EncodeToMemory(&priv_blk)))
state.Put("publicKey", string(ssh.MarshalAuthorizedKey(pub)))
ui.Message(fmt.Sprintf("Saving key to: %s", s.DebugKeyPath))
f, err := os.Create(s.DebugKeyPath)
if err != nil {
state.Put("error", fmt.Errorf("Error saving debug key: %s", err))
return multistep.ActionHalt
}
f.Chmod(os.FileMode(int(0700)))
err = pem.Encode(f, &priv_blk)
f.Close()
if err != nil {
state.Put("error", fmt.Errorf("Error saving debug key: %s", err))
return multistep.ActionHalt
}
} else {
ui.Say(c.SSHKey_path)
pemBytes, err := ioutil.ReadFile(c.SSHKey_path)
if err != nil {
ui.Error(err.Error())
return multistep.ActionHalt
}
block, _ := pem.Decode(pemBytes)
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
err := fmt.Errorf("Error creating temporary ssh key: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
priv_blk := pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: x509.MarshalPKCS1PrivateKey(priv),
}
pub, err := ssh.NewPublicKey(&priv.PublicKey)
if err != nil {
err := fmt.Errorf("Error creating temporary ssh key: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
state.Put("privateKey", string(pem.EncodeToMemory(&priv_blk)))
state.Put("publicKey", string(ssh.MarshalAuthorizedKey(pub)))
}
return multistep.ActionContinue
}
func (s *StepCreateSSHKey) Cleanup(state multistep.StateBag) {}

View File

@ -0,0 +1,76 @@
package profitbricks
import (
"errors"
"fmt"
"github.com/mitchellh/multistep"
"github.com/mitchellh/packer/packer"
"github.com/profitbricks/profitbricks-sdk-go"
"time"
"encoding/json"
)
type stepTakeSnapshot struct{}
func (s *stepTakeSnapshot) Run(state multistep.StateBag) multistep.StepAction {
ui := state.Get("ui").(packer.Ui)
c := state.Get("config").(*Config)
ui.Say("Creating ProfitBricks snapshot...")
profitbricks.SetAuth(c.PBUsername, c.PBPassword)
dcId := state.Get("datacenter_id").(string)
volumeId := state.Get("volume_id").(string)
snapshot := profitbricks.CreateSnapshot(dcId, volumeId, c.SnapshotName)
state.Put("snapshotname", c.SnapshotName)
if snapshot.StatusCode > 299 {
var restError RestError
json.Unmarshal([]byte(snapshot.Response), &restError)
if ( len(restError.Messages) > 0) {
ui.Error(restError.Messages[0].Message)
} else {
ui.Error(snapshot.Response)
}
return multistep.ActionHalt
}
s.waitTillProvisioned(snapshot.Headers.Get("Location"), *c)
return multistep.ActionContinue
}
func (s *stepTakeSnapshot) Cleanup(state multistep.StateBag) {
}
func (d *stepTakeSnapshot) checkForErrors(instance profitbricks.Resp) error {
if instance.StatusCode > 299 {
return errors.New(fmt.Sprintf("Error occured %s", string(instance.Body)))
}
return nil
}
func (d *stepTakeSnapshot) waitTillProvisioned(path string, config Config) {
d.setPB(config.PBUsername, config.PBPassword, config.PBUrl)
waitCount := 50
if config.Timeout > 0 {
waitCount = config.Timeout
}
for i := 0; i < waitCount; i++ {
request := profitbricks.GetRequestStatus(path)
if request.Metadata.Status == "DONE" {
break
}
time.Sleep(10 * time.Second)
i++
}
}
func (d *stepTakeSnapshot) setPB(username string, password string, url string) {
profitbricks.SetAuth(username, password)
profitbricks.SetEndpoint(url)
}

View File

@ -26,6 +26,7 @@ import (
openstackbuilder "github.com/mitchellh/packer/builder/openstack"
parallelsisobuilder "github.com/mitchellh/packer/builder/parallels/iso"
parallelspvmbuilder "github.com/mitchellh/packer/builder/parallels/pvm"
profitbricksbuilder "github.com/mitchellh/packer/builder/profitbricks"
qemubuilder "github.com/mitchellh/packer/builder/qemu"
virtualboxisobuilder "github.com/mitchellh/packer/builder/virtualbox/iso"
virtualboxovfbuilder "github.com/mitchellh/packer/builder/virtualbox/ovf"
@ -79,6 +80,7 @@ var Builders = map[string]packer.Builder{
"openstack": new(openstackbuilder.Builder),
"parallels-iso": new(parallelsisobuilder.Builder),
"parallels-pvm": new(parallelspvmbuilder.Builder),
"profitbricks": new(profitbricksbuilder.Builder),
"qemu": new(qemubuilder.Builder),
"virtualbox-iso": new(virtualboxisobuilder.Builder),
"virtualbox-ovf": new(virtualboxovfbuilder.Builder),

View File

@ -0,0 +1,33 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof
/.idea/
.idea/compiler.xml
.idea/copyright/
.idea/encodings.xml
.idea/misc.xml
.idea/modules.xml
.idea/profitbricks-sdk-go.iml
.idea/vcs.xml
.idea/workspace.xml

View File

@ -0,0 +1,202 @@
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 2015 ProfitBricks GmbH
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.

View File

@ -0,0 +1,342 @@
# Go SDK
The ProfitBricks Client Library for [Go](https://www.golang.org/) provides you with access to the ProfitBricks REST API. It is designed for developers who are building applications in Go.
This guide will walk you through getting setup with the library and performing various actions against the API.
# Table of Contents
* [Concepts](#concepts)
* [Getting Started](#getting-started)
* [Installation](#installation)
* [How to: Create Data Center](#how-to-create-data-center)
* [How to: Delete Data Center](#how-to-delete-data-center)
* [How to: Create Server](#how-to-create-server)
* [How to: List Available Images](#how-to-list-available-images)
* [How to: Create Storage Volume](#how-to-create-storage-volume)
* [How to: Update Cores and Memory](#how-to-update-cores-and-memory)
* [How to: Attach or Detach Storage Volume](#how-to-attach-or-detach-storage-volume)
* [How to: List Servers, Volumes, and Data Centers](#how-to-list-servers-volumes-and-data-centers)
* [Example](#example)
* [Return Types](#return-types)
* [Support](#support)
# Concepts
The Go SDK wraps the latest version of the ProfitBricks REST API. All API operations are performed over SSL and authenticated using your ProfitBricks portal credentials. The API can be accessed within an instance running in ProfitBricks or directly over the Internet from any application that can send an HTTPS request and receive an HTTPS response.
# Getting Started
Before you begin you will need to have [signed-up](https://www.profitbricks.com/signup) for a ProfitBricks account. The credentials you setup during sign-up will be used to authenticate against the API.
Install the Go language from: [Go Installation](https://golang.org/doc/install)
The `GOPATH` environment variable specifies the location of your Go workspace. It is likely the only environment variable you'll need to set when developing Go code. This is an example of pointing to a workspace configured underneath your home directory:
```
mkdir -p ~/go/bin
export GOPATH=~/go
export GOBIN=$GOPATH/bin
export PATH=$PATH:$GOBIN
```
# Installation
The following go command will download `profitbricks-sdk-go` to your configured `GOPATH`:
```go
go get "github.com/profitbricks/profitbricks-sdk-go"
```
The source code of the package will be located at:
$GOBIN\src\profitbricks-sdk-go
Create main package file *example.go*:
```go
package main
import (
"fmt"
)
func main() {
}
```
Import GO SDK:
```go
import(
"github.com/profitbricks/profitbricks-sdk-go"
)
```
Add your credentials for connecting to ProfitBricks:
```go
profitbricks.SetAuth("username", "password")
```
Set depth:
```go
profitbricks.SetDepth("5")
```
Depth controls the amount of data returned from the REST server ( range 1-5 ). The larger the number the more information is returned from the server. This is especially useful if you are looking for the information in the nested objects.
**Caution**: You will want to ensure you follow security best practices when using credentials within your code or stored in a file.
# How To's
## How To: Create Data Center
ProfitBricks introduces the concept of Data Centers. These are logically separated from one another and allow you to have a self-contained environment for all servers, volumes, networking, snapshots, and so forth. The goal is to give you the same experience as you would have if you were running your own physical data center.
The following code example shows you how to programmatically create a data center:
```go
dcrequest := profitbricks.Datacenter{
Properties: profitbricks.DatacenterProperties{
Name: "example.go3",
Description: "description",
Location: "us/lasdev",
},
}
datacenter := profitbricks.CreateDatacenter(dcrequest)
```
## How To: Create Data Center with Multiple Resources
To create a complex Data Center you would do this. As you can see, you can create quite a few of the objects you will need later all in one request.:
```go
datacenter := model.Datacenter{
Properties: model.DatacenterProperties{
Name: "composite test",
Location:location,
},
Entities:model.DatacenterEntities{
Servers: &model.Servers{
Items:[]model.Server{
model.Server{
Properties: model.ServerProperties{
Name : "server1",
Ram: 2048,
Cores: 1,
},
Entities:model.ServerEntities{
Volumes: &model.AttachedVolumes{
Items:[]model.Volume{
model.Volume{
Properties: model.VolumeProperties{
Type_:"HDD",
Size:10,
Name:"volume1",
Image:"1f46a4a3-3f47-11e6-91c6-52540005ab80",
Bus:"VIRTIO",
ImagePassword:"test1234",
SshKeys: []string{"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCoLVLHON4BSK3D8L4H79aFo..."},
},
},
},
},
Nics: &model.Nics{
Items: []model.Nic{
model.Nic{
Properties: model.NicProperties{
Name : "nic",
Lan : "1",
},
},
},
},
},
},
},
},
},
}
dc := CompositeCreateDatacenter(datacenter)
```
## How To: Delete Data Center
You will want to exercise a bit of caution here. Removing a data center will destroy all objects contained within that data center -- servers, volumes, snapshots, and so on.
The code to remove a data center is as follows. This example assumes you want to remove previously data center:
```go
profitbricks.DeleteDatacenter(response.Id)
```
## How To: Create Server
The server create method has a list of required parameters followed by a hash of optional parameters. The optional parameters are specified within the "options" hash and the variable names match the [REST API](https://devops.profitbricks.com/api/rest/) parameters.
The following example shows you how to create a new server in the data center created above:
```go
req := profitbricks.Server{
Properties: profitbricks.ServerProperties{
Name: "go01",
Ram: 1024,
Cores: 2,
},
}
server := CreateServer(datacenter.Id, req)
```
## How To: List Available Images
A list of disk and ISO images are available from ProfitBricks for immediate use. These can be easily viewed and selected. The following shows you how to get a list of images. This list represents both CDROM images and HDD images.
```go
images := profitbricks.ListImages()
```
This will return a [collection](#Collection) object
## How To: Create Storage Volume
ProfitBricks allows for the creation of multiple storage volumes that can be attached and detached as needed. It is useful to attach an image when creating a storage volume. The storage size is in gigabytes.
```go
volumerequest := profitbricks.Volume{
Properties: profitbricks.VolumeProperties{
Size: 1,
Name: "Volume Test",
LicenceType: "LINUX",
Type: "HDD",
},
}
storage := CreateVolume(datacenter.Id, volumerequest)
```
## How To: Update Cores and Memory
ProfitBricks allows users to dynamically update cores, memory, and disk independently of each other. This removes the restriction of needing to upgrade to the next size available size to receive an increase in memory. You can now simply increase the instances memory keeping your costs in-line with your resource needs.
Note: The memory parameter value must be a multiple of 256, e.g. 256, 512, 768, 1024, and so forth.
The following code illustrates how you can update cores and memory:
```go
serverupdaterequest := profitbricks.ServerProperties{
Cores: 1,
Ram: 256,
}
resp := PatchServer(datacenter.Id, server.Id, serverupdaterequest)
```
## How To: Attach or Detach Storage Volume
ProfitBricks allows for the creation of multiple storage volumes. You can detach and reattach these on the fly. This allows for various scenarios such as re-attaching a failed OS disk to another server for possible recovery or moving a volume to another location and spinning it up.
The following illustrates how you would attach and detach a volume and CDROM to/from a server:
```go
profitbricks.AttachVolume(datacenter.Id, server.Id, volume.Id)
profitbricks.AttachCdrom(datacenter.Id, server.Id, images.Items[0].Id)
profitbricks.DetachVolume(datacenter.Id, server.Id, volume.Id)
profitbricks.DetachCdrom(datacenter.Id, server.Id, images.Items[0].Id)
```
## How To: List Servers, Volumes, and Data Centers
Go SDK provides standard functions for retrieving a list of volumes, servers, and datacenters.
The following code illustrates how to pull these three list types:
```go
volumes := profitbricks.ListVolumes(datacenter.Id)
servers := profitbricks.ListServers(datacenter.Id)
datacenters := profitbricks.ListDatacenters()
```
## Example
```go
package main
import (
"fmt"
"time"
"github.com/profitbricks/profitbricks-sdk-go"
)
func main() {
//Sets username and password
profitbricks.SetAuth("username", "password")
//Sets depth.
profitbricks.SetDepth("5")
dcrequest := profitbricks.Datacenter{
Properties: profitbricks.DatacenterProperties{
Name: "example.go3",
Description: "description",
Location: "us/lasdev",
},
}
datacenter := profitbricks.CreateDatacenter(dcrequest)
serverrequest := profitbricks.Server{
Properties: profitbricks.ServerProperties{
Name: "go01",
Ram: 1024,
Cores: 2,
},
}
server := profitbricks.CreateServer(datacenter.Id, serverrequest)
volumerequest := profitbricks.Volume{
Properties: profitbricks.VolumeProperties{
Size: 1,
Name: "Volume Test",
LicenceType: "LINUX",
Type: "HDD",
},
}
storage := profitbricks.CreateVolume(datacenter.Id, volumerequest)
serverupdaterequest := profitbricks.ServerProperties{
Name: "go01renamed",
Cores: 1,
Ram: 256,
}
profitbricks.PatchServer(datacenter.Id, server.Id, serverupdaterequest)
//It takes a moment for a volume to be provisioned so we wait.
time.Sleep(60 * time.Second)
profitbricks.AttachVolume(datacenter.Id, server.Id, storage.Id)
volumes := profitbricks.ListVolumes(datacenter.Id)
fmt.Println(volumes.Items)
servers := profitbricks.ListServers(datacenter.Id)
fmt.Println(servers.Items)
datacenters := profitbricks.ListDatacenters()
fmt.Println(datacenters.Items)
profitbricks.DeleteServer(datacenter.Id, server.Id)
profitbricks.DeleteDatacenter(datacenter.Id)
}
```
# Support
You are welcome to contact us with questions or comments at [ProfitBricks DevOps Central](https://devops.profitbricks.com/). Please report any issues via [GitHub's issue tracker](https://github.com/profitbricks/profitbricks-sdk-go/issues).

View File

@ -0,0 +1,23 @@
package profitbricks
// Endpoint is the base url for REST requests .
var Endpoint = "https://api.profitbricks.com/rest/v2"
// Username for authentication .
var Username string
// Password for authentication .
var Passwd string
// SetEndpoint is used to set the REST Endpoint. Endpoint is declared in config.go
func SetEndpoint(newendpoint string) string {
Endpoint = newendpoint
return Endpoint
}
// SetAuth is used to set Username and Passwd. Username and Passwd are declared in config.go
func SetAuth(u, p string) {
Username = u
Passwd = p
}

View File

@ -0,0 +1,121 @@
package profitbricks
import (
"bytes"
"encoding/json"
"net/http"
"time"
)
type Datacenter struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Metadata *DatacenterElementMetadata `json:"metadata,omitempty"`
Properties DatacenterProperties `json:"properties,omitempty"`
Entities DatacenterEntities `json:"entities,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
type DatacenterElementMetadata struct {
CreatedDate time.Time `json:"createdDate,omitempty"`
CreatedBy string `json:"createdBy,omitempty"`
Etag string `json:"etag,omitempty"`
LastModifiedDate time.Time `json:"lastModifiedDate,omitempty"`
LastModifiedBy string `json:"lastModifiedBy,omitempty"`
State string `json:"state,omitempty"`
}
type DatacenterProperties struct {
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Location string `json:"location,omitempty"`
Version int32 `json:"version,omitempty"`
}
type DatacenterEntities struct {
Servers *Servers `json:"servers,omitempty"`
Volumes *Volumes `json:"volumes,omitempty"`
Loadbalancers *Loadbalancers `json:"loadbalancers,omitempty"`
Lans *Lans `json:"lans,omitempty"`
}
type Datacenters struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Items []Datacenter `json:"items,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
func ListDatacenters() Datacenters {
path := dc_col_path()
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
resp := do(req)
return toDataCenters(resp)
}
func CreateDatacenter(dc Datacenter) Datacenter {
obj, _ := json.Marshal(dc)
path := dc_col_path()
url := mk_url(path)
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(obj))
req.Header.Add("Content-Type", FullHeader)
return toDataCenter(do(req))
}
func CompositeCreateDatacenter(datacenter Datacenter) Datacenter {
obj, _ := json.Marshal(datacenter)
path := dc_col_path()
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(obj))
req.Header.Add("Content-Type", FullHeader)
return toDataCenter(do(req))
}
func GetDatacenter(dcid string) Datacenter {
path := dc_path(dcid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
return toDataCenter(do(req))
}
func PatchDatacenter(dcid string, obj DatacenterProperties) Datacenter {
jason_patch := []byte(MkJson(obj))
path := dc_path(dcid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(jason_patch))
req.Header.Add("Content-Type", PatchHeader)
return toDataCenter(do(req))
}
func DeleteDatacenter(dcid string) Resp {
path := dc_path(dcid)
return is_delete(path)
}
func toDataCenter(resp Resp) Datacenter {
var dc Datacenter
json.Unmarshal(resp.Body, &dc)
dc.Response = string(resp.Body)
dc.Headers = &resp.Headers
dc.StatusCode = resp.StatusCode
return dc
}
func toDataCenters(resp Resp) Datacenters {
var col Datacenters
json.Unmarshal(resp.Body, &col)
col.Response = string(resp.Body)
col.Headers = &resp.Headers
col.StatusCode = resp.StatusCode
return col
}

View File

@ -0,0 +1,6 @@
/*
Package profitbricks is a client library for interacting with Profitbricks RESTful APIs.
*/
package profitbricks

View File

@ -0,0 +1,99 @@
package profitbricks
import (
"bytes"
"encoding/json"
"net/http"
)
type FirewallRule struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Metadata *DatacenterElementMetadata `json:"metadata,omitempty"`
Properties FirewallruleProperties `json:"properties,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
type FirewallruleProperties struct {
Name string `json:"name,omitempty"`
Protocol string `json:"protocol,omitempty"`
SourceMac string `json:"sourceMac,omitempty"`
SourceIp string `json:"sourceIp,omitempty"`
TargetIp string `json:"targetIp,omitempty"`
IcmpCode int `json:"icmpCode,omitempty"`
IcmpType int `json:"icmpType,omitempty"`
PortRangeStart int `json:"portRangeStart,omitempty"`
PortRangeEnd int `json:"portRangeEnd,omitempty"`
}
type FirewallRules struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Items []FirewallRule `json:"items,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
func ListFirewallRules(dcId string, serverid string, nicId string) FirewallRules {
path := fwrule_col_path(dcId, serverid, nicId)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
resp := do(req)
return toFirewallRules(resp)
}
func GetFirewallRule(dcid string, srvid string, nicId string, fwId string) FirewallRule {
path := fwrule_path(dcid, srvid, nicId, fwId)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
resp := do(req)
return toFirewallRule(resp)
}
func CreateFirewallRule(dcid string, srvid string, nicId string, fw FirewallRule) FirewallRule {
path := fwrule_col_path(dcid, srvid, nicId)
url := mk_url(path) + `?depth=` + Depth
obj, _ := json.Marshal(fw)
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(obj))
req.Header.Add("Content-Type", FullHeader)
return toFirewallRule(do(req))
}
func PatchFirewallRule(dcid string, srvid string, nicId string, fwId string, obj FirewallruleProperties) FirewallRule {
jason_patch := []byte(MkJson(obj))
path := fwrule_path(dcid, srvid, nicId, fwId)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(jason_patch))
req.Header.Add("Content-Type", PatchHeader)
return toFirewallRule(do(req))
}
func DeleteFirewallRule(dcid string, srvid string, nicId string, fwId string) Resp {
path := fwrule_path(dcid, srvid, nicId, fwId)
return is_delete(path)
}
func toFirewallRule(resp Resp) FirewallRule {
var dc FirewallRule
json.Unmarshal(resp.Body, &dc)
dc.Response = string(resp.Body)
dc.Headers = &resp.Headers
dc.StatusCode = resp.StatusCode
return dc
}
func toFirewallRules(resp Resp) FirewallRules {
var col FirewallRules
json.Unmarshal(resp.Body, &col)
col.Response = string(resp.Body)
col.Headers = &resp.Headers
col.StatusCode = resp.StatusCode
return col
}

View File

@ -0,0 +1,98 @@
package profitbricks
import (
"encoding/json"
"net/http"
)
type Image struct {
Id string `json:"id,omitempty"`
Type string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Metadata *DatacenterElementMetadata `json:"metadata,omitempty"`
Properties ImageProperties `json:"properties,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
type ImageProperties struct {
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Location string `json:"location,omitempty"`
Size int `json:"size,omitempty"`
CpuHotPlug bool `json:"cpuHotPlug,omitempty"`
CpuHotUnplug bool `json:"cpuHotUnplug,omitempty"`
RamHotPlug bool `json:"ramHotPlug,omitempty"`
RamHotUnplug bool `json:"ramHotUnplug,omitempty"`
NicHotPlug bool `json:"nicHotPlug,omitempty"`
NicHotUnplug bool `json:"nicHotUnplug,omitempty"`
DiscVirtioHotPlug bool `json:"discVirtioHotPlug,omitempty"`
DiscVirtioHotUnplug bool `json:"discVirtioHotUnplug,omitempty"`
DiscScsiHotPlug bool `json:"discScsiHotPlug,omitempty"`
DiscScsiHotUnplug bool `json:"discScsiHotUnplug,omitempty"`
LicenceType string `json:"licenceType,omitempty"`
ImageType string `json:"imageType,omitempty"`
Public bool `json:"public,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
type Images struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Items []Image `json:"items,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
type Cdroms struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Items []Image `json:"items,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
// ListImages returns an Collection struct
func ListImages() Images {
path := image_col_path()
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
resp := do(req)
return toImages(resp)
}
// GetImage returns an Instance struct where id ==imageid
func GetImage(imageid string) Image {
path := image_path(imageid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
resp := do(req)
return toImage(resp)
}
func toImage(resp Resp) Image {
var image Image
json.Unmarshal(resp.Body, &image)
image.Response = string(resp.Body)
image.Headers = &resp.Headers
image.StatusCode = resp.StatusCode
return image
}
func toImages(resp Resp) Images {
var col Images
json.Unmarshal(resp.Body, &col)
col.Response = string(resp.Body)
col.Headers = &resp.Headers
col.StatusCode = resp.StatusCode
return col
}

View File

@ -0,0 +1,82 @@
package profitbricks
import (
"bytes"
"encoding/json"
"net/http"
)
type IpBlock struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Metadata *DatacenterElementMetadata `json:"metadata,omitempty"`
Properties IpBlockProperties `json:"properties,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
type IpBlockProperties struct {
Ips []string `json:"ips,omitempty"`
Location string `json:"location,omitempty"`
Size int `json:"size,omitempty"`
}
type IpBlocks struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Items []IpBlock `json:"items,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
// ListIpBlocks
func ListIpBlocks() IpBlocks {
path := ipblock_col_path()
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
return toIpBlocks(do(req))
}
func ReserveIpBlock(request IpBlock) IpBlock {
obj, _ := json.Marshal(request)
path := ipblock_col_path()
url := mk_url(path)
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(obj))
req.Header.Add("Content-Type", FullHeader)
return toIpBlock(do(req))
}
func GetIpBlock(ipblockid string) IpBlock {
path := ipblock_path(ipblockid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
return toIpBlock(do(req))
}
func ReleaseIpBlock(ipblockid string) Resp {
path := ipblock_path(ipblockid)
return is_delete(path)
}
func toIpBlock(resp Resp) IpBlock {
var obj IpBlock
json.Unmarshal(resp.Body, &obj)
obj.Response = string(resp.Body)
obj.Headers = &resp.Headers
obj.StatusCode = resp.StatusCode
return obj
}
func toIpBlocks(resp Resp) IpBlocks {
var col IpBlocks
json.Unmarshal(resp.Body, &col)
col.Response = string(resp.Body)
col.Headers = &resp.Headers
col.StatusCode = resp.StatusCode
return col
}

View File

@ -0,0 +1,109 @@
package profitbricks
import (
"bytes"
"encoding/json"
"net/http"
)
type Lan struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Metadata *DatacenterElementMetadata `json:"metadata,omitempty"`
Properties LanProperties `json:"properties,omitempty"`
Entities *LanEntities `json:"entities,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
type LanProperties struct {
Name string `json:"name,omitempty"`
Public bool `json:"public,omitempty"`
}
type LanEntities struct {
Nics *LanNics `json:"nics,omitempty"`
}
type LanNics struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Items []Nic `json:"items,omitempty"`
}
type Lans struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Items []Lan `json:"items,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
// ListLan returns a Collection for lans in the Datacenter
func ListLans(dcid string) Lans {
path := lan_col_path(dcid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
return toLans(do(req))
}
// CreateLan creates a lan in the datacenter
// from a jason []byte and returns a Instance struct
func CreateLan(dcid string, request Lan) Lan {
obj, _ := json.Marshal(request)
path := lan_col_path(dcid)
url := mk_url(path)
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(obj))
req.Header.Add("Content-Type", FullHeader)
return toLan(do(req))
}
// GetLan pulls data for the lan where id = lanid returns an Instance struct
func GetLan(dcid, lanid string) Lan {
path := lan_path(dcid, lanid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
return toLan(do(req))
}
// PatchLan does a partial update to a lan using json from []byte jason
// returns a Instance struct
func PatchLan(dcid string, lanid string, obj LanProperties) Lan {
jason := []byte(MkJson(obj))
path := lan_path(dcid, lanid)
url := mk_url(path)
req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(jason))
req.Header.Add("Content-Type", PatchHeader)
return toLan(do(req))
}
// DeleteLan deletes a lan where id == lanid
func DeleteLan(dcid, lanid string) Resp {
path := lan_path(dcid, lanid)
return is_delete(path)
}
func toLan(resp Resp) Lan {
var lan Lan
json.Unmarshal(resp.Body, &lan)
lan.Response = string(resp.Body)
lan.Headers = &resp.Headers
lan.StatusCode = resp.StatusCode
return lan
}
func toLans(resp Resp) Lans {
var col Lans
json.Unmarshal(resp.Body, &col)
col.Response = string(resp.Body)
col.Headers = &resp.Headers
col.StatusCode = resp.StatusCode
return col
}

View File

@ -0,0 +1,145 @@
package profitbricks
import (
"bytes"
"encoding/json"
"net/http"
)
type Loadbalancer struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Metadata *DatacenterElementMetadata `json:"metadata,omitempty"`
Properties LoadbalancerProperties `json:"properties,omitempty"`
Entities LoadbalancerEntities `json:"entities,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
type LoadbalancerProperties struct {
Name string `json:"name,omitempty"`
Ip string `json:"ip,omitempty"`
Dhcp bool `json:"dhcp,omitempty"`
}
type LoadbalancerEntities struct {
Balancednics *BalancedNics `json:"balancednics,omitempty"`
}
type BalancedNics struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Items []Nic `json:"items,omitempty"`
}
type Loadbalancers struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Items []Loadbalancer `json:"items,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
type LoablanacerCreateRequest struct {
LoadbalancerProperties `json:"properties"`
}
// Listloadbalancers returns a Collection struct
// for loadbalancers in the Datacenter
func ListLoadbalancers(dcid string) Loadbalancers {
path := lbal_col_path(dcid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
return toLoadbalancers(do(req))
}
// Createloadbalancer creates a loadbalancer in the datacenter
//from a jason []byte and returns a Instance struct
func CreateLoadbalancer(dcid string, request Loadbalancer) Loadbalancer {
obj, _ := json.Marshal(request)
path := lbal_col_path(dcid)
url := mk_url(path)
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(obj))
req.Header.Add("Content-Type", FullHeader)
return toLoadbalancer(do(req))
}
// GetLoadbalancer pulls data for the Loadbalancer
// where id = lbalid returns a Instance struct
func GetLoadbalancer(dcid, lbalid string) Loadbalancer {
path := lbal_path(dcid, lbalid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
return toLoadbalancer(do(req))
}
func PatchLoadbalancer(dcid string, lbalid string, obj LoadbalancerProperties) Loadbalancer {
jason := []byte(MkJson(obj))
path := lbal_path(dcid, lbalid)
url := mk_url(path)
req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(jason))
req.Header.Add("Content-Type", PatchHeader)
return toLoadbalancer(do(req))
}
func DeleteLoadbalancer(dcid, lbalid string) Resp {
path := lbal_path(dcid, lbalid)
return is_delete(path)
}
func ListBalancedNics(dcid, lbalid string) Nics {
path := balnic_col_path(dcid, lbalid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
return toNics(do(req))
}
func AssociateNic(dcid string, lbalid string, nicid string) Nic {
sm := map[string]string{"id": nicid}
jason := []byte(MkJson(sm))
path := balnic_col_path(dcid, lbalid)
url := mk_url(path)
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jason))
req.Header.Add("Content-Type", FullHeader)
return toNic(do(req))
}
func GetBalancedNic(dcid, lbalid, balnicid string) Nic {
path := balnic_path(dcid, lbalid, balnicid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
return toNic(do(req))
}
func DeleteBalancedNic(dcid, lbalid, balnicid string) Resp {
path := balnic_path(dcid, lbalid, balnicid)
return is_delete(path)
}
func toLoadbalancer(resp Resp) Loadbalancer {
var server Loadbalancer
json.Unmarshal(resp.Body, &server)
server.Response = string(resp.Body)
server.Headers = &resp.Headers
server.StatusCode = resp.StatusCode
return server
}
func toLoadbalancers(resp Resp) Loadbalancers {
var col Loadbalancers
json.Unmarshal(resp.Body, &col)
col.Response = string(resp.Body)
col.Headers = &resp.Headers
col.StatusCode = resp.StatusCode
return col
}

View File

@ -0,0 +1,65 @@
package profitbricks
import (
"encoding/json"
"net/http"
)
type Location struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Metadata DatacenterElementMetadata `json:"metadata,omitempty"`
Properties Properties `json:"properties,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
type Locations struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Items []Location `json:"items,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
type Properties struct {
Name string `json:"name,omitempty"`
}
// ListLocations returns location collection data
func ListLocations() Locations {
url := mk_url(location_col_path()) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
return toLocations(do(req))
}
// GetLocation returns location data
func GetLocation(locid string) Location {
url := mk_url(location_path(locid)) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
return toLocation(do(req))
}
func toLocation(resp Resp) Location {
var obj Location
json.Unmarshal(resp.Body, &obj)
obj.Response = string(resp.Body)
obj.Headers = &resp.Headers
obj.StatusCode = resp.StatusCode
return obj
}
func toLocations(resp Resp) Locations {
var col Locations
json.Unmarshal(resp.Body, &col)
col.Response = string(resp.Body)
col.Headers = &resp.Headers
col.StatusCode = resp.StatusCode
return col
}

View File

@ -0,0 +1,110 @@
package profitbricks
import (
"bytes"
"encoding/json"
"net/http"
)
type Nic struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Metadata *DatacenterElementMetadata `json:"metadata,omitempty"`
Properties NicProperties `json:"properties,omitempty"`
Entities *NicEntities `json:"entities,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
type NicProperties struct {
Name string `json:"name,omitempty"`
Mac string `json:"mac,omitempty"`
Ips []string `json:"ips,omitempty"`
Dhcp bool `json:"dhcp,omitempty"`
Lan int `json:"lan,omitempty"`
FirewallActive bool `json:"firewallActive,omitempty"`
}
type NicEntities struct {
Firewallrules *FirewallRules `json:"firewallrules,omitempty"`
}
type Nics struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Items []Nic `json:"items,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
type NicCreateRequest struct {
NicProperties `json:"properties"`
}
// ListNics returns a Nics struct collection
func ListNics(dcid, srvid string) Nics {
path := nic_col_path(dcid, srvid) + `?depth=` + Depth
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
return toNics(do(req))
}
// CreateNic creates a nic on a server
// from a jason []byte and returns a Instance struct
func CreateNic(dcid string, srvid string, request Nic) Nic {
obj, _ := json.Marshal(request)
path := nic_col_path(dcid, srvid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(obj))
req.Header.Add("Content-Type", FullHeader)
return toNic(do(req))
}
// GetNic pulls data for the nic where id = srvid returns a Instance struct
func GetNic(dcid, srvid, nicid string) Nic {
path := nic_path(dcid, srvid, nicid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
return toNic(do(req))
}
// PatchNic partial update of nic properties passed in as jason []byte
// Returns Instance struct
func PatchNic(dcid string, srvid string, nicid string, obj NicProperties) Nic {
jason := []byte(MkJson(obj))
path := nic_path(dcid, srvid, nicid)
url := mk_url(path)
req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(jason))
req.Header.Add("Content-Type", PatchHeader)
return toNic(do(req))
}
// DeleteNic deletes the nic where id=nicid and returns a Resp struct
func DeleteNic(dcid, srvid, nicid string) Resp {
path := nic_path(dcid, srvid, nicid)
return is_delete(path)
}
func toNic(resp Resp) Nic {
var obj Nic
json.Unmarshal(resp.Body, &obj)
obj.Response = string(resp.Body)
obj.Headers = &resp.Headers
obj.StatusCode = resp.StatusCode
return obj
}
func toNics(resp Resp) Nics {
var col Nics
json.Unmarshal(resp.Body, &col)
col.Response = string(resp.Body)
col.Headers = &resp.Headers
col.StatusCode = resp.StatusCode
return col
}

View File

@ -0,0 +1,173 @@
package profitbricks
// slash returns "/<str>" great for making url paths
func slash(str string) string {
return "/" + str
}
// dc_col_path returns the string "/datacenters"
func dc_col_path() string {
return slash("datacenters")
}
// dc_path returns the string "/datacenters/<dcid>"
func dc_path(dcid string) string {
return dc_col_path() + slash(dcid)
}
// image_col_path returns the string" /images"
func image_col_path() string {
return slash("images")
}
// image_path returns the string"/images/<imageid>"
func image_path(imageid string) string {
return image_col_path() + slash(imageid)
}
// ipblock_col_path returns the string "/ipblocks"
func ipblock_col_path() string {
return slash("ipblocks")
}
// ipblock_path returns the string "/ipblocks/<ipblockid>"
func ipblock_path(ipblockid string) string {
return ipblock_col_path() + slash(ipblockid)
}
// location_col_path returns the string "/locations"
func location_col_path() string {
return slash("locations")
}
// location_path returns the string "/locations/<locid>"
func location_path(locid string) string {
return location_col_path() + slash(locid)
}
// request_col_path returns the string "/requests"
func request_col_path() string {
return slash("requests")
}
// request_path returns the string "/requests/<requestid>"
func request_path(requestid string) string {
return request_col_path() + slash(requestid)
}
// request_status_path returns the string "/requests<requestid>/status"
func request_status_path(requestid string) string {
return request_path(requestid) + slash("status")
}
// snapshot_col_path returns the string "/snapshots"
func snapshot_col_path() string {
return slash("snapshots")
}
// snapshot_path returns the string "/snapshots/<snapid>"
func snapshot_path(snapid string) string {
return snapshot_col_path() + slash(snapid)
}
// lan_col_path returns the string "/datacenters/<dcid>/lans"
func lan_col_path(dcid string) string {
return dc_path(dcid) + slash("lans")
}
// lan_path returns the string "/datacenters/<dcid>/lans/<lanid>"
func lan_path(dcid, lanid string) string {
return lan_col_path(dcid) + slash(lanid)
}
// lbal_col_path returns the string "/loadbalancers"
func lbal_col_path(dcid string) string {
return dc_path(dcid) + slash("loadbalancers")
}
// lbalpath returns the string "/loadbalancers/<lbalid>"
func lbal_path(dcid, lbalid string) string {
return lbal_col_path(dcid) + slash(lbalid)
}
// server_col_path returns the string "/datacenters/<dcid>/servers"
func server_col_path(dcid string) string {
return dc_path(dcid) + slash("servers")
}
// server_path returns the string "/datacenters/<dcid>/servers/<srvid>"
func server_path(dcid, srvid string) string {
return server_col_path(dcid) + slash(srvid)
}
// server_cmd_path returns the string "/datacenters/<dcid>/servers/<srvid>/<cmd>"
func server_command_path(dcid, srvid, cmd string) string {
return server_path(dcid, srvid) + slash(cmd)
}
// volume_col_path returns the string "/volumes"
func volume_col_path(dcid string) string {
return dc_path(dcid) + slash("volumes")
}
// volume_path returns the string "/volumes/<volid>"
func volume_path(dcid, volid string) string {
return volume_col_path(dcid) + slash(volid)
}
// lan_nic_col_path returns the string /datacenters/<dcid>/lans/<lanid>/nics
func lan_nic_col(dcid, lanid string) string {
return lan_path(dcid, lanid) + slash("nics")
}
// balnic_col_path returns the string "/loadbalancers/<lbalid>/balancednics"
func balnic_col_path(dcid, lbalid string) string {
return lbal_path(dcid, lbalid) + slash("balancednics")
}
// balnic_path returns the string "/loadbalancers/<lbalid>/balancednics<balnicid>"
func balnic_path(dcid, lbalid, balnicid string) string {
return balnic_col_path(dcid, lbalid) + slash(balnicid)
}
// server_cdrom_col_path returns the string "/datacenters/<dcid>/servers/<srvid>/cdroms"
func server_cdrom_col_path(dcid, srvid string) string {
return server_path(dcid, srvid) + slash("cdroms")
}
// server_cdrom_path returns the string "/datacenters/<dcid>/servers/<srvid>/cdroms/<cdid>"
func server_cdrom_path(dcid, srvid, cdid string) string {
return server_cdrom_col_path(dcid, srvid) + slash(cdid)
}
// server_volume_col_path returns the string "/datacenters/<dcid>/servers/<srvid>/volumes"
func server_volume_col_path(dcid, srvid string) string {
return server_path(dcid, srvid) + slash("volumes")
}
// server_volume_path returns the string "/datacenters/<dcid>/servers/<srvid>/volumes/<volid>"
func server_volume_path(dcid, srvid, volid string) string {
return server_volume_col_path(dcid, srvid) + slash(volid)
}
// nic_path returns the string "/datacenters/<dcid>/servers/<srvid>/nics"
func nic_col_path(dcid, srvid string) string {
return server_path(dcid, srvid) + slash("nics")
}
// nic_path returns the string "/datacenters/<dcid>/servers/<srvid>/nics/<nicid>"
func nic_path(dcid, srvid, nicid string) string {
return nic_col_path(dcid, srvid) + slash(nicid)
}
// fwrule_col_path returns the string "/datacenters/<dcid>/servers/<srvid>/nics/<nicid>/firewallrules"
func fwrule_col_path(dcid, srvid, nicid string) string {
return nic_path(dcid, srvid, nicid) + slash("firewallrules")
}
// fwrule_path returns the string
// "/datacenters/<dcid>/servers/<srvid>/nics/<nicid>/firewallrules/<fwruleid>"
func fwrule_path(dcid, srvid, nicid, fwruleid string) string {
return fwrule_col_path(dcid, srvid, nicid) + slash(fwruleid)
}

View File

@ -0,0 +1,80 @@
package profitbricks
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"strings"
)
//FullHeader is the standard header to include with all http requests except is_patch and is_command
const FullHeader = "application/vnd.profitbricks.resource+json"
//PatchHeader is used with is_patch .
const PatchHeader = "application/vnd.profitbricks.partial-properties+json"
//CommandHeader is used with is_command
const CommandHeader = "application/x-www-form-urlencoded"
var Depth = "5"
// SetDepth is used to set Depth
func SetDepth(newdepth string) string {
Depth = newdepth
return Depth
}
// mk_url either:
// returns the path (if it`s a full url)
// or
// returns Endpoint+ path .
func mk_url(path string) string {
if strings.HasPrefix(path, "http") {
//REMOVE AFTER TESTING
path := strings.Replace(path, "https://api.profitbricks.com/rest/v2", Endpoint, 1)
// END REMOVE
return path
}
if strings.HasPrefix(path, "<base>") {
//REMOVE AFTER TESTING
path := strings.Replace(path, "<base>", Endpoint, 1)
return path
}
url := Endpoint + path
return url
}
func do(req *http.Request) Resp {
client := &http.Client{}
req.SetBasicAuth(Username, Passwd)
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
resp_body, _ := ioutil.ReadAll(resp.Body)
var R Resp
R.Req = resp.Request
R.Body = resp_body
R.Headers = resp.Header
R.StatusCode = resp.StatusCode
return R
}
// is_delete performs an http.NewRequest DELETE and returns a Resp struct
func is_delete(path string) Resp {
url := mk_url(path)
req, _ := http.NewRequest("DELETE", url, nil)
req.Header.Add("Content-Type", FullHeader)
return do(req)
}
// is_command performs an http.NewRequest POST and returns a Resp struct
func is_command(path string, jason string) Resp {
url := mk_url(path)
body := json.RawMessage(jason)
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(body))
req.Header.Add("Content-Type", CommandHeader)
return do(req)
}

View File

@ -0,0 +1,43 @@
package profitbricks
import (
"encoding/json"
"net/http"
)
type RequestStatus struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Metadata RequestStatusMetadata `json:"metadata,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
type RequestStatusMetadata struct {
Status string `json:"status,omitempty"`
Message string `json:"message,omitempty"`
Etag string `json:"etag,omitempty"`
Targets []RequestTarget `json:"targets,omitempty"`
}
type RequestTarget struct {
Target ResourceReference `json:"target,omitempty"`
Status string `json:"status,omitempty"`
}
func GetRequestStatus(path string) RequestStatus {
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
return toRequestStatus(do(req))
}
func toRequestStatus(resp Resp) RequestStatus {
var server RequestStatus
json.Unmarshal(resp.Body, &server)
server.Response = string(resp.Body)
server.Headers = &resp.Headers
server.StatusCode = resp.StatusCode
return server
}

View File

@ -0,0 +1,61 @@
package profitbricks
import "net/http"
import "fmt"
import (
"encoding/json"
)
func MkJson(i interface{}) string {
jason, err := json.MarshalIndent(&i, "", " ")
if err != nil {
panic(err)
}
// fmt.Println(string(jason))
return string(jason)
}
// MetaData is a map for metadata returned in a Resp.Body
type StringMap map[string]string
type StringIfaceMap map[string]interface{}
type StringCollectionMap map[string]Collection
// Resp is the struct returned by all Rest request functions
type Resp struct {
Req *http.Request
StatusCode int
Headers http.Header
Body []byte
}
// PrintHeaders prints the http headers as k,v pairs
func (r *Resp) PrintHeaders() {
for key, value := range r.Headers {
fmt.Println(key, " : ", value[0])
}
}
type Id_Type_Href struct {
Id string `json:"id"`
Type string `json:"type"`
Href string `json:"href"`
}
type MetaData StringIfaceMap
type Instance struct {
Id_Type_Href
MetaData StringMap `json:"metaData,omitempty"`
Properties StringIfaceMap `json:"properties,omitempty"`
Entities StringCollectionMap `json:"entities,omitempty"`
Resp Resp `json:"-"`
}
type Collection struct {
Id_Type_Href
Items []Instance `json:"items,omitempty"`
Resp Resp `json:"-"`
}

View File

@ -0,0 +1,208 @@
package profitbricks
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
type Server struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Metadata *DatacenterElementMetadata `json:"metadata,omitempty"`
Properties ServerProperties `json:"properties,omitempty"`
Entities *ServerEntities `json:"entities,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
type ServerProperties struct {
Name string `json:"name,omitempty"`
Cores int `json:"cores,omitempty"`
Ram int `json:"ram,omitempty"`
AvailabilityZone string `json:"availabilityZone,omitempty"`
VmState string `json:"vmState,omitempty"`
BootCdrom *ResourceReference `json:"bootCdrom,omitempty"`
BootVolume *ResourceReference `json:"bootVolume,omitempty"`
CpuFamily string `json:"cpuFamily,omitempty"`
}
type ServerEntities struct {
Cdroms *Cdroms `json:"cdroms,omitempty"`
Volumes *Volumes `json:"volumes,omitempty"`
Nics *Nics `json:"nics,omitempty"`
}
type Servers struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Items []Server `json:"items,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
type ResourceReference struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
}
type CreateServerRequest struct {
ServerProperties `json:"properties"`
}
// ListServers returns a server struct collection
func ListServers(dcid string) Servers {
path := server_col_path(dcid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
resp := do(req)
return toServers(resp)
}
// CreateServer creates a server from a jason []byte and returns a Instance struct
func CreateServer(dcid string, server Server) Server {
obj, _ := json.Marshal(server)
path := server_col_path(dcid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(obj))
req.Header.Add("Content-Type", FullHeader)
return toServer(do(req))
}
// GetServer pulls data for the server where id = srvid returns a Instance struct
func GetServer(dcid, srvid string) Server {
path := server_path(dcid, srvid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
fmt.Println(path)
req.Header.Add("Content-Type", FullHeader)
return toServer(do(req))
}
// PatchServer partial update of server properties passed in as jason []byte
// Returns Instance struct
func PatchServer(dcid string, srvid string, props ServerProperties) Server {
jason, _ := json.Marshal(props)
path := server_path(dcid, srvid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(jason))
req.Header.Add("Content-Type", PatchHeader)
return toServer(do(req))
}
// DeleteServer deletes the server where id=srvid and returns Resp struct
func DeleteServer(dcid, srvid string) Resp {
path := server_path(dcid, srvid)
return is_delete(path)
}
func ListAttachedCdroms(dcid, srvid string) Images {
path := server_cdrom_col_path(dcid, srvid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
return toImages(do(req))
}
func AttachCdrom(dcid string, srvid string, cdid string) Image {
jason := []byte(`{"id":"` + cdid + `"}`)
path := server_cdrom_col_path(dcid, srvid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jason))
req.Header.Add("Content-Type", FullHeader)
return toImage(do(req))
}
func GetAttachedCdrom(dcid, srvid, cdid string) Volume {
path := server_cdrom_path(dcid, srvid, cdid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
return toVolume(do(req))
}
func DetachCdrom(dcid, srvid, cdid string) Resp {
path := server_cdrom_path(dcid, srvid, cdid)
return is_delete(path)
}
func ListAttachedVolumes(dcid, srvid string) Volumes {
path := server_volume_col_path(dcid, srvid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
resp := do(req)
return toVolumes(resp)
}
func AttachVolume(dcid string, srvid string, volid string) Volume {
jason := []byte(`{"id":"` + volid + `"}`)
path := server_volume_col_path(dcid, srvid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jason))
req.Header.Add("Content-Type", FullHeader)
return toVolume(do(req))
}
func GetAttachedVolume(dcid, srvid, volid string) Volume {
path := server_volume_path(dcid, srvid, volid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
resp := do(req)
return toVolume(resp)
}
func DetachVolume(dcid, srvid, volid string) Resp {
path := server_volume_path(dcid, srvid, volid)
return is_delete(path)
}
// StartServer starts a server
func StartServer(dcid, srvid string) Resp {
return server_command(dcid, srvid, "start")
}
// StopServer stops a server
func StopServer(dcid, srvid string) Resp {
return server_command(dcid, srvid, "stop")
}
// RebootServer reboots a server
func RebootServer(dcid, srvid string) Resp {
return server_command(dcid, srvid, "reboot")
}
// server_command is a generic function for running server commands
func server_command(dcid, srvid, cmd string) Resp {
jason := `
{}
`
path := server_command_path(dcid, srvid, cmd)
return is_command(path, jason)
}
func toServer(resp Resp) Server {
var server Server
json.Unmarshal(resp.Body, &server)
server.Response = string(resp.Body)
server.Headers = &resp.Headers
server.StatusCode = resp.StatusCode
return server
}
func toServers(resp Resp) Servers {
var col Servers
json.Unmarshal(resp.Body, &col)
col.Response = string(resp.Body)
col.Headers = &resp.Headers
col.StatusCode = resp.StatusCode
return col
}

View File

@ -0,0 +1,96 @@
package profitbricks
import (
"bytes"
"encoding/json"
"net/http"
)
type Snapshot struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Metadata DatacenterElementMetadata `json:"metadata,omitempty"`
Properties SnapshotProperties `json:"properties,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
type SnapshotProperties struct {
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Location string `json:"location,omitempty"`
Size int `json:"size,omitempty"`
CpuHotPlug bool `json:"cpuHotPlug,omitempty"`
CpuHotUnplug bool `json:"cpuHotUnplug,omitempty"`
RamHotPlug bool `json:"ramHotPlug,omitempty"`
RamHotUnplug bool `json:"ramHotUnplug,omitempty"`
NicHotPlug bool `json:"nicHotPlug,omitempty"`
NicHotUnplug bool `json:"nicHotUnplug,omitempty"`
DiscVirtioHotPlug bool `json:"discVirtioHotPlug,omitempty"`
DiscVirtioHotUnplug bool `json:"discVirtioHotUnplug,omitempty"`
DiscScsiHotPlug bool `json:"discScsiHotPlug,omitempty"`
DiscScsiHotUnplug bool `json:"discScsiHotUnplug,omitempty"`
LicenceType string `json:"licenceType,omitempty"`
}
type Snapshots struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Items []Snapshot `json:"items,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
func ListSnapshots() Snapshots {
path := snapshot_col_path()
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
return toSnapshots(do(req))
}
func GetSnapshot(snapshotId string) Snapshot {
path := snapshot_col_path() + slash(snapshotId)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
return toSnapshot(do(req))
}
func DeleteSnapshot(snapshotId string) Resp {
path := snapshot_col_path() + slash(snapshotId)
url := mk_url(path)
req, _ := http.NewRequest("DELETE", url, nil)
req.Header.Add("Content-Type", FullHeader)
return do(req)
}
func UpdateSnapshot(snapshotId string, request SnapshotProperties) Snapshot {
path := snapshot_col_path() + slash(snapshotId)
obj, _ := json.Marshal(request)
url := mk_url(path)
req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(obj))
req.Header.Add("Content-Type", PatchHeader)
return toSnapshot(do(req))
}
func toSnapshot(resp Resp) Snapshot {
var lan Snapshot
json.Unmarshal(resp.Body, &lan)
lan.Response = string(resp.Body)
lan.Headers = &resp.Headers
lan.StatusCode = resp.StatusCode
return lan
}
func toSnapshots(resp Resp) Snapshots {
var col Snapshots
json.Unmarshal(resp.Body, &col)
col.Response = string(resp.Body)
col.Headers = &resp.Headers
col.StatusCode = resp.StatusCode
return col
}

View File

@ -0,0 +1,72 @@
package profitbricks
import (
"fmt"
"time"
)
func mkdcid(name string) string {
request := Datacenter{
Properties: DatacenterProperties{
Name: name,
Description: "description",
Location: "us/las",
},
}
dc := CreateDatacenter(request)
fmt.Println("===========================")
fmt.Println("Created a DC " + name)
fmt.Println("Created a DC id " + dc.Id)
fmt.Println(dc.StatusCode)
fmt.Println("===========================")
return dc.Id
}
func mksrvid(srv_dcid string) string {
var req = Server{
Properties: ServerProperties{
Name: "GO SDK test",
Ram: 1024,
Cores: 2,
},
}
srv := CreateServer(srv_dcid, req)
fmt.Println("===========================")
fmt.Println("Created a server " + srv.Id)
fmt.Println(srv.StatusCode)
fmt.Println("===========================")
waitTillProvisioned(srv.Headers.Get("Location"))
return srv.Id
}
func mknic(lbal_dcid, serverid string) string {
var request = Nic{
Properties: NicProperties{
Name: "GO SDK Original Nic",
Lan: 1,
},
}
resp := CreateNic(lbal_dcid, serverid, request)
fmt.Println("===========================")
fmt.Println("created a nic at server " + serverid)
fmt.Println("created a nic with id " + resp.Id)
fmt.Println(resp.StatusCode)
fmt.Println("===========================")
return resp.Id
}
func waitTillProvisioned(path string) {
waitCount := 20
fmt.Println(path)
for i := 0; i < waitCount; i++ {
request := GetRequestStatus(path)
if request.Metadata.Status == "DONE" {
break
}
time.Sleep(10 * time.Second)
i++
}
}

View File

@ -0,0 +1,131 @@
package profitbricks
import (
"bytes"
"encoding/json"
"net/http"
)
type Volume struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Metadata *DatacenterElementMetadata `json:"metadata,omitempty"`
Properties VolumeProperties `json:"properties,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
type VolumeProperties struct {
Name string `json:"name,omitempty"`
Type string `json:"type,omitempty"`
Size int `json:"size,omitempty"`
Image string `json:"image,omitempty"`
ImagePassword string `json:"imagePassword,omitempty"`
SshKeys []string `json:"sshKeys,omitempty"`
Bus string `json:"bus,omitempty"`
LicenceType string `json:"licenceType,omitempty"`
CpuHotPlug bool `json:"cpuHotPlug,omitempty"`
CpuHotUnplug bool `json:"cpuHotUnplug,omitempty"`
RamHotPlug bool `json:"ramHotPlug,omitempty"`
RamHotUnplug bool `json:"ramHotUnplug,omitempty"`
NicHotPlug bool `json:"nicHotPlug,omitempty"`
NicHotUnplug bool `json:"nicHotUnplug,omitempty"`
DiscVirtioHotPlug bool `json:"discVirtioHotPlug,omitempty"`
DiscVirtioHotUnplug bool `json:"discVirtioHotUnplug,omitempty"`
DiscScsiHotPlug bool `json:"discScsiHotPlug,omitempty"`
DiscScsiHotUnplug bool `json:"discScsiHotUnplug,omitempty"`
DeviceNumber int64 `json:"deviceNumber,omitempty"`
}
type Volumes struct {
Id string `json:"id,omitempty"`
Type_ string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Items []Volume `json:"items,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"headers,omitempty"`
}
type CreateVolumeRequest struct {
VolumeProperties `json:"properties"`
}
// ListVolumes returns a Collection struct for volumes in the Datacenter
func ListVolumes(dcid string) Volumes {
path := volume_col_path(dcid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
resp := do(req)
return toVolumes(resp)
}
func GetVolume(dcid string, volumeId string) Volume {
path := volume_path(dcid, volumeId)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
resp := do(req)
return toVolume(resp)
}
func PatchVolume(dcid string, volid string, request VolumeProperties) Volume {
obj, _ := json.Marshal(request)
path := volume_path(dcid, volid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(obj))
req.Header.Add("Content-Type", PatchHeader)
return toVolume(do(req))
}
func CreateVolume(dcid string, request Volume) Volume {
obj, _ := json.Marshal(request)
path := volume_col_path(dcid)
url := mk_url(path) + `?depth=` + Depth
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(obj))
req.Header.Add("Content-Type", FullHeader)
return toVolume(do(req))
}
func DeleteVolume(dcid, volid string) Resp {
path := volume_path(dcid, volid)
return is_delete(path)
}
func CreateSnapshot(dcid string, volid string, name string) Snapshot {
var path = volume_path(dcid, volid)
path = path + "/create-snapshot"
url := mk_url(path)
body := json.RawMessage("name=" + name)
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(body))
req.Header.Add("Content-Type", CommandHeader)
return toSnapshot(do(req))
}
func RestoreSnapshot(dcid string, volid string, snapshotId string) Resp {
var path = volume_path(dcid, volid)
path = path + "/restore-snapshot"
return is_command(path, "snapshotId="+snapshotId)
}
func toVolume(resp Resp) Volume {
var server Volume
json.Unmarshal(resp.Body, &server)
server.Response = string(resp.Body)
server.Headers = &resp.Headers
server.StatusCode = resp.StatusCode
return server
}
func toVolumes(resp Resp) Volumes {
var col Volumes
json.Unmarshal(resp.Body, &col)
col.Response = string(resp.Body)
col.Headers = &resp.Headers
col.StatusCode = resp.StatusCode
return col
}

View File

@ -0,0 +1,72 @@
---
description: |
The ProfitBricks builder is able to create images for ProfitBricks cloud.
layout: docs
page_title: ProfitBricks Builder
...
# ProfitBricks Builder
Type: `profitbricks`
The ProfitBricks Builder is able to create virtual machines for [ProfitBricks](https://www.profitbricks.com).
## Configuration Reference
There are many configuration options available for the builder. They are
segmented below into two categories: required and optional parameters. Within
each category, the available configuration keys are alphabetized.
In addition to the options listed here, a
[communicator](/docs/templates/communicator.html) can be configured for this
builder.
### Required
- `image` (string) - ProfitBricks volume image. Only Linux public images are supported. Defaults to "Ubuntu-16.04". To obtain full list of available images you can use [ProfitBricks CLI](https://github.com/profitbricks/profitbricks-cli#image).
- `password` (string) - ProfitBricks password. This can be specified via environment variable `PROFITBRICKS_PASSWORD', if provided. The value definded in the config has precedence over environemnt variable.
- `username` (string) - ProfitBricks username. This can be specified via environment variable `PROFITBRICKS_USERNAME', if provided. The value definded in the config has precedence over environemnt variable.
### Optional
- `cores` (integer) - Amount of CPU cores to use for this build. Defaults to "4".
- `disk_size` (string) - Amount of disk space for this image in GB. Defaults to "50"
- `disk_type` (string) - Type of disk to use for this image. Defaults to "HDD".
- `location` (string) - Defaults to "us/las".
- `ram` (integer) - Amount of RAM to use for this image. Defalts to "2048".
- `snapshot_name` (string) - If snapshot name is not provided Packer will generate it
- `snapshot_password` (string) - Password for the snapshot.
- `timeout` (string) - An approximate limit on how long Packer will continue making status requests while waiting for the build to complete. Default value 120 seconds.
- `url` (string) - Endpoint for the ProfitBricks REST API. Default URL "https://api.profitbricks.com/rest/v2"
## Example
Here is a basic example:
```json
{
"builders": [
{
"image": "Ubuntu-16.04",
"type": "profitbricks",
"disk_size": "5",
"snapshot_name": "double",
"ssh_key_path": "/path/to/private/key",
"snapshot_password": "test1234",
"timeout": 100
}
]
}
```