Packer Builder ProfitBricks
This commit is contained in:
parent
63edbd40ed
commit
df0298c9ae
|
@ -632,6 +632,10 @@
|
|||
{
|
||||
"ImportPath": "gopkg.in/xmlpath.v2",
|
||||
"Rev": "860cbeca3ebcc600db0b213c0e83ad6ce91f5739"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/profitbricks/profitbricks-sdk-go",
|
||||
"Rev": "04e83add0882eb67a163231899300f97b91f248d"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
@ -0,0 +1,35 @@
|
|||
package profitbricks
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// dummy Artifact implementation - does nothing
|
||||
type Artifact struct {
|
||||
// The name of the snapshot
|
||||
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
|
||||
}
|
|
@ -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)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,81 @@
|
|||
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.pem", b.config.ServerName),
|
||||
},
|
||||
new(stepCreateServer),
|
||||
&communicator.StepConnect{
|
||||
Config: &b.config.Comm,
|
||||
Host: commHost,
|
||||
SSHConfig: sshConfig,
|
||||
},
|
||||
&common.StepProvision{},
|
||||
new(stepTakeSnapshot),
|
||||
}
|
||||
|
||||
// Setup the state bag and initial state for the steps
|
||||
state := new(multistep.BasicStateBag)
|
||||
|
||||
state.Put("config", b.config)
|
||||
state.Put("hook", hook)
|
||||
state.Put("ui", ui)
|
||||
|
||||
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 there was an error, return that
|
||||
if rawErr, ok := state.GetOk("error"); ok {
|
||||
return nil, rawErr.(error)
|
||||
}
|
||||
|
||||
// No errors, must've worked
|
||||
artifact := &Artifact{
|
||||
snapshotData: state.Get("snapshotname").(string),
|
||||
}
|
||||
return artifact, nil
|
||||
}
|
||||
|
||||
func (b *Builder) Cancel() {
|
||||
if b.runner != nil {
|
||||
log.Println("Cancelling the step runner...")
|
||||
b.runner.Cancel()
|
||||
}
|
||||
}
|
|
@ -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",
|
||||
"pbpassword": "password",
|
||||
"pbusername": "username",
|
||||
"servername": "packer",
|
||||
"type": "profitbricks"
|
||||
}]
|
||||
}
|
||||
`
|
|
@ -0,0 +1,90 @@
|
|||
package profitbricks
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"github.com/mitchellh/packer/packer"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func testConfig() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"image": "Ubuntu-16.04",
|
||||
"pbpassword": "password",
|
||||
"pbusername": "username",
|
||||
"servername": "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()
|
||||
|
||||
// Add a random key
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuilderPrepare_Servername(t *testing.T) {
|
||||
var b Builder
|
||||
config := testConfig()
|
||||
|
||||
// Test default
|
||||
delete(config, "servername")
|
||||
warnings, err := b.Prepare(config)
|
||||
if len(warnings) > 0 {
|
||||
t.Fatalf("bad: %#v", warnings)
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatalf("should error")
|
||||
}
|
||||
|
||||
expected := "packer"
|
||||
|
||||
// Test set
|
||||
config["servername"] = expected
|
||||
b = Builder{}
|
||||
warnings, err = b.Prepare(config)
|
||||
if len(warnings) > 0 {
|
||||
t.Fatalf("bad: %#v", warnings)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("should not have error: %s", err)
|
||||
}
|
||||
|
||||
if b.config.ServerName != expected {
|
||||
t.Errorf("found %s, expected %s", b.config.ServerName, expected)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,123 @@
|
|||
package profitbricks
|
||||
|
||||
import (
|
||||
"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"
|
||||
"errors"
|
||||
"os"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
common.PackerConfig `mapstructure:",squash"`
|
||||
Comm communicator.Config `mapstructure:",squash"`
|
||||
|
||||
PBUsername string `mapstructure:"pbusername"`
|
||||
PBPassword string `mapstructure:"pbpassword"`
|
||||
PBUrl string `mapstructure:"pburl"`
|
||||
|
||||
Region string `mapstructure:"region"`
|
||||
Image string `mapstructure:"image"`
|
||||
SSHKey string `mapstructure:"sshkey"`
|
||||
ServerName string `mapstructure:"servername"`
|
||||
DiskSize int `mapstructure:"disksize"`
|
||||
DiskType string `mapstructure:"disktype"`
|
||||
Cores int `mapstructure:"cores"`
|
||||
Ram int `mapstructure:"ram"`
|
||||
|
||||
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.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 == "" {
|
||||
// Required configurations that will display errors if not set
|
||||
errs = packer.MultiErrorAppend(
|
||||
errs, errors.New("ProfitBricks username is required"))
|
||||
}
|
||||
|
||||
if c.PBPassword == "" {
|
||||
errs = packer.MultiErrorAppend(
|
||||
errs, errors.New("Profitbricks passwrod is required"))
|
||||
}
|
||||
|
||||
if c.ServerName == "" {
|
||||
errs = packer.MultiErrorAppend(
|
||||
errs, errors.New("Server Name is required"))
|
||||
}
|
||||
|
||||
if errs != nil && len(errs.Errors) > 0 {
|
||||
return nil, nil, errs
|
||||
}
|
||||
common.ScrubConfig(c, c.PBUsername)
|
||||
|
||||
return &c, nil, nil
|
||||
}
|
|
@ -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
|
||||
}
|
|
@ -0,0 +1,221 @@
|
|||
package profitbricks
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/mitchellh/multistep"
|
||||
"github.com/mitchellh/packer/packer"
|
||||
"github.com/profitbricks/profitbricks-sdk-go"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
waitCount = 30
|
||||
)
|
||||
|
||||
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)
|
||||
|
||||
ui.Say("Creating Virutal datacenter...")
|
||||
|
||||
//Create a Virtual datacenter
|
||||
datacenter := profitbricks.CreateDatacenter(profitbricks.CreateDatacenterRequest{
|
||||
DCProperties: profitbricks.DCProperties{
|
||||
Name: c.ServerName,
|
||||
Location: c.Region,
|
||||
},
|
||||
})
|
||||
|
||||
err := s.checkForErrors(datacenter.Resp)
|
||||
if err != nil {
|
||||
ui.Error(err.Error())
|
||||
return multistep.ActionHalt
|
||||
}
|
||||
|
||||
s.waitTillProvisioned(strings.Join(datacenter.Resp.Headers["Location"], ""), *c)
|
||||
|
||||
state.Put("datacenter_id", datacenter.Id)
|
||||
|
||||
ui.Say("Creating ProfitBricks server...")
|
||||
|
||||
server := profitbricks.CreateServer(datacenter.Id, profitbricks.CreateServerRequest{
|
||||
ServerProperties: profitbricks.ServerProperties{
|
||||
Name: c.ServerName,
|
||||
Ram: c.Ram,
|
||||
Cores: c.Cores,
|
||||
},
|
||||
})
|
||||
|
||||
err = s.checkForErrors(server.Resp)
|
||||
if err != nil {
|
||||
ui.Error(err.Error())
|
||||
return multistep.ActionHalt
|
||||
}
|
||||
|
||||
s.waitTillProvisioned(strings.Join(server.Resp.Headers["Location"], ""), *c)
|
||||
|
||||
ui.Say("Creating a volume...")
|
||||
|
||||
c.SSHKey = state.Get("publicKey").(string)
|
||||
|
||||
img := s.getImageId(c.Image, c)
|
||||
|
||||
volume := profitbricks.CreateVolume(datacenter.Id, profitbricks.CreateVolumeRequest{
|
||||
VolumeProperties: profitbricks.VolumeProperties{
|
||||
Size: c.DiskSize,
|
||||
Name: c.ServerName,
|
||||
Image: img,
|
||||
Type: c.DiskType,
|
||||
SshKey: []string{c.SSHKey},
|
||||
},
|
||||
})
|
||||
|
||||
err = s.checkForErrors(volume.Resp)
|
||||
if err != nil {
|
||||
ui.Error(err.Error())
|
||||
return multistep.ActionHalt
|
||||
}
|
||||
|
||||
s.waitTillProvisioned(strings.Join(volume.Resp.Headers["Location"], ""), *c)
|
||||
|
||||
attachresponse := profitbricks.AttachVolume(datacenter.Id, server.Id, volume.Id)
|
||||
|
||||
s.waitTillProvisioned(strings.Join(attachresponse.Resp.Headers["Location"], ""), *c)
|
||||
ui.Say("Creating a LAN...")
|
||||
|
||||
lan := profitbricks.CreateLan(datacenter.Id, profitbricks.CreateLanRequest{
|
||||
LanProperties: profitbricks.LanProperties{
|
||||
Public: true,
|
||||
Name: c.ServerName,
|
||||
},
|
||||
})
|
||||
|
||||
err = s.checkForErrors(lan.Resp)
|
||||
if err != nil {
|
||||
ui.Error(err.Error())
|
||||
return multistep.ActionHalt
|
||||
}
|
||||
|
||||
s.waitTillProvisioned(strings.Join(lan.Resp.Headers["Location"], ""), *c)
|
||||
|
||||
ui.Say("Creating a NIC...")
|
||||
|
||||
nic := profitbricks.CreateNic(datacenter.Id, server.Id, profitbricks.NicCreateRequest{
|
||||
NicProperties: profitbricks.NicProperties{
|
||||
Name: c.ServerName,
|
||||
Lan: lan.Id,
|
||||
Dhcp: true,
|
||||
},
|
||||
})
|
||||
|
||||
err = s.checkForErrors(nic.Resp)
|
||||
if err != nil {
|
||||
ui.Error(err.Error())
|
||||
return multistep.ActionHalt
|
||||
}
|
||||
|
||||
s.waitTillProvisioned(strings.Join(nic.Resp.Headers["Location"], ""), *c)
|
||||
|
||||
bootVolume := profitbricks.Instance{
|
||||
Properties: nil,
|
||||
Entities: nil,
|
||||
MetaData: nil,
|
||||
}
|
||||
|
||||
bootVolume.Id = volume.Id
|
||||
|
||||
serverpatchresponse := profitbricks.PatchServer(datacenter.Id, server.Id, profitbricks.ServerProperties{
|
||||
BootVolume: &bootVolume,
|
||||
})
|
||||
|
||||
state.Put("volume_id", volume.Id)
|
||||
|
||||
err = s.checkForErrors(serverpatchresponse.Resp)
|
||||
if err != nil {
|
||||
ui.Error(err.Error())
|
||||
return multistep.ActionHalt
|
||||
}
|
||||
|
||||
s.waitTillProvisioned(strings.Join(serverpatchresponse.Resp.Headers["Location"], ""), *c)
|
||||
|
||||
server = profitbricks.GetServer(datacenter.Id, server.Id)
|
||||
|
||||
state.Put("server_ip", server.Entities["nics"].Items[0].Properties["ips"].([]interface{})[0].(string))
|
||||
|
||||
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)
|
||||
dcId := state.Get("datacenter_id").(string)
|
||||
|
||||
resp := profitbricks.DeleteDatacenter(dcId)
|
||||
|
||||
s.checkForErrors(resp)
|
||||
|
||||
err := s.waitTillProvisioned(strings.Join(resp.Headers["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)
|
||||
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(10 * 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
|
||||
}
|
||||
|
||||
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"] != nil {
|
||||
imgName = images.Items[i].Properties["name"].(string)
|
||||
}
|
||||
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 {
|
||||
return images.Items[i].Id
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
|
@ -0,0 +1,72 @@
|
|||
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"
|
||||
)
|
||||
|
||||
// StepCreateSSHKey represents a Packer build step that generates SSH key pairs.
|
||||
type StepCreateSSHKey struct {
|
||||
Debug bool
|
||||
DebugKeyPath string
|
||||
}
|
||||
|
||||
// Run executes the Packer build step that generates SSH key pairs.
|
||||
func (s *StepCreateSSHKey) Run(state multistep.StateBag) multistep.StepAction {
|
||||
ui := state.Get("ui").(packer.Ui)
|
||||
|
||||
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
|
||||
}
|
||||
//fmt.Println("PUTTING")
|
||||
state.Put("privateKey", string(pem.EncodeToMemory(&priv_blk)))
|
||||
state.Put("publicKey", string(ssh.MarshalAuthorizedKey(pub)))
|
||||
|
||||
if s.Debug {
|
||||
ui.Message(fmt.Sprintf("Saving key for debug purposes: %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
|
||||
}
|
||||
|
||||
// Write out the key
|
||||
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
|
||||
}
|
||||
}
|
||||
return multistep.ActionContinue
|
||||
}
|
||||
|
||||
// Nothing to clean up. SSH keys are associated with a single GCE instance.
|
||||
func (s *StepCreateSSHKey) Cleanup(state multistep.StateBag) {}
|
|
@ -0,0 +1,66 @@
|
|||
package profitbricks
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/mitchellh/multistep"
|
||||
"github.com/mitchellh/packer/packer"
|
||||
"github.com/profitbricks/profitbricks-sdk-go"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
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.ServerName+"Snapshot")
|
||||
|
||||
state.Put("snapshotname", c.ServerName+"Snapshot")
|
||||
|
||||
err := s.checkForErrors(snapshot)
|
||||
if err != nil {
|
||||
ui.Error(err.Error())
|
||||
return multistep.ActionHalt
|
||||
}
|
||||
|
||||
s.waitTillProvisioned(strings.Join(snapshot.Headers["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)
|
||||
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)
|
||||
}
|
|
@ -25,6 +25,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"
|
||||
|
@ -75,6 +76,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),
|
||||
|
|
|
@ -0,0 +1,24 @@
|
|||
# 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
|
|
@ -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.
|
||||
|
|
@ -0,0 +1,323 @@
|
|||
# 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
|
||||
request := profitbricks.CreateDatacenterRequest{
|
||||
DCProperties: profitbricks.DCProperties{
|
||||
Name: "test",
|
||||
Description: "description",
|
||||
Location: "us/lasdev",
|
||||
},
|
||||
}
|
||||
|
||||
response := profitbricks.CreateDatacenter(request)
|
||||
```
|
||||
|
||||
## 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
|
||||
request = CreateServerRequest{
|
||||
ServerProperties: 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 := CreateVolumeRequest{
|
||||
VolumeProperties: VolumeProperties{
|
||||
Size: 1,
|
||||
Name: "Volume Test",
|
||||
ImageId: "imageid",
|
||||
Type: "HDD",
|
||||
SshKey: []string{"hQGOEJeFL91EG3+l9TtRbWNjzhDVHeLuL3NWee6bekA="},
|
||||
},
|
||||
}
|
||||
|
||||
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"
|
||||
"github.com/profitbricks/profitbricks-sdk-go"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
//Sets username and password
|
||||
profitbricks.SetAuth("username", "password")
|
||||
//Sets depth.
|
||||
profitbricks.SetDepth(5)
|
||||
|
||||
dcrequest := profitbricks.CreateDatacenterRequest{
|
||||
DCProperties: profitbricks.DCProperties{
|
||||
Name: "test",
|
||||
Description: "description",
|
||||
Location: "us/lasdev",
|
||||
},
|
||||
}
|
||||
|
||||
datacenter := profitbricks.CreateDatacenter(dcrequest)
|
||||
|
||||
serverrequest := profitbricks.CreateServerRequest{
|
||||
ServerProperties: profitbricks.ServerProperties{
|
||||
Name: "go01",
|
||||
Ram: 1024,
|
||||
Cores: 2,
|
||||
},
|
||||
}
|
||||
|
||||
server := profitbricks.CreateServer(datacenter.Id, serverrequest)
|
||||
|
||||
images := profitbricks.ListImages()
|
||||
|
||||
fmt.Println(images.Items)
|
||||
|
||||
volumerequest := profitbricks.CreateVolumeRequest{
|
||||
VolumeProperties: profitbricks.VolumeProperties{
|
||||
Size: 1,
|
||||
Name: "Volume Test",
|
||||
LicenceType: "LINUX",
|
||||
},
|
||||
}
|
||||
|
||||
storage := profitbricks.CreateVolume(datacenter.Id, volumerequest)
|
||||
|
||||
serverupdaterequest := profitbricks.ServerProperties{
|
||||
Name: "go01renamed",
|
||||
Cores: 1,
|
||||
Ram: 256,
|
||||
}
|
||||
|
||||
resp := profitbricks.PatchServer(datacenter.Id, server.Id, serverupdaterequest)
|
||||
|
||||
volumes := profitbricks.ListVolumes(datacenter.Id)
|
||||
servers := profitbricks.ListServers(datacenter.Id)
|
||||
datacenters := profitbricks.ListDatacenters()
|
||||
|
||||
profitbricks.DeleteServer(datacenter.Id, server.Id)
|
||||
profitbricks.DeleteDatacenter(datacenter.Id)
|
||||
}
|
||||
```
|
||||
|
||||
# Return Types
|
||||
|
||||
## Resp struct
|
||||
* Resp is the struct returned by all REST request functions
|
||||
|
||||
```go
|
||||
type Resp struct {
|
||||
Req *http.Request
|
||||
StatusCode int
|
||||
Headers http.Header
|
||||
Body []byte
|
||||
}
|
||||
```
|
||||
|
||||
## Instance struct
|
||||
* `Get`, `Create`, and `Patch` functions all return an Instance struct.
|
||||
* A Resp struct is embedded in the Instance struct.
|
||||
* The raw server response is available as `Instance.Resp.Body`.
|
||||
|
||||
```go
|
||||
type Instance struct {
|
||||
Id_Type_Href
|
||||
MetaData StringMap `json:"metaData"`
|
||||
Properties StringIfaceMap `json:"properties"`
|
||||
Entities StringCollectionMap `json:"entities"`
|
||||
Resp Resp `json:"-"`
|
||||
}
|
||||
```
|
||||
|
||||
## Collection struct
|
||||
* Collection Structs contain Instance arrays.
|
||||
* List functions return Collections
|
||||
|
||||
```go
|
||||
type Collection struct {
|
||||
Id_Type_Href
|
||||
Items []Instance `json:"items,omitempty"`
|
||||
Resp Resp `json:"-"`
|
||||
}
|
||||
```
|
||||
|
||||
# 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).
|
|
@ -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
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package profitbricks
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
type CreateDatacenterRequest struct {
|
||||
DCProperties `json:"properties"`
|
||||
}
|
||||
|
||||
type DCProperties struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Location string `json:"location,omitempty"`
|
||||
}
|
||||
|
||||
// ListDatacenters returns a Collection struct
|
||||
func ListDatacenters() Collection {
|
||||
path := dc_col_path()
|
||||
return is_list(path)
|
||||
}
|
||||
|
||||
// CreateDatacenter creates a datacenter and returns a Instance struct
|
||||
func CreateDatacenter(dc CreateDatacenterRequest) Instance {
|
||||
obj, _ := json.Marshal(dc)
|
||||
path := dc_col_path()
|
||||
return is_post(path, obj)
|
||||
}
|
||||
|
||||
// GetDatacenter returns a Instance struct where id == dcid
|
||||
func GetDatacenter(dcid string) Instance {
|
||||
path := dc_path(dcid)
|
||||
return is_get(path)
|
||||
}
|
||||
|
||||
// PatchDatacenter replaces any Datacenter properties with the values in jason
|
||||
//returns an Instance struct where id ==dcid
|
||||
func PatchDatacenter(dcid string, obj map[string]string) Instance {
|
||||
jason_patch := []byte(MkJson(obj))
|
||||
path := dc_path(dcid)
|
||||
return is_patch(path, jason_patch)
|
||||
}
|
||||
|
||||
// Deletes a Datacenter where id==dcid
|
||||
func DeleteDatacenter(dcid string) Resp {
|
||||
path := dc_path(dcid)
|
||||
return is_delete(path)
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
/*
|
||||
Package profitbricks is a client library for interacting with Profitbricks RESTful APIs.
|
||||
|
||||
|
||||
*/
|
||||
package profitbricks
|
|
@ -0,0 +1,27 @@
|
|||
package profitbricks
|
||||
|
||||
// ListImages returns an Collection struct
|
||||
func ListImages() Collection {
|
||||
path := image_col_path()
|
||||
return is_list(path)
|
||||
}
|
||||
|
||||
// GetImage returns an Instance struct where id ==imageid
|
||||
func GetImage(imageid string) Instance {
|
||||
path := image_path(imageid)
|
||||
return is_get(path)
|
||||
}
|
||||
|
||||
// PatchImage replaces any image properties from values in jason
|
||||
//returns an Instance struct where id ==imageid
|
||||
func PatchImage(imageid string, obj map[string]string) Instance {
|
||||
jason := []byte(MkJson(obj))
|
||||
path := image_path(imageid)
|
||||
return is_patch(path, jason)
|
||||
}
|
||||
|
||||
// Deletes an image where id==imageid
|
||||
func DeleteImage(imageid string) Resp {
|
||||
path := image_path(imageid)
|
||||
return is_delete(path)
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package profitbricks
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
type IPBlockReserveRequest struct {
|
||||
IPBlockProperties `json:"properties"`
|
||||
}
|
||||
|
||||
type IPBlockProperties struct {
|
||||
Size int `json:"size,omitempty"`
|
||||
Location string `json:"location,omitempty"`
|
||||
}
|
||||
|
||||
// ListIpBlocks
|
||||
func ListIpBlocks() Collection {
|
||||
path := ipblock_col_path()
|
||||
return is_list(path)
|
||||
}
|
||||
|
||||
func ReserveIpBlock(request IPBlockReserveRequest) Instance {
|
||||
obj, _ := json.Marshal(request)
|
||||
path := ipblock_col_path()
|
||||
return is_post(path, obj)
|
||||
|
||||
}
|
||||
func GetIpBlock(ipblockid string) Instance {
|
||||
path := ipblock_path(ipblockid)
|
||||
return is_get(path)
|
||||
}
|
||||
|
||||
func ReleaseIpBlock(ipblockid string) Resp {
|
||||
path := ipblock_path(ipblockid)
|
||||
return is_delete(path)
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
package profitbricks
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
type CreateLanRequest struct {
|
||||
LanProperties `json:"properties"`
|
||||
}
|
||||
|
||||
type LanProperties struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Public bool `json:"public,omitempty"`
|
||||
Nics []string `json:"nics,omitempty"`
|
||||
}
|
||||
|
||||
// ListLan returns a Collection for lans in the Datacenter
|
||||
func ListLans(dcid string) Collection {
|
||||
path := lan_col_path(dcid)
|
||||
return is_list(path)
|
||||
}
|
||||
|
||||
// CreateLan creates a lan in the datacenter
|
||||
// from a jason []byte and returns a Instance struct
|
||||
func CreateLan(dcid string, request CreateLanRequest) Instance {
|
||||
obj, _ := json.Marshal(request)
|
||||
path := lan_col_path(dcid)
|
||||
return is_post(path, obj)
|
||||
}
|
||||
|
||||
// GetLan pulls data for the lan where id = lanid returns an Instance struct
|
||||
func GetLan(dcid, lanid string) Instance {
|
||||
path := lan_path(dcid, lanid)
|
||||
return is_get(path)
|
||||
}
|
||||
|
||||
// PatchLan does a partial update to a lan using json from []byte jason
|
||||
// returns a Instance struct
|
||||
func PatchLan(dcid string, lanid string, obj map[string]string) Instance {
|
||||
jason := []byte(MkJson(obj))
|
||||
path := lan_path(dcid, lanid)
|
||||
return is_patch(path, jason)
|
||||
}
|
||||
|
||||
// DeleteLan deletes a lan where id == lanid
|
||||
func DeleteLan(dcid, lanid string) Resp {
|
||||
path := lan_path(dcid, lanid)
|
||||
return is_delete(path)
|
||||
}
|
||||
|
||||
// ListLanMembers returns a Nic struct collection for the Lan
|
||||
func ListLanMembers(dcid, lanid string) Collection {
|
||||
path := lan_nic_col(dcid, lanid)
|
||||
return is_list(path)
|
||||
}
|
70
vendor/github.com/profitbricks/profitbricks-sdk-go/loadbalancer.go
generated
vendored
Normal file
70
vendor/github.com/profitbricks/profitbricks-sdk-go/loadbalancer.go
generated
vendored
Normal file
|
@ -0,0 +1,70 @@
|
|||
package profitbricks
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
type LoablanacerCreateRequest struct {
|
||||
LoablanacerProperties `json:"properties"`
|
||||
}
|
||||
|
||||
type LoablanacerProperties struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Ip string `json:"ip,omitempty"`
|
||||
Dhcp bool `json:"dhcp,omitempty"`
|
||||
}
|
||||
|
||||
// Listloadbalancers returns a Collection struct
|
||||
// for loadbalancers in the Datacenter
|
||||
func ListLoadbalancers(dcid string) Collection {
|
||||
path := lbal_col_path(dcid)
|
||||
return is_list(path)
|
||||
}
|
||||
|
||||
// Createloadbalancer creates a loadbalancer in the datacenter
|
||||
//from a jason []byte and returns a Instance struct
|
||||
func CreateLoadbalancer(dcid string, request LoablanacerCreateRequest) Instance {
|
||||
obj, _ := json.Marshal(request)
|
||||
path := lbal_col_path(dcid)
|
||||
return is_post(path, obj)
|
||||
}
|
||||
|
||||
// GetLoadbalancer pulls data for the Loadbalancer
|
||||
// where id = lbalid returns a Instance struct
|
||||
func GetLoadbalancer(dcid, lbalid string) Instance {
|
||||
path := lbal_path(dcid, lbalid)
|
||||
return is_get(path)
|
||||
}
|
||||
|
||||
func PatchLoadbalancer(dcid string, lbalid string, obj map[string]string) Instance {
|
||||
jason := []byte(MkJson(obj))
|
||||
path := lbal_path(dcid, lbalid)
|
||||
return is_patch(path, jason)
|
||||
}
|
||||
|
||||
func DeleteLoadbalancer(dcid, lbalid string) Resp {
|
||||
path := lbal_path(dcid, lbalid)
|
||||
return is_delete(path)
|
||||
}
|
||||
|
||||
func ListBalancedNics(dcid, lbalid string) Collection {
|
||||
path := balnic_col_path(dcid, lbalid)
|
||||
return is_list(path)
|
||||
}
|
||||
|
||||
func AssociateNic(dcid string, lbalid string, nicid string) Instance {
|
||||
/*var sm StringMap
|
||||
sm["id"] = nicid*/
|
||||
sm := map[string]string{"id": nicid}
|
||||
jason := []byte(MkJson(sm))
|
||||
path := balnic_col_path(dcid, lbalid)
|
||||
return is_post(path, jason)
|
||||
}
|
||||
|
||||
func GetBalancedNic(dcid, lbalid, balnicid string) Instance {
|
||||
path := balnic_path(dcid, lbalid, balnicid)
|
||||
return is_get(path)
|
||||
}
|
||||
|
||||
func DeleteBalancedNic(dcid, lbalid, balnicid string) Resp {
|
||||
path := balnic_path(dcid, lbalid, balnicid)
|
||||
return is_delete(path)
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package profitbricks
|
||||
|
||||
// ListLocations returns location collection data
|
||||
func ListLocations() Collection {
|
||||
return is_list(location_col_path())
|
||||
}
|
||||
|
||||
// GetLocation returns location data
|
||||
func GetLocation(locid string) Instance {
|
||||
return is_get(location_path(locid))
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
package profitbricks
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
type NicCreateRequest struct {
|
||||
NicProperties `json:"properties"`
|
||||
}
|
||||
|
||||
type NicProperties struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Ips []string `json:"ips,omitempty"`
|
||||
Dhcp bool `json:"dhcp"`
|
||||
Lan string `json:"lan"`
|
||||
}
|
||||
|
||||
// ListNics returns a Nics struct collection
|
||||
func ListNics(dcid, srvid string) Collection {
|
||||
path := nic_col_path(dcid, srvid)
|
||||
return is_list(path)
|
||||
}
|
||||
|
||||
// CreateNic creates a nic on a server
|
||||
// from a jason []byte and returns a Instance struct
|
||||
func CreateNic(dcid string, srvid string, request NicCreateRequest) Instance {
|
||||
obj, _ := json.Marshal(request)
|
||||
path := nic_col_path(dcid, srvid)
|
||||
return is_post(path, obj)
|
||||
}
|
||||
|
||||
// GetNic pulls data for the nic where id = srvid returns a Instance struct
|
||||
func GetNic(dcid, srvid, nicid string) Instance {
|
||||
path := nic_path(dcid, srvid, nicid)
|
||||
return is_get(path)
|
||||
}
|
||||
|
||||
// PatchNic partial update of nic properties passed in as jason []byte
|
||||
// Returns Instance struct
|
||||
func PatchNic(dcid string, srvid string, nicid string, obj map[string]string) Instance {
|
||||
jason := []byte(MkJson(obj))
|
||||
path := nic_path(dcid, srvid, nicid)
|
||||
return is_patch(path, jason)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
|
@ -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)
|
||||
}
|
|
@ -0,0 +1,120 @@
|
|||
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_list performs an http.NewRequest GET and returns a Collection struct
|
||||
func is_list(path string) Collection {
|
||||
url := mk_url(path) + `?depth=` + Depth
|
||||
req, _ := http.NewRequest("GET", url, nil)
|
||||
req.Header.Add("Content-Type", FullHeader)
|
||||
return toCollection(do(req))
|
||||
}
|
||||
|
||||
// is_get performs an http.NewRequest GET and returns an Instance struct
|
||||
func is_get(path string) Instance {
|
||||
url := mk_url(path) + `?depth=` + Depth
|
||||
req, _ := http.NewRequest("GET", url, nil)
|
||||
req.Header.Add("Content-Type", FullHeader)
|
||||
return toInstance(do(req))
|
||||
}
|
||||
|
||||
// is_patch performs an http.NewRequest PATCH and returns an Instance struct
|
||||
func is_patch(path string, jason []byte) Instance {
|
||||
url := mk_url(path)
|
||||
req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(jason))
|
||||
req.Header.Add("Content-Type", PatchHeader)
|
||||
return toInstance(do(req))
|
||||
}
|
||||
|
||||
// is_put performs an http.NewRequest PUT and returns an Instance struct
|
||||
func is_put(path string, jason []byte) Instance {
|
||||
url := mk_url(path)
|
||||
req, _ := http.NewRequest("PUT", url, bytes.NewBuffer(jason))
|
||||
req.Header.Add("Content-Type", FullHeader)
|
||||
return toInstance(do(req))
|
||||
}
|
||||
|
||||
// is_post performs an http.NewRequest POST and returns an Instance struct
|
||||
func is_post(path string, jason []byte) Instance {
|
||||
url := mk_url(path)
|
||||
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jason))
|
||||
req.Header.Add("Content-Type", FullHeader)
|
||||
return toInstance(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)
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package profitbricks
|
||||
|
||||
func GetRequestStatus(path string) Instance {
|
||||
return is_get(path)
|
||||
}
|
|
@ -0,0 +1,105 @@
|
|||
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
|
||||
|
||||
// toInstance converts a Resp struct into a Instance struct
|
||||
func toInstance(resp Resp) Instance {
|
||||
var ins Instance
|
||||
json.Unmarshal(resp.Body, &ins)
|
||||
ins.Resp = resp
|
||||
return ins
|
||||
}
|
||||
|
||||
type Instance struct {
|
||||
Id_Type_Href
|
||||
MetaData StringMap `json:"metaData,omitempty"`
|
||||
Properties StringIfaceMap `json:"properties,omitempty"`
|
||||
Entities StringCollectionMap `json:"entities,omitempty"`
|
||||
Resp Resp `json:"-"`
|
||||
}
|
||||
|
||||
// Save converts the Instance struct's properties to json
|
||||
// and "patch"es them to the rest server
|
||||
func (ins *Instance) Save() {
|
||||
path := ins.Href
|
||||
jason, err := json.MarshalIndent(&ins.Properties, "", " ")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
r := is_patch(path, jason).Resp
|
||||
fmt.Println("save status code is ", r.StatusCode)
|
||||
}
|
||||
|
||||
// ShowProps prints the properties as k,v pairs
|
||||
func (ins *Instance) ShowProps() {
|
||||
for key, value := range ins.Properties {
|
||||
fmt.Println(key, " : ", value)
|
||||
}
|
||||
}
|
||||
func (ins *Instance) SetProp(key, val string) {
|
||||
ins.Properties[key] = val
|
||||
}
|
||||
|
||||
// ShowEnts prints the Entities as k,v pairs
|
||||
func (ins *Instance) ShowEnts() {
|
||||
for key, value := range ins.Entities {
|
||||
v := MkJson(value)
|
||||
fmt.Println(key, " : ", v)
|
||||
}
|
||||
}
|
||||
|
||||
// toServers converts a Resp struct into a Collection struct
|
||||
func toCollection(resp Resp) Collection {
|
||||
var col Collection
|
||||
json.Unmarshal(resp.Body, &col)
|
||||
col.Resp = resp
|
||||
return col
|
||||
}
|
||||
|
||||
type Collection struct {
|
||||
Id_Type_Href
|
||||
Items []Instance `json:"items,omitempty"`
|
||||
Resp Resp `json:"-"`
|
||||
}
|
|
@ -0,0 +1,116 @@
|
|||
package profitbricks
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
type CreateServerRequest struct {
|
||||
ServerProperties `json:"properties"`
|
||||
}
|
||||
|
||||
type ServerProperties struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Ram int `json:"ram,omitempty"`
|
||||
Cores int `json:"cores,omitempty"`
|
||||
Availabilityzone string `json:"availabilityzone,omitempty"`
|
||||
Licencetype string `json:"licencetype,omitempty"`
|
||||
BootVolume *Instance `json:"bootVolume,omitempty"`
|
||||
BootCdrom *Instance `json:"bootCdrom,omitempty"`
|
||||
}
|
||||
|
||||
// ListServers returns a server struct collection
|
||||
func ListServers(dcid string) Collection {
|
||||
path := server_col_path(dcid)
|
||||
return is_list(path)
|
||||
}
|
||||
|
||||
// CreateServer creates a server from a jason []byte and returns a Instance struct
|
||||
func CreateServer(dcid string, req CreateServerRequest) Instance {
|
||||
jason, _ := json.Marshal(req)
|
||||
path := server_col_path(dcid)
|
||||
return is_post(path, jason)
|
||||
}
|
||||
|
||||
// GetServer pulls data for the server where id = srvid returns a Instance struct
|
||||
func GetServer(dcid, srvid string) Instance {
|
||||
path := server_path(dcid, srvid)
|
||||
return is_get(path)
|
||||
}
|
||||
|
||||
// PatchServer partial update of server properties passed in as jason []byte
|
||||
// Returns Instance struct
|
||||
func PatchServer(dcid string, srvid string, req ServerProperties) Instance {
|
||||
jason, _ := json.Marshal(req)
|
||||
path := server_path(dcid, srvid)
|
||||
return is_patch(path, jason)
|
||||
}
|
||||
|
||||
// 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) Collection {
|
||||
path := server_cdrom_col_path(dcid, srvid)
|
||||
return is_list(path)
|
||||
}
|
||||
|
||||
func AttachCdrom(dcid string, srvid string, cdid string) Instance {
|
||||
jason := []byte(`{"id":"` + cdid + `"}`)
|
||||
path := server_cdrom_col_path(dcid, srvid)
|
||||
return is_post(path, jason)
|
||||
}
|
||||
|
||||
func GetAttachedCdrom(dcid, srvid, cdid string) Instance {
|
||||
path := server_cdrom_path(dcid, srvid, cdid)
|
||||
return is_get(path)
|
||||
}
|
||||
|
||||
func DetachCdrom(dcid, srvid, cdid string) Resp {
|
||||
path := server_cdrom_path(dcid, srvid, cdid)
|
||||
return is_delete(path)
|
||||
}
|
||||
|
||||
func ListAttachedVolumes(dcid, srvid string) Collection {
|
||||
path := server_volume_col_path(dcid, srvid)
|
||||
return is_list(path)
|
||||
}
|
||||
|
||||
func AttachVolume(dcid string, srvid string, volid string) Instance {
|
||||
jason := []byte(`{"id":"` + volid + `"}`)
|
||||
path := server_volume_col_path(dcid, srvid)
|
||||
return is_post(path, jason)
|
||||
}
|
||||
|
||||
func GetAttachedVolume(dcid, srvid, volid string) Instance {
|
||||
path := server_volume_path(dcid, srvid, volid)
|
||||
return is_get(path)
|
||||
}
|
||||
|
||||
func DetachVolume(dcid, srvid, volid string) Resp {
|
||||
path := server_volume_path(dcid, srvid, volid)
|
||||
return is_delete(path)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
// 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")
|
||||
}
|
61
vendor/github.com/profitbricks/profitbricks-sdk-go/test_helpers.go
generated
vendored
Normal file
61
vendor/github.com/profitbricks/profitbricks-sdk-go/test_helpers.go
generated
vendored
Normal file
|
@ -0,0 +1,61 @@
|
|||
package profitbricks
|
||||
|
||||
import "fmt"
|
||||
|
||||
func mkdcid(name string) string {
|
||||
request := CreateDatacenterRequest{
|
||||
DCProperties: DCProperties{
|
||||
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.Resp.StatusCode)
|
||||
fmt.Println("===========================")
|
||||
return dc.Id
|
||||
}
|
||||
|
||||
func mklocid() string {
|
||||
resp := ListLocations()
|
||||
|
||||
locid := resp.Items[0].Id
|
||||
return locid
|
||||
}
|
||||
|
||||
func mksrvid(srv_dcid string) string {
|
||||
var req = CreateServerRequest{
|
||||
ServerProperties: 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.Resp.StatusCode)
|
||||
fmt.Println("===========================")
|
||||
return srv.Id
|
||||
}
|
||||
|
||||
func mknic(lbal_dcid, serverid string) string {
|
||||
var request = NicCreateRequest{
|
||||
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.Resp.StatusCode)
|
||||
fmt.Println("===========================")
|
||||
return resp.Id
|
||||
}
|
|
@ -0,0 +1,60 @@
|
|||
package profitbricks
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
type CreateVolumeRequest struct {
|
||||
VolumeProperties `json:"properties"`
|
||||
}
|
||||
|
||||
type VolumeProperties struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Size int `json:"size,omitempty"`
|
||||
Bus string `json:",bus,omitempty"`
|
||||
Image string `json:"image,omitempty"`
|
||||
Type string `json:"type,omitempty"`
|
||||
LicenceType string `json:"licenceType,omitempty"`
|
||||
ImagePassword string `json:"imagePassword,omitempty"`
|
||||
SshKey []string `json:"sshKeys,omitempty"`
|
||||
}
|
||||
|
||||
// ListVolumes returns a Collection struct for volumes in the Datacenter
|
||||
func ListVolumes(dcid string) Collection {
|
||||
path := volume_col_path(dcid)
|
||||
return is_list(path)
|
||||
}
|
||||
|
||||
func GetVolume(dcid string, volumeId string) Instance {
|
||||
path := volume_path(dcid, volumeId)
|
||||
return is_get(path)
|
||||
}
|
||||
|
||||
func PatchVolume(dcid string, volid string, request VolumeProperties) Instance {
|
||||
obj, _ := json.Marshal(request)
|
||||
path := volume_path(dcid, volid)
|
||||
return is_patch(path, obj)
|
||||
}
|
||||
|
||||
func CreateVolume(dcid string, request CreateVolumeRequest) Instance {
|
||||
obj, _ := json.Marshal(request)
|
||||
path := volume_col_path(dcid)
|
||||
return is_post(path, obj)
|
||||
}
|
||||
|
||||
func DeleteVolume(dcid, volid string) Resp {
|
||||
path := volume_path(dcid, volid)
|
||||
return is_delete(path)
|
||||
}
|
||||
|
||||
func CreateSnapshot(dcid string, volid string, name string) Resp {
|
||||
var path = volume_path(dcid, volid)
|
||||
path = path + "/create-snapshot"
|
||||
|
||||
return is_command(path, "name="+name)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
Loading…
Reference in New Issue