From a3d5d40f78bfa16b04ee5b48d08363fe5ce98270 Mon Sep 17 00:00:00 2001 From: Megan Marsh Date: Fri, 5 Jan 2018 11:06:26 -0800 Subject: [PATCH 1/7] reformat TestDownloadableURL into a table test to allow adding more URLS --- common/config_test.go | 59 +++++++++++++++++++++++-------------------- 1 file changed, 31 insertions(+), 28 deletions(-) diff --git a/common/config_test.go b/common/config_test.go index 8bd684739..23aa25dd1 100644 --- a/common/config_test.go +++ b/common/config_test.go @@ -38,36 +38,39 @@ func TestChooseString(t *testing.T) { } func TestDownloadableURL(t *testing.T) { - // Invalid URL: has hex code in host - _, err := DownloadableURL("http://what%20.com") - if err == nil { - t.Fatal("expected err") + + cases := []struct { + InputString string + OutputURL string + ErrExpected bool + }{ + // Invalid URL: has hex code in host + {"http://what%20.com", "", true}, + // Valid: http + {"HTTP://packer.io/path", "http://packer.io/path", false}, + // No path + {"HTTP://packer.io", "http://packer.io", false}, + // Invalid: unsupported scheme + {"ftp://host.com/path", "", true}, } - // Invalid: unsupported scheme - _, err = DownloadableURL("ftp://host.com/path") - if err == nil { - t.Fatal("expected err") - } - - // Valid: http - u, err := DownloadableURL("HTTP://packer.io/path") - if err != nil { - t.Fatalf("err: %s", err) - } - - if u != "http://packer.io/path" { - t.Fatalf("bad: %s", u) - } - - // No path - u, err = DownloadableURL("HTTP://packer.io") - if err != nil { - t.Fatalf("err: %s", err) - } - - if u != "http://packer.io" { - t.Fatalf("bad: %s", u) + for _, tc := range cases { + u, err := DownloadableURL(tc.InputString) + if u != tc.OutputURL { + t.Fatal(fmt.Sprintf("Error with URL %s: got %s but expected %s", + tc.InputString, tc.OutputURL, u)) + } + if (err != nil) != tc.ErrExpected { + if tc.ErrExpected == true { + t.Fatal(fmt.Sprintf("Error with URL %s: we expected "+ + "DownloadableURL to return an error but didn't get one.", + tc.InputString)) + } else { + t.Fatal(fmt.Sprintf("Error with URL %s: we did not expect an "+ + " error from DownloadableURL but we got: %s", + tc.InputString, err)) + } + } } } From e4c1805f8128cb9ff079c7df5a2603688dd1074f Mon Sep 17 00:00:00 2001 From: Justin Campbell Date: Tue, 9 Jan 2018 13:11:22 -0500 Subject: [PATCH 2/7] Update hashicorp-middleman to 0.3.29 Also includes Nokogiri 1.8.1, to fix https://github.com/hashicorp/packer/network/dependencies#30455077 --- website/Gemfile | 2 +- website/Gemfile.lock | 46 ++++++++++++++++++++++---------------------- website/Makefile | 2 +- website/packer.json | 2 +- 4 files changed, 26 insertions(+), 26 deletions(-) diff --git a/website/Gemfile b/website/Gemfile index a2c4d1525..bb10a536e 100644 --- a/website/Gemfile +++ b/website/Gemfile @@ -1,3 +1,3 @@ source "https://rubygems.org" -gem "middleman-hashicorp", "0.3.28" +gem "middleman-hashicorp", "0.3.29" diff --git a/website/Gemfile.lock b/website/Gemfile.lock index dea170939..3f43b760a 100644 --- a/website/Gemfile.lock +++ b/website/Gemfile.lock @@ -1,12 +1,12 @@ GEM remote: https://rubygems.org/ specs: - activesupport (4.2.8) + activesupport (4.2.10) i18n (~> 0.7) minitest (~> 5.1) thread_safe (~> 0.3, >= 0.3.4) tzinfo (~> 1.1) - autoprefixer-rails (7.1.1.2) + autoprefixer-rails (7.2.4) execjs bootstrap-sass (3.3.7) autoprefixer-rails (>= 5.2.1) @@ -39,10 +39,10 @@ GEM eventmachine (>= 0.12.9) http_parser.rb (~> 0.6.0) erubis (2.7.0) - eventmachine (1.2.3) + eventmachine (1.2.5) execjs (2.7.0) ffi (1.9.18) - haml (5.0.1) + haml (5.0.4) temple (>= 0.8.0) tilt hike (1.2.3) @@ -51,7 +51,7 @@ GEM http_parser.rb (0.6.0) i18n (0.7.0) json (2.1.0) - kramdown (1.13.2) + kramdown (1.16.2) listen (3.0.8) rb-fsevent (~> 0.9, >= 0.9.4) rb-inotify (~> 0.9, >= 0.9.7) @@ -78,7 +78,7 @@ GEM rack (>= 1.4.5, < 2.0) thor (>= 0.15.2, < 2.0) tilt (~> 1.4.1, < 2.0) - middleman-hashicorp (0.3.28) + middleman-hashicorp (0.3.29) bootstrap-sass (~> 3.3) builder (~> 3.2) middleman (~> 3.4) @@ -101,11 +101,11 @@ GEM mime-types (3.1) mime-types-data (~> 3.2015) mime-types-data (3.2016.0521) - mini_portile2 (2.2.0) - minitest (5.10.2) - multi_json (1.12.1) - nokogiri (1.8.0) - mini_portile2 (~> 2.2.0) + mini_portile2 (2.3.0) + minitest (5.11.1) + multi_json (1.13.0) + nokogiri (1.8.1) + mini_portile2 (~> 2.3.0) padrino-helpers (0.12.8.1) i18n (~> 0.6, >= 0.6.7) padrino-support (= 0.12.8.1) @@ -115,14 +115,14 @@ GEM rack (1.6.8) rack-livereload (0.3.16) rack - rack-test (0.6.3) - rack (>= 1.0) - rb-fsevent (0.9.8) + rack-test (0.8.2) + rack (>= 1.0, < 3) + rb-fsevent (0.10.2) rb-inotify (0.9.10) ffi (>= 0.5.0, < 2) redcarpet (3.4.0) - rouge (2.1.1) - sass (3.4.24) + rouge (2.2.1) + sass (3.4.25) sprockets (2.12.4) hike (~> 1.2) multi_json (~> 1.0) @@ -134,13 +134,13 @@ GEM sprockets (~> 2.0) tilt (~> 1.1) temple (0.8.0) - thor (0.19.4) + thor (0.20.0) thread_safe (0.3.6) tilt (1.4.1) - turbolinks (5.0.1) - turbolinks-source (~> 5) - turbolinks-source (5.0.3) - tzinfo (1.2.3) + turbolinks (5.1.0) + turbolinks-source (~> 5.1) + turbolinks-source (5.1.0) + tzinfo (1.2.4) thread_safe (~> 0.1) uber (0.0.15) uglifier (2.7.2) @@ -153,7 +153,7 @@ PLATFORMS ruby DEPENDENCIES - middleman-hashicorp (= 0.3.28) + middleman-hashicorp (= 0.3.29) BUNDLED WITH - 1.15.1 + 1.16.1 diff --git a/website/Makefile b/website/Makefile index 4d3d361b7..ccc3ae634 100644 --- a/website/Makefile +++ b/website/Makefile @@ -1,4 +1,4 @@ -VERSION?="0.3.28" +VERSION?="0.3.29" build: @echo "==> Starting build in Docker..." diff --git a/website/packer.json b/website/packer.json index fd2618f17..cbfb5c565 100644 --- a/website/packer.json +++ b/website/packer.json @@ -8,7 +8,7 @@ "builders": [ { "type": "docker", - "image": "hashicorp/middleman-hashicorp:0.3.28", + "image": "hashicorp/middleman-hashicorp:0.3.29", "discard": "true", "volumes": { "{{ pwd }}": "/website" From 2e8561a28d1b4a643c855201bd094f7fe0876d07 Mon Sep 17 00:00:00 2001 From: Matthew Hooker Date: Tue, 9 Jan 2018 11:39:55 -0800 Subject: [PATCH 3/7] update middleman-hashicorp --- website/Gemfile | 2 +- website/Gemfile.lock | 44 ++++++++++++++++++++++---------------------- 2 files changed, 23 insertions(+), 23 deletions(-) diff --git a/website/Gemfile b/website/Gemfile index a2c4d1525..bb10a536e 100644 --- a/website/Gemfile +++ b/website/Gemfile @@ -1,3 +1,3 @@ source "https://rubygems.org" -gem "middleman-hashicorp", "0.3.28" +gem "middleman-hashicorp", "0.3.29" diff --git a/website/Gemfile.lock b/website/Gemfile.lock index dea170939..e7076767b 100644 --- a/website/Gemfile.lock +++ b/website/Gemfile.lock @@ -1,12 +1,12 @@ GEM remote: https://rubygems.org/ specs: - activesupport (4.2.8) + activesupport (4.2.10) i18n (~> 0.7) minitest (~> 5.1) thread_safe (~> 0.3, >= 0.3.4) tzinfo (~> 1.1) - autoprefixer-rails (7.1.1.2) + autoprefixer-rails (7.2.4) execjs bootstrap-sass (3.3.7) autoprefixer-rails (>= 5.2.1) @@ -39,10 +39,10 @@ GEM eventmachine (>= 0.12.9) http_parser.rb (~> 0.6.0) erubis (2.7.0) - eventmachine (1.2.3) + eventmachine (1.2.5) execjs (2.7.0) ffi (1.9.18) - haml (5.0.1) + haml (5.0.4) temple (>= 0.8.0) tilt hike (1.2.3) @@ -51,7 +51,7 @@ GEM http_parser.rb (0.6.0) i18n (0.7.0) json (2.1.0) - kramdown (1.13.2) + kramdown (1.16.2) listen (3.0.8) rb-fsevent (~> 0.9, >= 0.9.4) rb-inotify (~> 0.9, >= 0.9.7) @@ -78,7 +78,7 @@ GEM rack (>= 1.4.5, < 2.0) thor (>= 0.15.2, < 2.0) tilt (~> 1.4.1, < 2.0) - middleman-hashicorp (0.3.28) + middleman-hashicorp (0.3.29) bootstrap-sass (~> 3.3) builder (~> 3.2) middleman (~> 3.4) @@ -101,11 +101,11 @@ GEM mime-types (3.1) mime-types-data (~> 3.2015) mime-types-data (3.2016.0521) - mini_portile2 (2.2.0) - minitest (5.10.2) - multi_json (1.12.1) - nokogiri (1.8.0) - mini_portile2 (~> 2.2.0) + mini_portile2 (2.3.0) + minitest (5.11.1) + multi_json (1.13.0) + nokogiri (1.8.1) + mini_portile2 (~> 2.3.0) padrino-helpers (0.12.8.1) i18n (~> 0.6, >= 0.6.7) padrino-support (= 0.12.8.1) @@ -115,14 +115,14 @@ GEM rack (1.6.8) rack-livereload (0.3.16) rack - rack-test (0.6.3) - rack (>= 1.0) - rb-fsevent (0.9.8) + rack-test (0.8.2) + rack (>= 1.0, < 3) + rb-fsevent (0.10.2) rb-inotify (0.9.10) ffi (>= 0.5.0, < 2) redcarpet (3.4.0) - rouge (2.1.1) - sass (3.4.24) + rouge (2.2.1) + sass (3.4.25) sprockets (2.12.4) hike (~> 1.2) multi_json (~> 1.0) @@ -134,13 +134,13 @@ GEM sprockets (~> 2.0) tilt (~> 1.1) temple (0.8.0) - thor (0.19.4) + thor (0.20.0) thread_safe (0.3.6) tilt (1.4.1) - turbolinks (5.0.1) - turbolinks-source (~> 5) - turbolinks-source (5.0.3) - tzinfo (1.2.3) + turbolinks (5.1.0) + turbolinks-source (~> 5.1) + turbolinks-source (5.1.0) + tzinfo (1.2.4) thread_safe (~> 0.1) uber (0.0.15) uglifier (2.7.2) @@ -153,7 +153,7 @@ PLATFORMS ruby DEPENDENCIES - middleman-hashicorp (= 0.3.28) + middleman-hashicorp (= 0.3.29) BUNDLED WITH 1.15.1 From 5189d65467d9fe857fe1f286c2649c1e1f0063ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=8B=E1=85=B2=E1=84=89=E1=85=A5=E1=86=BC=E1=84=83?= =?UTF-8?q?=E1=85=A5=E1=86=A8?= Date: Thu, 11 Jan 2018 18:57:53 +0900 Subject: [PATCH 4/7] Support Naver Cloud Platform --- builder/ncloud/artifact.go | 46 +++ builder/ncloud/builder.go | 117 ++++++++ builder/ncloud/config.go | 114 ++++++++ builder/ncloud/config_test.go | 149 ++++++++++ builder/ncloud/ssh.go | 30 ++ builder/ncloud/step.go | 16 ++ .../step_create_block_storage_instance.go | 101 +++++++ ...step_create_block_storage_instance_test.go | 62 +++++ builder/ncloud/step_create_login_key.go | 71 +++++ builder/ncloud/step_create_login_key_test.go | 53 ++++ .../ncloud/step_create_public_ip_instance.go | 167 +++++++++++ .../step_create_public_ip_instance_test.go | 62 +++++ builder/ncloud/step_create_server_image.go | 77 +++++ .../ncloud/step_create_server_image_test.go | 58 ++++ builder/ncloud/step_create_server_instance.go | 129 +++++++++ .../step_create_server_instance_test.go | 58 ++++ .../step_delete_block_storage_instance.go | 95 +++++++ ...step_delete_block_storage_instance_test.go | 57 ++++ builder/ncloud/step_delete_login_key.go | 51 ++++ builder/ncloud/step_delete_login_key_test.go | 55 ++++ .../ncloud/step_delete_public_ip_instance.go | 78 ++++++ .../step_delete_public_ip_instance_test.go | 57 ++++ builder/ncloud/step_get_rootpassword.go | 57 ++++ builder/ncloud/step_get_rootpassword_test.go | 56 ++++ builder/ncloud/step_stop_server_instance.go | 64 +++++ .../ncloud/step_stop_server_instance_test.go | 55 ++++ .../ncloud/step_terminate_server_instance.go | 81 ++++++ .../step_terminate_server_instance_test.go | 54 ++++ builder/ncloud/step_validate_template.go | 263 ++++++++++++++++++ builder/ncloud/step_validate_template_test.go | 54 ++++ .../ncloud/waiter_block_storage_instance.go | 80 ++++++ builder/ncloud/waiter_server_image_status.go | 43 +++ .../ncloud/waiter_server_instance_status.go | 43 +++ command/plugin.go | 2 + 34 files changed, 2555 insertions(+) create mode 100644 builder/ncloud/artifact.go create mode 100644 builder/ncloud/builder.go create mode 100644 builder/ncloud/config.go create mode 100644 builder/ncloud/config_test.go create mode 100644 builder/ncloud/ssh.go create mode 100644 builder/ncloud/step.go create mode 100644 builder/ncloud/step_create_block_storage_instance.go create mode 100644 builder/ncloud/step_create_block_storage_instance_test.go create mode 100644 builder/ncloud/step_create_login_key.go create mode 100644 builder/ncloud/step_create_login_key_test.go create mode 100644 builder/ncloud/step_create_public_ip_instance.go create mode 100644 builder/ncloud/step_create_public_ip_instance_test.go create mode 100644 builder/ncloud/step_create_server_image.go create mode 100644 builder/ncloud/step_create_server_image_test.go create mode 100644 builder/ncloud/step_create_server_instance.go create mode 100644 builder/ncloud/step_create_server_instance_test.go create mode 100644 builder/ncloud/step_delete_block_storage_instance.go create mode 100644 builder/ncloud/step_delete_block_storage_instance_test.go create mode 100644 builder/ncloud/step_delete_login_key.go create mode 100644 builder/ncloud/step_delete_login_key_test.go create mode 100644 builder/ncloud/step_delete_public_ip_instance.go create mode 100644 builder/ncloud/step_delete_public_ip_instance_test.go create mode 100644 builder/ncloud/step_get_rootpassword.go create mode 100644 builder/ncloud/step_get_rootpassword_test.go create mode 100644 builder/ncloud/step_stop_server_instance.go create mode 100644 builder/ncloud/step_stop_server_instance_test.go create mode 100644 builder/ncloud/step_terminate_server_instance.go create mode 100644 builder/ncloud/step_terminate_server_instance_test.go create mode 100644 builder/ncloud/step_validate_template.go create mode 100644 builder/ncloud/step_validate_template_test.go create mode 100644 builder/ncloud/waiter_block_storage_instance.go create mode 100644 builder/ncloud/waiter_server_image_status.go create mode 100644 builder/ncloud/waiter_server_instance_status.go diff --git a/builder/ncloud/artifact.go b/builder/ncloud/artifact.go new file mode 100644 index 000000000..52624e437 --- /dev/null +++ b/builder/ncloud/artifact.go @@ -0,0 +1,46 @@ +package ncloud + +import ( + "bytes" + "fmt" + + ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" +) + +const BuilderID = "ncloud.server.image" + +type Artifact struct { + ServerImage *ncloud.ServerImage +} + +func (*Artifact) BuilderId() string { + return BuilderID +} + +func (a *Artifact) Files() []string { + /* no file */ + return nil +} + +func (a *Artifact) Id() string { + return a.ServerImage.MemberServerImageNo +} + +func (a *Artifact) String() string { + var buf bytes.Buffer + + // TODO : Logging artifact information + buf.WriteString(fmt.Sprintf("%s:\n\n", a.BuilderId())) + buf.WriteString(fmt.Sprintf("Member Server Image Name: %s\n", a.ServerImage.MemberServerImageName)) + buf.WriteString(fmt.Sprintf("Member Server Image No: %s\n", a.ServerImage.MemberServerImageNo)) + + return buf.String() +} + +func (a *Artifact) State(name string) interface{} { + return a.ServerImage.MemberServerImageStatus +} + +func (a *Artifact) Destroy() error { + return nil +} diff --git a/builder/ncloud/builder.go b/builder/ncloud/builder.go new file mode 100644 index 000000000..580514d53 --- /dev/null +++ b/builder/ncloud/builder.go @@ -0,0 +1,117 @@ +package ncloud + +import ( + ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" + "github.com/hashicorp/packer/common" + "github.com/hashicorp/packer/helper/communicator" + "github.com/hashicorp/packer/packer" + "github.com/mitchellh/multistep" +) + +const version = "1.0.0" + +// Builder assume this implements packer.Builder +type Builder struct { + config *Config + stateBag multistep.StateBag + 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 + + b.stateBag = new(multistep.BasicStateBag) + + return warnings, nil +} + +func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) { + ui.Say("Running builder for Naver Cloud Platform (version: " + version + ") ...") + + ui.Message("Creating Naver Cloud Platform Connection ...") + conn := ncloud.NewConnection(b.config.AccessKey, b.config.SecretKey) + + b.stateBag.Put("hook", hook) + b.stateBag.Put("ui", ui) + + var steps []multistep.Step + + steps = []multistep.Step{} + + if b.config.OSType == "Linux" { + steps = []multistep.Step{ + NewStepValidateTemplate(conn, ui, b.config), + NewStepCreateLoginKey(conn, ui), + NewStepCreateServerInstance(conn, ui, b.config), + NewStepCreateBlockStorageInstance(conn, ui, b.config), + NewStepGetRootPassword(conn, ui), + NewStepCreatePublicIPInstance(conn, ui, b.config), + &communicator.StepConnectSSH{ + Config: &b.config.Comm, + Host: SSHHost, + SSHConfig: SSHConfig(b.config.Comm.SSHUsername), + }, + &common.StepProvision{}, + NewStepStopServerInstance(conn, ui), + NewStepCreateServerImage(conn, ui, b.config), + NewStepDeleteBlockStorageInstance(conn, ui, b.config), + NewStepTerminateServerInstance(conn, ui), + NewStepDeleteLoginKey(conn, ui), + NewStepDeletePublicIPInstance(conn, ui), + } + } else if b.config.OSType == "Windows" { + steps = []multistep.Step{ + NewStepValidateTemplate(conn, ui, b.config), + NewStepCreateLoginKey(conn, ui), + NewStepCreateServerInstance(conn, ui, b.config), + NewStepCreateBlockStorageInstance(conn, ui, b.config), + NewStepGetRootPassword(conn, ui), + NewStepCreatePublicIPInstance(conn, ui, b.config), + &communicator.StepConnectWinRM{ + Config: &b.config.Comm, + Host: func(stateBag multistep.StateBag) (string, error) { + return stateBag.Get("WinRMHost").(string), nil + }, + WinRMConfig: func(state multistep.StateBag) (*communicator.WinRMConfig, error) { + return &communicator.WinRMConfig{ + Username: b.config.Comm.WinRMUser, + Password: state.Get("Password").(string), + }, nil + }, + }, + &common.StepProvision{}, + NewStepStopServerInstance(conn, ui), + NewStepCreateServerImage(conn, ui, b.config), + NewStepDeleteBlockStorageInstance(conn, ui, b.config), + NewStepTerminateServerInstance(conn, ui), + NewStepDeleteLoginKey(conn, ui), + NewStepDeletePublicIPInstance(conn, ui), + } + } + + // Run! + b.runner = common.NewRunner(steps, b.config.PackerConfig, ui) + b.runner.Run(b.stateBag) + + // If there was an error, return that + if rawErr, ok := b.stateBag.GetOk("Error"); ok { + return nil, rawErr.(error) + } + + // Build the artifact and return it + artifact := &Artifact{} + + if serverImage, ok := b.stateBag.GetOk("memberServerImage"); ok { + artifact.ServerImage = serverImage.(*ncloud.ServerImage) + } + + return artifact, nil +} + +func (b *Builder) Cancel() { + b.runner.Cancel() +} diff --git a/builder/ncloud/config.go b/builder/ncloud/config.go new file mode 100644 index 000000000..e18ab822d --- /dev/null +++ b/builder/ncloud/config.go @@ -0,0 +1,114 @@ +package ncloud + +import ( + "errors" + + "github.com/hashicorp/packer/common" + "github.com/hashicorp/packer/helper/communicator" + "github.com/hashicorp/packer/helper/config" + "github.com/hashicorp/packer/packer" + "github.com/hashicorp/packer/template/interpolate" +) + +// Config is structure to use packer builder plugin for Naver Cloud Platform +type Config struct { + common.PackerConfig `mapstructure:",squash"` + + AccessKey string `mapstructure:"access_key"` + SecretKey string `mapstructure:"secret_key"` + OSType string `mapstructure:"os_type"` + ServerImageProductCode string `mapstructure:"server_image_product_code"` + ServerProductCode string `mapstructure:"server_product_code"` + MemberServerImageNo string `mapstructure:"member_server_image_no"` + ServerImageName string `mapstructure:"server_image_name"` + ServerImageDescription string `mapstructure:"server_image_description"` + UserData string `mapstructure:"user_data"` + BlockStorageSize int `mapstructure:"block_storage_size"` + Region string `mapstructure:"region"` + AccessControlGroupConfigurationNo string `mapstructure:"access_control_group_configuration_no"` + FeeSystemTypeCode string `mapstructure:"-"` + + Comm communicator.Config `mapstructure:",squash"` + ctx *interpolate.Context +} + +// NewConfig checks parameters +func NewConfig(raws ...interface{}) (*Config, []string, error) { + c := new(Config) + warnings := []string{} + + err := config.Decode(c, &config.DecodeOpts{ + Interpolate: true, + InterpolateFilter: &interpolate.RenderFilter{ + Exclude: []string{}, + }, + }, raws...) + if err != nil { + return nil, warnings, err + } + + var errs *packer.MultiError + if es := c.Comm.Prepare(nil); len(es) > 0 { + errs = packer.MultiErrorAppend(errs, es...) + } + + if c.AccessKey == "" { + errs = packer.MultiErrorAppend(errs, errors.New("access_key is required")) + } + + if c.SecretKey == "" { + errs = packer.MultiErrorAppend(errs, errors.New("secret_key is required")) + } + + if c.OSType != "Linux" && c.OSType != "Windows" { + errs = packer.MultiErrorAppend(errs, errors.New("os_type is required. ('Linux' or 'Windows')")) + } + + if c.MemberServerImageNo == "" && c.ServerImageProductCode == "" { + errs = packer.MultiErrorAppend(errs, errors.New("server_image_product_code or member_server_image_no is required")) + } + + if c.MemberServerImageNo != "" && c.ServerImageProductCode != "" { + errs = packer.MultiErrorAppend(errs, errors.New("Only one of server_image_product_code and member_server_image_no can be set")) + } + + if c.ServerImageProductCode != "" && len(c.ServerImageProductCode) > 20 { + errs = packer.MultiErrorAppend(errs, errors.New("If server_image_product_code field is set, length of server_image_product_code should be max 20")) + } + + if c.ServerProductCode != "" && len(c.ServerProductCode) > 20 { + errs = packer.MultiErrorAppend(errs, errors.New("If server_product_code field is set, length of server_product_code should be max 20")) + } + + if c.ServerImageName != "" && (len(c.ServerImageName) < 3 || len(c.ServerImageName) > 30) { + errs = packer.MultiErrorAppend(errs, errors.New("If server_image_name field is set, length of server_image_name should be min 3 and max 20")) + } + + if c.ServerImageDescription != "" && len(c.ServerImageDescription) > 1000 { + errs = packer.MultiErrorAppend(errs, errors.New("If server_image_description field is set, length of server_image_description should be max 1000")) + } + + if c.BlockStorageSize != 0 { + if c.BlockStorageSize < 10 || c.BlockStorageSize > 2000 { + errs = packer.MultiErrorAppend(errs, errors.New("The size of BlockStorageSize is at least 10 GB and up to 2000GB")) + } else if int(c.BlockStorageSize/10)*10 != c.BlockStorageSize { + return nil, nil, errors.New("BlockStorageSize must be a multiple of 10 GB") + } + } + + if c.UserData != "" && len(c.UserData) > 21847 { + errs = packer.MultiErrorAppend(errs, errors.New("If user_data field is set, length of UserData should be max 21847")) + } + + if c.OSType == "Windows" && c.AccessControlGroupConfigurationNo == "" { + errs = packer.MultiErrorAppend(errs, errors.New("If os_type is Windows, access_control_group_configuration_no is required")) + } + + c.FeeSystemTypeCode = "MTRAT" + + if errs != nil && len(errs.Errors) > 0 { + return nil, warnings, errs + } + + return c, warnings, nil +} diff --git a/builder/ncloud/config_test.go b/builder/ncloud/config_test.go new file mode 100644 index 000000000..7907c7ee1 --- /dev/null +++ b/builder/ncloud/config_test.go @@ -0,0 +1,149 @@ +package ncloud + +import ( + "strings" + "testing" +) + +func testConfig() map[string]interface{} { + return map[string]interface{}{ + "access_key": "access_key", + "secret_key": "secret_key", + "os_type": "Windows", + "server_image_product_code": "SPSW0WINNT000016", + "server_product_code": "SPSVRSSD00000011", + "server_image_name": "packer-test {{timestamp}}", + "server_image_description": "server description", + "block_storage_size": 100, + "user_data": "#!/bin/sh\nyum install -y httpd\ntouch /var/www/html/index.html\nchkconfig --level 2345 httpd on", + "region": "Korea", + "access_control_group_configuration_no": "33", + "communicator": "ssh", + "ssh_username": "root", + } +} + +func testConfigForMemberServerImage() map[string]interface{} { + return map[string]interface{}{ + "access_key": "access_key", + "secret_key": "secret_key", + "os_type": "Windows", + "server_product_code": "SPSVRSSD00000011", + "member_server_image_no": "2440", + "server_image_name": "packer-test {{timestamp}}", + "server_image_description": "server description", + "block_storage_size": 100, + "user_data": "#!/bin/sh\nyum install -y httpd\ntouch /var/www/html/index.html\nchkconfig --level 2345 httpd on", + "region": "Korea", + "access_control_group_configuration_no": "33", + "communicator": "ssh", + "ssh_username": "root", + } +} + +func TestConfigWithServerImageProductCode(t *testing.T) { + raw := testConfig() + + c, _, _ := NewConfig(raw) + + if c.AccessKey != "access_key" { + t.Errorf("Expected 'access_key' to be set to '%s', but got '%s'.", raw["access_key"], c.AccessKey) + } + + if c.SecretKey != "secret_key" { + t.Errorf("Expected 'secret_key' to be set to '%s', but got '%s'.", raw["secret_key"], c.SecretKey) + } + + if c.ServerImageProductCode != "SPSW0WINNT000016" { + t.Errorf("Expected 'server_image_product_code' to be set to '%s', but got '%s'.", raw["server_image_product_code"], c.ServerImageProductCode) + } + + if c.ServerProductCode != "SPSVRSSD00000011" { + t.Errorf("Expected 'server_product_code' to be set to '%s', but got '%s'.", raw["server_product_code"], c.ServerProductCode) + } + + if c.BlockStorageSize != 100 { + t.Errorf("Expected 'block_storage_size' to be set to '%d', but got '%d'.", raw["block_storage_size"], c.BlockStorageSize) + } + + if c.ServerImageDescription != "server description" { + t.Errorf("Expected 'server_image_description_key' to be set to '%s', but got '%s'.", raw["server_image_description"], c.ServerImageDescription) + } + + if c.Region != "Korea" { + t.Errorf("Expected 'region' to be set to '%s', but got '%s'.", raw["server_image_description"], c.Region) + } +} + +func TestConfigWithMemberServerImageCode(t *testing.T) { + raw := testConfigForMemberServerImage() + + c, _, _ := NewConfig(raw) + + if c.AccessKey != "access_key" { + t.Errorf("Expected 'access_key' to be set to '%s', but got '%s'.", raw["access_key"], c.AccessKey) + } + + if c.SecretKey != "secret_key" { + t.Errorf("Expected 'secret_key' to be set to '%s', but got '%s'.", raw["secret_key"], c.SecretKey) + } + + if c.MemberServerImageNo != "2440" { + t.Errorf("Expected 'member_server_image_no' to be set to '%s', but got '%s'.", raw["member_server_image_no"], c.MemberServerImageNo) + } + + if c.ServerProductCode != "SPSVRSSD00000011" { + t.Errorf("Expected 'server_product_code' to be set to '%s', but got '%s'.", raw["server_product_code"], c.ServerProductCode) + } + + if c.BlockStorageSize != 100 { + t.Errorf("Expected 'block_storage_size' to be set to '%d', but got '%d'.", raw["block_storage_size"], c.BlockStorageSize) + } + + if c.ServerImageDescription != "server description" { + t.Errorf("Expected 'server_image_description_key' to be set to '%s', but got '%s'.", raw["server_image_description"], c.ServerImageDescription) + } + + if c.Region != "Korea" { + t.Errorf("Expected 'region' to be set to '%s', but got '%s'.", raw["server_image_description"], c.Region) + } +} + +func TestEmptyConfig(t *testing.T) { + raw := new(map[string]interface{}) + + _, _, err := NewConfig(raw) + + if err == nil { + t.Error("Expected Config to require 'access_key', 'secret_key' and some mendatory fields, but it did not") + } + + if !strings.Contains(err.Error(), "access_key is required") { + t.Error("Expected Config to require 'access_key', but it did not") + } + + if !strings.Contains(err.Error(), "secret_key is required") { + t.Error("Expected Config to require 'secret_key', but it did not") + } + + if !strings.Contains(err.Error(), "server_image_product_code or member_server_image_no is required") { + t.Error("Expected Config to require 'server_image_product_code' or 'member_server_image_no', but it did not") + } +} + +func TestExistsBothServerImageProductCodeAndMemberServerImageNoConfig(t *testing.T) { + raw := map[string]interface{}{ + "access_key": "access_key", + "secret_key": "secret_key", + "os_type": "Windows", + "server_image_product_code": "SPSW0WINNT000016", + "server_product_code": "SPSVRSSD00000011", + "member_server_image_no": "2440", + } + + _, _, err := NewConfig(raw) + + if !strings.Contains(err.Error(), "Only one of server_image_product_code and member_server_image_no can be set") { + t.Error("Expected Config to require Only one of 'server_image_product_code' and 'member_server_image_no' can be set, but it did not") + } +} diff --git a/builder/ncloud/ssh.go b/builder/ncloud/ssh.go new file mode 100644 index 000000000..ee7d99226 --- /dev/null +++ b/builder/ncloud/ssh.go @@ -0,0 +1,30 @@ +package ncloud + +import ( + packerssh "github.com/hashicorp/packer/communicator/ssh" + "github.com/mitchellh/multistep" + "golang.org/x/crypto/ssh" +) + +func SSHHost(state multistep.StateBag) (string, error) { + host := state.Get("SSHHost").(string) + return host, nil +} + +// SSHConfig returns a function that can be used for the SSH communicator +// config for connecting to the specified host via SSH +func SSHConfig(username string) func(multistep.StateBag) (*ssh.ClientConfig, error) { + return func(state multistep.StateBag) (*ssh.ClientConfig, error) { + password := state.Get("Password").(string) + + return &ssh.ClientConfig{ + User: username, + Auth: []ssh.AuthMethod{ + ssh.Password(password), + ssh.KeyboardInteractive( + packerssh.PasswordKeyboardInteractive(password)), + }, + HostKeyCallback: ssh.InsecureIgnoreHostKey(), + }, nil + } +} diff --git a/builder/ncloud/step.go b/builder/ncloud/step.go new file mode 100644 index 000000000..ba71efbee --- /dev/null +++ b/builder/ncloud/step.go @@ -0,0 +1,16 @@ +package ncloud + +import ( + "github.com/mitchellh/multistep" +) + +func processStepResult(err error, sayError func(error), state multistep.StateBag) multistep.StepAction { + if err != nil { + state.Put("Error", err) + sayError(err) + + return multistep.ActionHalt + } + + return multistep.ActionContinue +} diff --git a/builder/ncloud/step_create_block_storage_instance.go b/builder/ncloud/step_create_block_storage_instance.go new file mode 100644 index 000000000..ef7306264 --- /dev/null +++ b/builder/ncloud/step_create_block_storage_instance.go @@ -0,0 +1,101 @@ +package ncloud + +import ( + "errors" + "fmt" + "log" + "time" + + ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" + "github.com/hashicorp/packer/packer" + "github.com/mitchellh/multistep" +) + +// StepCreateBlockStorageInstance struct is for making extra block storage +type StepCreateBlockStorageInstance struct { + Conn *ncloud.Conn + CreateBlockStorageInstance func(serverInstanceNo string) (string, error) + Say func(message string) + Error func(e error) + Config *Config +} + +// NewStepCreateBlockStorageInstance make StepCreateBlockStorage struct to make extra block storage +func NewStepCreateBlockStorageInstance(conn *ncloud.Conn, ui packer.Ui, config *Config) *StepCreateBlockStorageInstance { + var step = &StepCreateBlockStorageInstance{ + Conn: conn, + Say: func(message string) { ui.Say(message) }, + Error: func(e error) { ui.Error(e.Error()) }, + Config: config, + } + + step.CreateBlockStorageInstance = step.createBlockStorageInstance + + return step +} + +func (s *StepCreateBlockStorageInstance) createBlockStorageInstance(serverInstanceNo string) (string, error) { + + reqParams := new(ncloud.RequestBlockStorageInstance) + reqParams.BlockStorageSize = s.Config.BlockStorageSize + reqParams.ServerInstanceNo = serverInstanceNo + + blockStorageInstanceList, err := s.Conn.CreateBlockStorageInstance(reqParams) + if err != nil { + return "", fmt.Errorf("error code: %d, error message: %s", blockStorageInstanceList.ReturnCode, blockStorageInstanceList.ReturnMessage) + } + + log.Println("Block Storage Instance information : ", blockStorageInstanceList.BlockStorageInstance[0]) + + if err := waiterBlockStorageInstanceStatus(s.Conn, blockStorageInstanceList.BlockStorageInstance[0].BlockStorageInstanceNo, "ATTAC", 10*time.Minute); err != nil { + return "", errors.New("TIMEOUT : Block Storage instance status is not attached") + } + + return blockStorageInstanceList.BlockStorageInstance[0].BlockStorageInstanceNo, nil +} + +func (s *StepCreateBlockStorageInstance) Run(state multistep.StateBag) multistep.StepAction { + if s.Config.BlockStorageSize == 0 { + return processStepResult(nil, s.Error, state) + } + + s.Say("Create extra block storage instance") + + serverInstanceNo := state.Get("InstanceNo").(string) + + blockStorageInstanceNo, err := s.CreateBlockStorageInstance(serverInstanceNo) + if err == nil { + state.Put("BlockStorageInstanceNo", blockStorageInstanceNo) + } + + return processStepResult(err, s.Error, state) +} + +func (s *StepCreateBlockStorageInstance) Cleanup(state multistep.StateBag) { + _, cancelled := state.GetOk(multistep.StateCancelled) + _, halted := state.GetOk(multistep.StateHalted) + + if !cancelled && !halted { + return + } + + if s.Config.BlockStorageSize == 0 { + return + } + + if blockStorageInstanceNo, ok := state.GetOk("BlockStorageInstanceNo"); ok { + s.Say("Clean up Block Storage Instance") + no := blockStorageInstanceNo.(string) + blockStorageInstanceList, err := s.Conn.DeleteBlockStorageInstances([]string{no}) + if err != nil { + return + } + + s.Say(fmt.Sprintf("Block Storage Instance is deleted. Block Storage InstanceNo is %s", no)) + log.Println("Block Storage Instance information : ", blockStorageInstanceList.BlockStorageInstance[0]) + + if err := waiterBlockStorageInstanceStatus(s.Conn, no, "DETAC", time.Minute); err != nil { + s.Say("TIMEOUT : Block Storage instance status is not deattached") + } + } +} diff --git a/builder/ncloud/step_create_block_storage_instance_test.go b/builder/ncloud/step_create_block_storage_instance_test.go new file mode 100644 index 000000000..101e94658 --- /dev/null +++ b/builder/ncloud/step_create_block_storage_instance_test.go @@ -0,0 +1,62 @@ +package ncloud + +import ( + "fmt" + "github.com/mitchellh/multistep" + "testing" +) + +func TestStepCreateBlockStorageInstanceShouldFailIfOperationCreateBlockStorageInstanceFails(t *testing.T) { + + var testSubject = &StepCreateBlockStorageInstance{ + CreateBlockStorageInstance: func(serverInstanceNo string) (string, error) { return "", fmt.Errorf("!! Unit Test FAIL !!") }, + Say: func(message string) {}, + Error: func(e error) {}, + Config: new(Config), + } + + testSubject.Config.BlockStorageSize = 10 + + stateBag := createTestStateBagStepCreateBlockStorageInstance() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionHalt { + t.Fatalf("Expected the step to return 'ActionHalt', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == false { + t.Fatal("Expected the step to set stateBag['Error'], but it was not.") + } +} + +func TestStepCreateBlockStorageInstanceShouldPassIfOperationCreateBlockStorageInstancePasses(t *testing.T) { + var testSubject = &StepCreateBlockStorageInstance{ + CreateBlockStorageInstance: func(serverInstanceNo string) (string, error) { return "a", nil }, + Say: func(message string) {}, + Error: func(e error) {}, + Config: new(Config), + } + + testSubject.Config.BlockStorageSize = 10 + + stateBag := createTestStateBagStepCreateBlockStorageInstance() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionContinue { + t.Fatalf("Expected the step to return 'ActionContinue', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == true { + t.Fatalf("Expected the step to not set stateBag['Error'], but it was.") + } +} + +func createTestStateBagStepCreateBlockStorageInstance() multistep.StateBag { + stateBag := new(multistep.BasicStateBag) + + stateBag.Put("InstanceNo", "a") + + return stateBag +} diff --git a/builder/ncloud/step_create_login_key.go b/builder/ncloud/step_create_login_key.go new file mode 100644 index 000000000..7dddebd25 --- /dev/null +++ b/builder/ncloud/step_create_login_key.go @@ -0,0 +1,71 @@ +package ncloud + +import ( + "fmt" + "time" + + ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" + "github.com/hashicorp/packer/packer" + "github.com/mitchellh/multistep" +) + +type LoginKey struct { + KeyName string + PrivateKey string +} + +type StepCreateLoginKey struct { + Conn *ncloud.Conn + CreateLoginKey func() (*LoginKey, error) + Say func(message string) + Error func(e error) +} + +func NewStepCreateLoginKey(conn *ncloud.Conn, ui packer.Ui) *StepCreateLoginKey { + var step = &StepCreateLoginKey{ + Conn: conn, + Say: func(message string) { ui.Say(message) }, + Error: func(e error) { ui.Error(e.Error()) }, + } + + step.CreateLoginKey = step.createLoginKey + + return step +} + +func (s *StepCreateLoginKey) createLoginKey() (*LoginKey, error) { + KeyName := fmt.Sprintf("packer-%d", time.Now().Unix()) + + privateKey, err := s.Conn.CreateLoginKey(KeyName) + if err != nil { + return nil, fmt.Errorf("error code: %d , error message: %s", privateKey.ReturnCode, privateKey.ReturnMessage) + } + + return &LoginKey{KeyName, privateKey.PrivateKey}, nil +} + +func (s *StepCreateLoginKey) Run(state multistep.StateBag) multistep.StepAction { + s.Say("Create Login Key") + + loginKey, err := s.CreateLoginKey() + if err == nil { + state.Put("LoginKey", loginKey) + s.Say(fmt.Sprintf("Login Key[%s] is created", loginKey.KeyName)) + } + + return processStepResult(err, s.Error, state) +} + +func (s *StepCreateLoginKey) Cleanup(state multistep.StateBag) { + _, cancelled := state.GetOk(multistep.StateCancelled) + _, halted := state.GetOk(multistep.StateHalted) + + if !cancelled && !halted { + return + } + + if loginKey, ok := state.GetOk("LoginKey"); ok { + s.Say("Clean up login key") + s.Conn.DeleteLoginKey(loginKey.(*LoginKey).KeyName) + } +} diff --git a/builder/ncloud/step_create_login_key_test.go b/builder/ncloud/step_create_login_key_test.go new file mode 100644 index 000000000..374d10330 --- /dev/null +++ b/builder/ncloud/step_create_login_key_test.go @@ -0,0 +1,53 @@ +package ncloud + +import ( + "fmt" + "github.com/mitchellh/multistep" + "testing" +) + +func TestStepCreateLoginKeyShouldFailIfOperationCreateLoginKeyFails(t *testing.T) { + var testSubject = &StepCreateLoginKey{ + CreateLoginKey: func() (*LoginKey, error) { return nil, fmt.Errorf("!! Unit Test FAIL !!") }, + Say: func(message string) {}, + Error: func(e error) {}, + } + + stateBag := createTestStateBagStepCreateLoginKey() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionHalt { + t.Fatalf("Expected the step to return 'ActionHalt', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == false { + t.Fatal("Expected the step to set stateBag['Error'], but it was not.") + } +} + +func TestStepCreateLoginKeyShouldPassIfOperationCreateLoginKeyPasses(t *testing.T) { + var testSubject = &StepCreateLoginKey{ + CreateLoginKey: func() (*LoginKey, error) { return &LoginKey{"a", "b"}, nil }, + Say: func(message string) {}, + Error: func(e error) {}, + } + + stateBag := createTestStateBagStepCreateLoginKey() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionContinue { + t.Fatalf("Expected the step to return 'ActionContinue', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == true { + t.Fatalf("Expected the step to not set stateBag['Error'], but it was.") + } +} + +func createTestStateBagStepCreateLoginKey() multistep.StateBag { + stateBag := new(multistep.BasicStateBag) + + return stateBag +} diff --git a/builder/ncloud/step_create_public_ip_instance.go b/builder/ncloud/step_create_public_ip_instance.go new file mode 100644 index 000000000..88d98eb6c --- /dev/null +++ b/builder/ncloud/step_create_public_ip_instance.go @@ -0,0 +1,167 @@ +package ncloud + +import ( + "fmt" + "log" + "time" + + ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" + "github.com/hashicorp/packer/packer" + "github.com/mitchellh/multistep" +) + +type StepCreatePublicIPInstance struct { + Conn *ncloud.Conn + CreatePublicIPInstance func(serverInstanceNo string) (*ncloud.PublicIPInstance, error) + WaiterAssociatePublicIPToServerInstance func(serverInstanceNo string, publicIP string) error + Say func(message string) + Error func(e error) + Config *Config +} + +func NewStepCreatePublicIPInstance(conn *ncloud.Conn, ui packer.Ui, config *Config) *StepCreatePublicIPInstance { + var step = &StepCreatePublicIPInstance{ + Conn: conn, + Say: func(message string) { ui.Say(message) }, + Error: func(e error) { ui.Error(e.Error()) }, + Config: config, + } + + step.CreatePublicIPInstance = step.createPublicIPInstance + step.WaiterAssociatePublicIPToServerInstance = step.waiterAssociatePublicIPToServerInstance + + return step +} + +func (s *StepCreatePublicIPInstance) waiterAssociatePublicIPToServerInstance(serverInstanceNo string, publicIP string) error { + reqParams := new(ncloud.RequestGetServerInstanceList) + reqParams.ServerInstanceNoList = []string{serverInstanceNo} + + c1 := make(chan error, 1) + + go func() { + for { + serverInstanceList, err := s.Conn.GetServerInstanceList(reqParams) + + if err != nil { + c1 <- err + return + } + + if publicIP == serverInstanceList.ServerInstanceList[0].PublicIP { + c1 <- nil + return + } + + s.Say("Wait to associate public ip serverInstance") + time.Sleep(time.Second * 3) + } + }() + + select { + case res := <-c1: + return res + case <-time.After(time.Second * 60): + return fmt.Errorf("TIMEOUT : association public ip[%s] to server instance[%s] Failed", publicIP, serverInstanceNo) + } +} + +func (s *StepCreatePublicIPInstance) createPublicIPInstance(serverInstanceNo string) (*ncloud.PublicIPInstance, error) { + reqParams := new(ncloud.RequestCreatePublicIPInstance) + reqParams.ServerInstanceNo = serverInstanceNo + + publicIPInstanceList, err := s.Conn.CreatePublicIPInstance(reqParams) + if err != nil { + return nil, fmt.Errorf("error code: %d, error message: %s", publicIPInstanceList.ReturnCode, publicIPInstanceList.ReturnMessage) + } + + publicIPInstance := publicIPInstanceList.PublicIPInstanceList[0] + publicIP := publicIPInstance.PublicIP + s.Say(fmt.Sprintf("Public IP Instance [%s:%s] is created", publicIPInstance.PublicIPInstanceNo, publicIP)) + + err = s.waiterAssociatePublicIPToServerInstance(serverInstanceNo, publicIP) + + return &publicIPInstance, nil +} + +func (s *StepCreatePublicIPInstance) Run(state multistep.StateBag) multistep.StepAction { + s.Say("Create Public IP Instance") + + serverInstanceNo := state.Get("InstanceNo").(string) + + publicIPInstance, err := s.CreatePublicIPInstance(serverInstanceNo) + if err == nil { + switch s.Config.OSType { + case "Linux": + state.Put("SSHHost", publicIPInstance.PublicIP) + case "Windows": + state.Put("WinRMHost", publicIPInstance.PublicIP) + } + + state.Put("PublicIPInstance", publicIPInstance) + } + + return processStepResult(err, s.Error, state) +} + +func (s *StepCreatePublicIPInstance) Cleanup(state multistep.StateBag) { + _, cancelled := state.GetOk(multistep.StateCancelled) + _, halted := state.GetOk(multistep.StateHalted) + + if !cancelled && !halted { + return + } + + publicIPInstance, ok := state.GetOk("PublicIPInstance") + if !ok { + return + } + + s.Say("Clean up Public IP Instance") + publicIPInstanceNo := publicIPInstance.(*ncloud.PublicIPInstance).PublicIPInstanceNo + s.waitPublicIPInstanceStatus(publicIPInstanceNo, "USED") + + log.Println("Disassociate Public IP Instance ", publicIPInstanceNo) + s.Conn.DisassociatePublicIP(publicIPInstanceNo) + + s.waitPublicIPInstanceStatus(publicIPInstanceNo, "CREAT") + + reqParams := new(ncloud.RequestDeletePublicIPInstances) + reqParams.PublicIPInstanceNoList = []string{publicIPInstanceNo} + + log.Println("Delete Public IP Instance ", publicIPInstanceNo) + s.Conn.DeletePublicIPInstances(reqParams) +} + +func (s *StepCreatePublicIPInstance) waitPublicIPInstanceStatus(publicIPInstanceNo string, status string) { + c1 := make(chan error, 1) + + go func() { + reqParams := new(ncloud.RequestPublicIPInstanceList) + reqParams.PublicIPInstanceNoList = []string{publicIPInstanceNo} + + for { + resp, err := s.Conn.GetPublicIPInstanceList(reqParams) + if err != nil { + log.Printf("error code: %d, error message: %s", resp.ReturnCode, resp.ReturnMessage) + c1 <- err + return + } + + instance := resp.PublicIPInstanceList[0] + if instance.PublicIPInstanceStatus.Code == status && instance.PublicIPInstanceOperation.Code == "NULL" { + c1 <- nil + return + } + + time.Sleep(time.Second * 2) + } + }() + + select { + case <-c1: + return + case <-time.After(time.Second * 60): + return + } +} diff --git a/builder/ncloud/step_create_public_ip_instance_test.go b/builder/ncloud/step_create_public_ip_instance_test.go new file mode 100644 index 000000000..30eaca017 --- /dev/null +++ b/builder/ncloud/step_create_public_ip_instance_test.go @@ -0,0 +1,62 @@ +package ncloud + +import ( + "fmt" + ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" + "testing" + + "github.com/mitchellh/multistep" +) + +func TestStepCreatePublicIPInstanceShouldFailIfOperationCreatePublicIPInstanceFails(t *testing.T) { + var testSubject = &StepCreatePublicIPInstance{ + CreatePublicIPInstance: func(serverInstanceNo string) (*ncloud.PublicIPInstance, error) { + return nil, fmt.Errorf("!! Unit Test FAIL !!") + }, + Say: func(message string) {}, + Error: func(e error) {}, + } + + stateBag := createTestStateBagStepCreateServerImage() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionHalt { + t.Fatalf("Expected the step to return 'ActionHalt', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == false { + t.Fatal("Expected the step to set stateBag['Error'], but it was not.") + } +} + +func TestStepCreatePublicIPInstanceShouldPassIfOperationCreatePublicIPInstancePasses(t *testing.T) { + var testSubject = &StepCreatePublicIPInstance{ + CreatePublicIPInstance: func(serverInstanceNo string) (*ncloud.PublicIPInstance, error) { + return &ncloud.PublicIPInstance{PublicIPInstanceNo: "a", PublicIP: "b"}, nil + }, + Say: func(message string) {}, + Error: func(e error) {}, + Config: &Config{OSType: "Windows"}, + } + + stateBag := createTestStateBagStepCreatePublicIPInstance() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionContinue { + t.Fatalf("Expected the step to return 'ActionContinue', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == true { + t.Fatalf("Expected the step to not set stateBag['Error'], but it was.") + } +} + +func createTestStateBagStepCreatePublicIPInstance() multistep.StateBag { + stateBag := new(multistep.BasicStateBag) + + stateBag.Put("InstanceNo", "a") + + return stateBag +} diff --git a/builder/ncloud/step_create_server_image.go b/builder/ncloud/step_create_server_image.go new file mode 100644 index 000000000..4256664f4 --- /dev/null +++ b/builder/ncloud/step_create_server_image.go @@ -0,0 +1,77 @@ +package ncloud + +import ( + "errors" + "fmt" + "time" + + ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" + "github.com/hashicorp/packer/packer" + "github.com/mitchellh/multistep" +) + +type StepCreateServerImage struct { + Conn *ncloud.Conn + CreateServerImage func(serverInstanceNo string) (*ncloud.ServerImage, error) + Say func(message string) + Error func(e error) + Config *Config +} + +func NewStepCreateServerImage(conn *ncloud.Conn, ui packer.Ui, config *Config) *StepCreateServerImage { + var step = &StepCreateServerImage{ + Conn: conn, + Say: func(message string) { ui.Say(message) }, + Error: func(e error) { ui.Error(e.Error()) }, + Config: config, + } + + step.CreateServerImage = step.createServerImage + + return step +} + +func (s *StepCreateServerImage) createServerImage(serverInstanceNo string) (*ncloud.ServerImage, error) { + // 서버 인스턴스 상태가 정지 중일 경우에는 서버 이미지 생성할 수 없음. + if err := waiterServerInstanceStatus(s.Conn, serverInstanceNo, "NSTOP", 1*time.Minute); err != nil { + return nil, err + } + + reqParams := new(ncloud.RequestCreateServerImage) + reqParams.MemberServerImageName = s.Config.ServerImageName + reqParams.MemberServerImageDescription = s.Config.ServerImageDescription + reqParams.ServerInstanceNo = serverInstanceNo + + memberServerImageList, err := s.Conn.CreateMemberServerImage(reqParams) + if err != nil { + return nil, fmt.Errorf("error code: %d , error message: %s", memberServerImageList.ReturnCode, memberServerImageList.ReturnMessage) + } + + serverImage := memberServerImageList.MemberServerImageList[0] + + s.Say(fmt.Sprintf("Server Image[%s:%s] is creating...", serverImage.MemberServerImageName, serverImage.MemberServerImageNo)) + + if err := waiterMemberServerImageStatus(s.Conn, serverImage.MemberServerImageNo, "CREAT", 6*time.Hour); err != nil { + return nil, errors.New("TIMEOUT : Server Image is not created") + } + + s.Say(fmt.Sprintf("Server Image[%s:%s] is created", serverImage.MemberServerImageName, serverImage.MemberServerImageNo)) + + return &serverImage, nil +} + +func (s *StepCreateServerImage) Run(state multistep.StateBag) multistep.StepAction { + s.Say("Create Server Image") + + serverInstanceNo := state.Get("InstanceNo").(string) + + serverImage, err := s.CreateServerImage(serverInstanceNo) + if err == nil { + state.Put("memberServerImage", serverImage) + } + + return processStepResult(err, s.Error, state) +} + +func (*StepCreateServerImage) Cleanup(multistep.StateBag) { +} diff --git a/builder/ncloud/step_create_server_image_test.go b/builder/ncloud/step_create_server_image_test.go new file mode 100644 index 000000000..41a40971a --- /dev/null +++ b/builder/ncloud/step_create_server_image_test.go @@ -0,0 +1,58 @@ +package ncloud + +import ( + "fmt" + ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" + "testing" + + "github.com/mitchellh/multistep" +) + +func TestStepCreateServerImageShouldFailIfOperationCreateServerImageFails(t *testing.T) { + var testSubject = &StepCreateServerImage{ + CreateServerImage: func(serverInstanceNo string) (*ncloud.ServerImage, error) { + return nil, fmt.Errorf("!! Unit Test FAIL !!") + }, + Say: func(message string) {}, + Error: func(e error) {}, + } + + stateBag := createTestStateBagStepCreateServerImage() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionHalt { + t.Fatalf("Expected the step to return 'ActionHalt', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == false { + t.Fatal("Expected the step to set stateBag['Error'], but it was not.") + } +} +func TestStepCreateServerImageShouldPassIfOperationCreateServerImagePasses(t *testing.T) { + var testSubject = &StepCreateServerImage{ + CreateServerImage: func(serverInstanceNo string) (*ncloud.ServerImage, error) { return nil, nil }, + Say: func(message string) {}, + Error: func(e error) {}, + } + + stateBag := createTestStateBagStepCreateServerImage() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionContinue { + t.Fatalf("Expected the step to return 'ActionContinue', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == true { + t.Fatalf("Expected the step to not set stateBag['Error'], but it was.") + } +} + +func createTestStateBagStepCreateServerImage() multistep.StateBag { + stateBag := new(multistep.BasicStateBag) + + stateBag.Put("InstanceNo", "a") + + return stateBag +} diff --git a/builder/ncloud/step_create_server_instance.go b/builder/ncloud/step_create_server_instance.go new file mode 100644 index 000000000..040e72eb1 --- /dev/null +++ b/builder/ncloud/step_create_server_instance.go @@ -0,0 +1,129 @@ +package ncloud + +import ( + "errors" + "fmt" + "log" + "time" + + ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" + "github.com/hashicorp/packer/packer" + "github.com/mitchellh/multistep" +) + +type StepCreateServerInstance struct { + Conn *ncloud.Conn + CreateServerInstance func(loginKeyName string, zoneNo string) (string, error) + CheckServerInstanceStatusIsRunning func(serverInstanceNo string) error + Say func(message string) + Error func(e error) + Config *Config + serverInstanceNo string +} + +func NewStepCreateServerInstance(conn *ncloud.Conn, ui packer.Ui, config *Config) *StepCreateServerInstance { + var step = &StepCreateServerInstance{ + Conn: conn, + Say: func(message string) { ui.Say(message) }, + Error: func(e error) { ui.Error(e.Error()) }, + Config: config, + } + + step.CreateServerInstance = step.createServerInstance + + return step +} + +func (s *StepCreateServerInstance) createServerInstance(loginKeyName string, zoneNo string) (string, error) { + reqParams := new(ncloud.RequestCreateServerInstance) + reqParams.ServerProductCode = s.Config.ServerProductCode + reqParams.MemberServerImageNo = s.Config.MemberServerImageNo + if s.Config.MemberServerImageNo == "" { + reqParams.ServerImageProductCode = s.Config.ServerImageProductCode + } + reqParams.LoginKeyName = loginKeyName + reqParams.ZoneNo = zoneNo + reqParams.FeeSystemTypeCode = s.Config.FeeSystemTypeCode + + if s.Config.UserData != "" { + reqParams.UserData = s.Config.UserData + } + + if s.Config.AccessControlGroupConfigurationNo != "" { + reqParams.AccessControlGroupConfigurationNoList = []string{s.Config.AccessControlGroupConfigurationNo} + } + + serverInstanceList, err := s.Conn.CreateServerInstances(reqParams) + if err != nil { + return "", fmt.Errorf("error code: %d, error message: %s", serverInstanceList.ReturnCode, serverInstanceList.ReturnMessage) + } + + s.serverInstanceNo = serverInstanceList.ServerInstanceList[0].ServerInstanceNo + s.Say(fmt.Sprintf("Server Instance is creating. Server InstanceNo is %s", s.serverInstanceNo)) + log.Println("Server Instance information : ", serverInstanceList.ServerInstanceList[0]) + + if err := waiterServerInstanceStatus(s.Conn, s.serverInstanceNo, "RUN", 30*time.Minute); err != nil { + return "", errors.New("TIMEOUT : server instance status is not running") + } + + s.Say(fmt.Sprintf("Server Instance is created. Server InstanceNo is %s", s.serverInstanceNo)) + + return s.serverInstanceNo, nil +} + +func (s *StepCreateServerInstance) Run(state multistep.StateBag) multistep.StepAction { + s.Say("Create Server Instance") + + var loginKey = state.Get("LoginKey").(*LoginKey) + var zoneNo = state.Get("ZoneNo").(string) + + serverInstanceNo, err := s.CreateServerInstance(loginKey.KeyName, zoneNo) + if err == nil { + state.Put("InstanceNo", serverInstanceNo) + } + + return processStepResult(err, s.Error, state) +} + +func (s *StepCreateServerInstance) Cleanup(state multistep.StateBag) { + _, cancelled := state.GetOk(multistep.StateCancelled) + _, halted := state.GetOk(multistep.StateHalted) + + if !cancelled && !halted { + return + } + + if s.serverInstanceNo == "" { + return + } + + reqParams := new(ncloud.RequestGetServerInstanceList) + reqParams.ServerInstanceNoList = []string{s.serverInstanceNo} + + serverInstanceList, err := s.Conn.GetServerInstanceList(reqParams) + if err != nil || serverInstanceList.TotalRows == 0 { + return + } + + s.Say("Clean up Server Instance") + + serverInstance := serverInstanceList.ServerInstanceList[0] + // stop server instance + if serverInstance.ServerInstanceStatus.Code != "NSTOP" && serverInstance.ServerInstanceStatus.Code != "TERMT" { + reqParams := new(ncloud.RequestStopServerInstances) + reqParams.ServerInstanceNoList = []string{s.serverInstanceNo} + + log.Println("Stop Server Instance") + s.Conn.StopServerInstances(reqParams) + waiterServerInstanceStatus(s.Conn, s.serverInstanceNo, "NSTOP", time.Minute) + } + + // terminate server instance + if serverInstance.ServerInstanceStatus.Code != "TERMT" { + reqParams := new(ncloud.RequestTerminateServerInstances) + reqParams.ServerInstanceNoList = []string{s.serverInstanceNo} + + log.Println("Terminate Server Instance") + s.Conn.TerminateServerInstances(reqParams) + } +} diff --git a/builder/ncloud/step_create_server_instance_test.go b/builder/ncloud/step_create_server_instance_test.go new file mode 100644 index 000000000..327228b75 --- /dev/null +++ b/builder/ncloud/step_create_server_instance_test.go @@ -0,0 +1,58 @@ +package ncloud + +import ( + "fmt" + "github.com/mitchellh/multistep" + "testing" +) + +func TestStepCreateServerInstanceShouldFailIfOperationCreateFails(t *testing.T) { + var testSubject = &StepCreateServerInstance{ + CreateServerInstance: func(loginKeyName string, zoneNo string) (string, error) { + return "", fmt.Errorf("!! Unit Test FAIL !!") + }, + Say: func(message string) {}, + Error: func(e error) {}, + } + + stateBag := createTestStateBagStepCreateServerInstance() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionHalt { + t.Fatalf("Expected the step to return 'ActionHalt', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == false { + t.Fatal("Expected the step to set stateBag['Error'], but it was not.") + } +} + +func TestStepCreateServerInstanceShouldPassIfOperationCreatePasses(t *testing.T) { + var testSubject = &StepCreateServerInstance{ + CreateServerInstance: func(loginKeyName string, zoneNo string) (string, error) { return "", nil }, + Say: func(message string) {}, + Error: func(e error) {}, + } + + stateBag := createTestStateBagStepCreateServerInstance() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionContinue { + t.Fatalf("Expected the step to return 'ActionContinue', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == true { + t.Fatalf("Expected the step to not set stateBag['Error'], but it was.") + } +} + +func createTestStateBagStepCreateServerInstance() multistep.StateBag { + stateBag := new(multistep.BasicStateBag) + + stateBag.Put("LoginKey", &LoginKey{"a", "b"}) + stateBag.Put("ZoneNo", "1") + + return stateBag +} diff --git a/builder/ncloud/step_delete_block_storage_instance.go b/builder/ncloud/step_delete_block_storage_instance.go new file mode 100644 index 000000000..3c6c44b82 --- /dev/null +++ b/builder/ncloud/step_delete_block_storage_instance.go @@ -0,0 +1,95 @@ +package ncloud + +import ( + "errors" + "fmt" + "log" + "time" + + ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" + "github.com/hashicorp/packer/packer" + "github.com/mitchellh/multistep" +) + +type StepDeleteBlockStorageInstance struct { + Conn *ncloud.Conn + DeleteBlockStorageInstance func(blockStorageInstanceNo string) error + Say func(message string) + Error func(e error) + Config *Config +} + +func NewStepDeleteBlockStorageInstance(conn *ncloud.Conn, ui packer.Ui, config *Config) *StepDeleteBlockStorageInstance { + var step = &StepDeleteBlockStorageInstance{ + Conn: conn, + Say: func(message string) { ui.Say(message) }, + Error: func(e error) { ui.Error(e.Error()) }, + Config: config, + } + + step.DeleteBlockStorageInstance = step.deleteBlockStorageInstance + + return step +} + +func (s *StepDeleteBlockStorageInstance) getBlockInstanceList(serverInstanceNo string) []string { + reqParams := new(ncloud.RequestBlockStorageInstanceList) + reqParams.ServerInstanceNo = serverInstanceNo + + blockStorageInstanceList, err := s.Conn.GetBlockStorageInstance(reqParams) + if err != nil { + return nil + } + + if blockStorageInstanceList.TotalRows == 1 { + return nil + } + + var instanceList []string + + for _, blockStorageInstance := range blockStorageInstanceList.BlockStorageInstance { + log.Println(blockStorageInstance) + if blockStorageInstance.BlockStorageType.Code != "BASIC" { + instanceList = append(instanceList, blockStorageInstance.BlockStorageInstanceNo) + } + } + + return instanceList +} + +func (s *StepDeleteBlockStorageInstance) deleteBlockStorageInstance(serverInstanceNo string) error { + blockStorageInstanceList := s.getBlockInstanceList(serverInstanceNo) + if blockStorageInstanceList == nil || len(blockStorageInstanceList) == 0 { + return nil + } + + result, err := s.Conn.DeleteBlockStorageInstances(blockStorageInstanceList) + if err != nil { + return fmt.Errorf("error code: %d , error message: %s", result.ReturnCode, result.ReturnMessage) + } + + s.Say(fmt.Sprintf("Block Storage Instance is deleted. Block Storage InstanceNo is %s", blockStorageInstanceList)) + + if err := waiterDetachedBlockStorageInstance(s.Conn, serverInstanceNo, time.Minute); err != nil { + return errors.New("TIMEOUT : Block Storage instance status is not deattached") + } + + return nil +} + +func (s *StepDeleteBlockStorageInstance) Run(state multistep.StateBag) multistep.StepAction { + if s.Config.BlockStorageSize == 0 { + return processStepResult(nil, s.Error, state) + } + + s.Say("Delete Block Storage Instance") + + var serverInstanceNo = state.Get("InstanceNo").(string) + + err := s.DeleteBlockStorageInstance(serverInstanceNo) + + return processStepResult(err, s.Error, state) +} + +func (*StepDeleteBlockStorageInstance) Cleanup(multistep.StateBag) { +} diff --git a/builder/ncloud/step_delete_block_storage_instance_test.go b/builder/ncloud/step_delete_block_storage_instance_test.go new file mode 100644 index 000000000..ce0f0cb09 --- /dev/null +++ b/builder/ncloud/step_delete_block_storage_instance_test.go @@ -0,0 +1,57 @@ +package ncloud + +import ( + "fmt" + "github.com/mitchellh/multistep" + "testing" +) + +func TestStepDeleteBlockStorageInstanceShouldFailIfOperationDeleteBlockStorageInstanceFails(t *testing.T) { + var testSubject = &StepDeleteBlockStorageInstance{ + DeleteBlockStorageInstance: func(blockStorageInstanceNo string) error { return fmt.Errorf("!! Unit Test FAIL !!") }, + Say: func(message string) {}, + Error: func(e error) {}, + Config: &Config{BlockStorageSize: 10}, + } + + stateBag := createTestStateBagStepDeleteBlockStorageInstance() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionHalt { + t.Fatalf("Expected the step to return 'ActionHalt', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == false { + t.Fatal("Expected the step to set stateBag['Error'], but it was not.") + } +} + +func TestStepDeleteBlockStorageInstanceShouldPassIfOperationDeleteBlockStorageInstancePasses(t *testing.T) { + var testSubject = &StepDeleteBlockStorageInstance{ + DeleteBlockStorageInstance: func(blockStorageInstanceNo string) error { return nil }, + Say: func(message string) {}, + Error: func(e error) {}, + Config: &Config{BlockStorageSize: 10}, + } + + stateBag := createTestStateBagStepDeleteBlockStorageInstance() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionContinue { + t.Fatalf("Expected the step to return 'ActionContinue', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == true { + t.Fatalf("Expected the step to not set stateBag['Error'], but it was.") + } +} + +func createTestStateBagStepDeleteBlockStorageInstance() multistep.StateBag { + stateBag := new(multistep.BasicStateBag) + + stateBag.Put("InstanceNo", "1") + + return stateBag +} diff --git a/builder/ncloud/step_delete_login_key.go b/builder/ncloud/step_delete_login_key.go new file mode 100644 index 000000000..b0cfbf7a1 --- /dev/null +++ b/builder/ncloud/step_delete_login_key.go @@ -0,0 +1,51 @@ +package ncloud + +import ( + "fmt" + + ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" + "github.com/hashicorp/packer/packer" + "github.com/mitchellh/multistep" +) + +type StepDeleteLoginKey struct { + Conn *ncloud.Conn + DeleteLoginKey func(keyName string) error + Say func(message string) + Error func(e error) +} + +func NewStepDeleteLoginKey(conn *ncloud.Conn, ui packer.Ui) *StepDeleteLoginKey { + var step = &StepDeleteLoginKey{ + Conn: conn, + Say: func(message string) { ui.Say(message) }, + Error: func(e error) { ui.Error(e.Error()) }, + } + + step.DeleteLoginKey = step.deleteLoginKey + + return step +} + +func (s *StepDeleteLoginKey) deleteLoginKey(keyName string) error { + resp, err := s.Conn.DeleteLoginKey(keyName) + if err != nil { + return fmt.Errorf("error code: %d , error message: %s", resp.ReturnCode, resp.ReturnMessage) + } + + return nil +} + +func (s *StepDeleteLoginKey) Run(state multistep.StateBag) multistep.StepAction { + var loginKey = state.Get("LoginKey").(*LoginKey) + + err := s.DeleteLoginKey(loginKey.KeyName) + if err == nil { + s.Say(fmt.Sprintf("Login Key[%s] is deleted", loginKey.KeyName)) + } + + return processStepResult(err, s.Error, state) +} + +func (*StepDeleteLoginKey) Cleanup(multistep.StateBag) { +} diff --git a/builder/ncloud/step_delete_login_key_test.go b/builder/ncloud/step_delete_login_key_test.go new file mode 100644 index 000000000..38ce1e22c --- /dev/null +++ b/builder/ncloud/step_delete_login_key_test.go @@ -0,0 +1,55 @@ +package ncloud + +import ( + "fmt" + "github.com/mitchellh/multistep" + "testing" +) + +func TestStepDeleteLoginKeyShouldFailIfOperationDeleteLoginKeyFails(t *testing.T) { + var testSubject = &StepDeleteLoginKey{ + DeleteLoginKey: func(keyName string) error { return fmt.Errorf("!! Unit Test FAIL !!") }, + Say: func(message string) {}, + Error: func(e error) {}, + } + + stateBag := DeleteTestStateBagStepDeleteLoginKey() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionHalt { + t.Fatalf("Expected the step to return 'ActionHalt', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == false { + t.Fatal("Expected the step to set stateBag['Error'], but it was not.") + } +} + +func TestStepDeleteLoginKeyShouldPassIfOperationDeleteLoginKeyPasses(t *testing.T) { + var testSubject = &StepDeleteLoginKey{ + DeleteLoginKey: func(keyName string) error { return nil }, + Say: func(message string) {}, + Error: func(e error) {}, + } + + stateBag := DeleteTestStateBagStepDeleteLoginKey() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionContinue { + t.Fatalf("Expected the step to return 'ActionContinue', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == true { + t.Fatalf("Expected the step to not set stateBag['Error'], but it was.") + } +} + +func DeleteTestStateBagStepDeleteLoginKey() multistep.StateBag { + stateBag := new(multistep.BasicStateBag) + + stateBag.Put("LoginKey", &LoginKey{"a", "b"}) + + return stateBag +} diff --git a/builder/ncloud/step_delete_public_ip_instance.go b/builder/ncloud/step_delete_public_ip_instance.go new file mode 100644 index 000000000..4a1401984 --- /dev/null +++ b/builder/ncloud/step_delete_public_ip_instance.go @@ -0,0 +1,78 @@ +package ncloud + +import ( + "errors" + "fmt" + "log" + "time" + + ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" + "github.com/hashicorp/packer/packer" + "github.com/mitchellh/multistep" +) + +type StepDeletePublicIPInstance struct { + Conn *ncloud.Conn + DeletePublicIPInstance func(publicIPInstanceNo string) error + Say func(message string) + Error func(e error) +} + +func NewStepDeletePublicIPInstance(conn *ncloud.Conn, ui packer.Ui) *StepDeletePublicIPInstance { + var step = &StepDeletePublicIPInstance{ + Conn: conn, + Say: func(message string) { ui.Say(message) }, + Error: func(e error) { ui.Error(e.Error()) }, + } + + step.DeletePublicIPInstance = step.deletePublicIPInstance + + return step +} + +func (s *StepDeletePublicIPInstance) deletePublicIPInstance(publicIPInstanceNo string) error { + reqParams := new(ncloud.RequestDeletePublicIPInstances) + reqParams.PublicIPInstanceNoList = []string{publicIPInstanceNo} + + c1 := make(chan error, 1) + + go func() { + for { + resp, err := s.Conn.DeletePublicIPInstances(reqParams) + if err != nil && (resp.ReturnCode == 24073 || resp.ReturnCode == 25032) { + // error code : 24073 : Unable to destroy the server since a public IP is associated with the server. First, please disassociate a public IP from the server. + // error code : 25032 : You may not delete sk since (other) user is changing the target official IP settings. + log.Println(resp.ReturnCode, resp.ReturnMessage) + } else if err != nil { + c1 <- fmt.Errorf("error code: %d, error message: %s", resp.ReturnCode, resp.ReturnMessage) + return + } else if err == nil { + s.Say(fmt.Sprintf("Public IP Instance [%s] is deleted.", publicIPInstanceNo)) + c1 <- nil + return + } + + time.Sleep(time.Second * 5) + } + }() + + select { + case res := <-c1: + return res + case <-time.After(time.Second * 60): + return errors.New("TIMEOUT : Can't delete server instance") + } +} + +func (s *StepDeletePublicIPInstance) Run(state multistep.StateBag) multistep.StepAction { + s.Say("Delete Public IP Instance") + + publicIPInstance := state.Get("PublicIPInstance").(*ncloud.PublicIPInstance) + + err := s.DeletePublicIPInstance(publicIPInstance.PublicIPInstanceNo) + + return processStepResult(err, s.Error, state) +} + +func (*StepDeletePublicIPInstance) Cleanup(multistep.StateBag) { +} diff --git a/builder/ncloud/step_delete_public_ip_instance_test.go b/builder/ncloud/step_delete_public_ip_instance_test.go new file mode 100644 index 000000000..b9fa04ec8 --- /dev/null +++ b/builder/ncloud/step_delete_public_ip_instance_test.go @@ -0,0 +1,57 @@ +package ncloud + +import ( + "fmt" + ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" + "testing" + + "github.com/mitchellh/multistep" +) + +func TestStepDeletePublicIPInstanceShouldFailIfOperationDeletePublicIPInstanceFails(t *testing.T) { + var testSubject = &StepDeletePublicIPInstance{ + DeletePublicIPInstance: func(publicIPInstanceNo string) error { return fmt.Errorf("!! Unit Test FAIL !!") }, + Say: func(message string) {}, + Error: func(e error) {}, + } + + stateBag := createTestStateBagStepDeletePublicIPInstance() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionHalt { + t.Fatalf("Expected the step to return 'ActionHalt', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == false { + t.Fatal("Expected the step to set stateBag['Error'], but it was not.") + } +} + +func TestStepDeletePublicIPInstanceShouldPassIfOperationDeletePublicIPInstancePasses(t *testing.T) { + var testSubject = &StepDeletePublicIPInstance{ + DeletePublicIPInstance: func(publicIPInstanceNo string) error { return nil }, + Say: func(message string) {}, + Error: func(e error) {}, + } + + stateBag := createTestStateBagStepDeletePublicIPInstance() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionContinue { + t.Fatalf("Expected the step to return 'ActionContinue', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == true { + t.Fatalf("Expected the step to not set stateBag['Error'], but it was.") + } +} + +func createTestStateBagStepDeletePublicIPInstance() multistep.StateBag { + stateBag := new(multistep.BasicStateBag) + + stateBag.Put("PublicIPInstance", &ncloud.PublicIPInstance{PublicIPInstanceNo: "22"}) + + return stateBag +} diff --git a/builder/ncloud/step_get_rootpassword.go b/builder/ncloud/step_get_rootpassword.go new file mode 100644 index 000000000..c5070d179 --- /dev/null +++ b/builder/ncloud/step_get_rootpassword.go @@ -0,0 +1,57 @@ +package ncloud + +import ( + "fmt" + + ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" + "github.com/hashicorp/packer/packer" + "github.com/mitchellh/multistep" +) + +type StepGetRootPassword struct { + Conn *ncloud.Conn + GetRootPassword func(serverInstanceNo string, privateKey string) (string, error) + Say func(message string) + Error func(e error) +} + +func NewStepGetRootPassword(conn *ncloud.Conn, ui packer.Ui) *StepGetRootPassword { + var step = &StepGetRootPassword{ + Conn: conn, + Say: func(message string) { ui.Say(message) }, + Error: func(e error) { ui.Error(e.Error()) }, + } + + step.GetRootPassword = step.getRootPassword + + return step +} + +func (s *StepGetRootPassword) getRootPassword(serverInstanceNo string, privateKey string) (string, error) { + reqParams := new(ncloud.RequestGetRootPassword) + reqParams.ServerInstanceNo = serverInstanceNo + reqParams.PrivateKey = privateKey + + rootPassword, err := s.Conn.GetRootPassword(reqParams) + if err != nil { + return "", fmt.Errorf("error code: %d, error message: %s", rootPassword.ReturnCode, rootPassword.ReturnMessage) + } + + return rootPassword.RootPassword, nil +} + +func (s *StepGetRootPassword) Run(state multistep.StateBag) multistep.StepAction { + s.Say("Get Root Password") + + serverInstanceNo := state.Get("InstanceNo").(string) + loginKey := state.Get("LoginKey").(*LoginKey) + + rootPassword, err := s.GetRootPassword(serverInstanceNo, loginKey.PrivateKey) + + state.Put("Password", rootPassword) + + return processStepResult(err, s.Error, state) +} + +func (*StepGetRootPassword) Cleanup(multistep.StateBag) { +} diff --git a/builder/ncloud/step_get_rootpassword_test.go b/builder/ncloud/step_get_rootpassword_test.go new file mode 100644 index 000000000..b9ed6aa56 --- /dev/null +++ b/builder/ncloud/step_get_rootpassword_test.go @@ -0,0 +1,56 @@ +package ncloud + +import ( + "fmt" + "github.com/mitchellh/multistep" + "testing" +) + +func TestStepGetRootPasswordShouldFailIfOperationGetRootPasswordFails(t *testing.T) { + var testSubject = &StepGetRootPassword{ + GetRootPassword: func(string, string) (string, error) { return "", fmt.Errorf("!! Unit Test FAIL !!") }, + Say: func(message string) {}, + Error: func(e error) {}, + } + + stateBag := DeleteTestStateBagStepGetRootPassword() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionHalt { + t.Fatalf("Expected the step to return 'ActionHalt', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == false { + t.Fatal("Expected the step to set stateBag['Error'], but it was not.") + } +} + +func TestStepGetRootPasswordShouldPassIfOperationGetRootPasswordPasses(t *testing.T) { + var testSubject = &StepGetRootPassword{ + GetRootPassword: func(string, string) (string, error) { return "a", nil }, + Say: func(message string) {}, + Error: func(e error) {}, + } + + stateBag := DeleteTestStateBagStepGetRootPassword() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionContinue { + t.Fatalf("Expected the step to return 'ActionContinue', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == true { + t.Fatalf("Expected the step to not set stateBag['Error'], but it was.") + } +} + +func DeleteTestStateBagStepGetRootPassword() multistep.StateBag { + stateBag := new(multistep.BasicStateBag) + + stateBag.Put("LoginKey", &LoginKey{"a", "b"}) + stateBag.Put("InstanceNo", "a") + + return stateBag +} diff --git a/builder/ncloud/step_stop_server_instance.go b/builder/ncloud/step_stop_server_instance.go new file mode 100644 index 000000000..1c9252ed2 --- /dev/null +++ b/builder/ncloud/step_stop_server_instance.go @@ -0,0 +1,64 @@ +package ncloud + +import ( + "fmt" + "log" + "time" + + ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" + "github.com/hashicorp/packer/packer" + "github.com/mitchellh/multistep" +) + +type StepStopServerInstance struct { + Conn *ncloud.Conn + StopServerInstance func(serverInstanceNo string) error + Say func(message string) + Error func(e error) +} + +func NewStepStopServerInstance(conn *ncloud.Conn, ui packer.Ui) *StepStopServerInstance { + var step = &StepStopServerInstance{ + Conn: conn, + Say: func(message string) { ui.Say(message) }, + Error: func(e error) { ui.Error(e.Error()) }, + } + + step.StopServerInstance = step.stopServerInstance + + return step +} + +func (s *StepStopServerInstance) stopServerInstance(serverInstanceNo string) error { + reqParams := new(ncloud.RequestStopServerInstances) + reqParams.ServerInstanceNoList = []string{serverInstanceNo} + + serverInstanceList, err := s.Conn.StopServerInstances(reqParams) + if err != nil { + return fmt.Errorf("error code: %d , error message: %s", serverInstanceList.ReturnCode, serverInstanceList.ReturnMessage) + } + + s.Say(fmt.Sprintf("Server Instance is stopping. Server InstanceNo is %s", serverInstanceList.ServerInstanceList[0].ServerInstanceNo)) + log.Println("Server Instance information : ", serverInstanceList.ServerInstanceList[0]) + + if err := waiterServerInstanceStatus(s.Conn, serverInstanceNo, "NSTOP", 5*time.Minute); err != nil { + return err + } + + s.Say(fmt.Sprintf("Server Instance stopped. Server InstanceNo is %s", serverInstanceList.ServerInstanceList[0].ServerInstanceNo)) + + return nil +} + +func (s *StepStopServerInstance) Run(state multistep.StateBag) multistep.StepAction { + s.Say("Stop Server Instance") + + var serverInstanceNo = state.Get("InstanceNo").(string) + + err := s.StopServerInstance(serverInstanceNo) + + return processStepResult(err, s.Error, state) +} + +func (*StepStopServerInstance) Cleanup(multistep.StateBag) { +} diff --git a/builder/ncloud/step_stop_server_instance_test.go b/builder/ncloud/step_stop_server_instance_test.go new file mode 100644 index 000000000..d90bc6953 --- /dev/null +++ b/builder/ncloud/step_stop_server_instance_test.go @@ -0,0 +1,55 @@ +package ncloud + +import ( + "fmt" + "testing" + + "github.com/mitchellh/multistep" +) + +func TestStepStopServerInstanceShouldFailIfOperationStopFails(t *testing.T) { + var testSubject = &StepStopServerInstance{ + StopServerInstance: func(serverInstanceNo string) error { return fmt.Errorf("!! Unit Test FAIL !!") }, + Say: func(message string) {}, + Error: func(e error) {}, + } + + stateBag := createTestStateBagStepStopServerInstance() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionHalt { + t.Fatalf("Expected the step to return 'ActionHalt', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == false { + t.Fatal("Expected the step to set stateBag['Error'], but it was not.") + } +} + +func TestStepStopServerInstanceShouldPassIfOperationStopPasses(t *testing.T) { + var testSubject = &StepStopServerInstance{ + StopServerInstance: func(serverInstanceNo string) error { return nil }, + Say: func(message string) {}, + Error: func(e error) {}, + } + + stateBag := createTestStateBagStepStopServerInstance() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionContinue { + t.Fatalf("Expected the step to return 'ActionContinue', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == true { + t.Fatalf("Expected the step to not set stateBag['Error'], but it was.") + } +} + +func createTestStateBagStepStopServerInstance() multistep.StateBag { + stateBag := new(multistep.BasicStateBag) + + stateBag.Put("InstanceNo", "a") + return stateBag +} diff --git a/builder/ncloud/step_terminate_server_instance.go b/builder/ncloud/step_terminate_server_instance.go new file mode 100644 index 000000000..5d60236f0 --- /dev/null +++ b/builder/ncloud/step_terminate_server_instance.go @@ -0,0 +1,81 @@ +package ncloud + +import ( + "errors" + "fmt" + "time" + + ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" + "github.com/hashicorp/packer/packer" + "github.com/mitchellh/multistep" +) + +type StepTerminateServerInstance struct { + Conn *ncloud.Conn + TerminateServerInstance func(serverInstanceNo string) error + Say func(message string) + Error func(e error) +} + +func NewStepTerminateServerInstance(conn *ncloud.Conn, ui packer.Ui) *StepTerminateServerInstance { + var step = &StepTerminateServerInstance{ + Conn: conn, + Say: func(message string) { ui.Say(message) }, + Error: func(e error) { ui.Error(e.Error()) }, + } + + step.TerminateServerInstance = step.terminateServerInstance + + return step +} + +func (s *StepTerminateServerInstance) terminateServerInstance(serverInstanceNo string) error { + reqParams := new(ncloud.RequestTerminateServerInstances) + reqParams.ServerInstanceNoList = []string{serverInstanceNo} + + serverInstanceList, err := s.Conn.TerminateServerInstances(reqParams) + if err != nil { + return fmt.Errorf("error code: %d , error message: %s", serverInstanceList.ReturnCode, serverInstanceList.ReturnMessage) + } + + c1 := make(chan error, 1) + + go func() { + reqParams := new(ncloud.RequestGetServerInstanceList) + reqParams.ServerInstanceNoList = []string{serverInstanceNo} + + for { + + serverInstanceList, err := s.Conn.GetServerInstanceList(reqParams) + if err != nil { + c1 <- fmt.Errorf("error code: %d , error message: %s", serverInstanceList.ReturnCode, serverInstanceList.ReturnMessage) + return + } else if serverInstanceList.TotalRows == 0 { + c1 <- nil + return + } + + time.Sleep(time.Second * 3) + } + }() + + select { + case res := <-c1: + return res + case <-time.After(time.Second * 60): + return errors.New("TIMEOUT : Can't terminate server instance") + } +} + +func (s *StepTerminateServerInstance) Run(state multistep.StateBag) multistep.StepAction { + s.Say("Terminate Server Instance") + + var serverInstanceNo = state.Get("InstanceNo").(string) + + err := s.TerminateServerInstance(serverInstanceNo) + + return processStepResult(err, s.Error, state) +} + +func (*StepTerminateServerInstance) Cleanup(multistep.StateBag) { +} diff --git a/builder/ncloud/step_terminate_server_instance_test.go b/builder/ncloud/step_terminate_server_instance_test.go new file mode 100644 index 000000000..b5967fc65 --- /dev/null +++ b/builder/ncloud/step_terminate_server_instance_test.go @@ -0,0 +1,54 @@ +package ncloud + +import ( + "fmt" + "github.com/mitchellh/multistep" + "testing" +) + +func TestStepTerminateServerInstanceShouldFailIfOperationTerminationFails(t *testing.T) { + var testSubject = &StepTerminateServerInstance{ + TerminateServerInstance: func(serverInstanceNo string) error { return fmt.Errorf("!! Unit Test FAIL !!") }, + Say: func(message string) {}, + Error: func(e error) {}, + } + + stateBag := createTestStateBagStepTerminateServerInstance() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionHalt { + t.Fatalf("Expected the step to return 'ActionHalt', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == false { + t.Fatal("Expected the step to set stateBag['Error'], but it was not.") + } +} + +func TestStepTerminateServerInstanceShouldPassIfOperationTerminationPasses(t *testing.T) { + var testSubject = &StepTerminateServerInstance{ + TerminateServerInstance: func(serverInstanceNo string) error { return nil }, + Say: func(message string) {}, + Error: func(e error) {}, + } + + stateBag := createTestStateBagStepTerminateServerInstance() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionContinue { + t.Fatalf("Expected the step to return 'ActionContinue', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == true { + t.Fatalf("Expected the step to not set stateBag['Error'], but it was.") + } +} + +func createTestStateBagStepTerminateServerInstance() multistep.StateBag { + stateBag := new(multistep.BasicStateBag) + + stateBag.Put("InstanceNo", "a") + return stateBag +} diff --git a/builder/ncloud/step_validate_template.go b/builder/ncloud/step_validate_template.go new file mode 100644 index 000000000..0007bfa40 --- /dev/null +++ b/builder/ncloud/step_validate_template.go @@ -0,0 +1,263 @@ +package ncloud + +import ( + "bytes" + "errors" + "fmt" + "strings" + + ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" + "github.com/hashicorp/packer/packer" + "github.com/mitchellh/multistep" + "github.com/olekukonko/tablewriter" +) + +//StepValidateTemplate : struct for Validation a tempalte +type StepValidateTemplate struct { + Conn *ncloud.Conn + Validate func() error + Say func(message string) + Error func(e error) + Config *Config + zoneNo string + regionNo string +} + +// NewStepValidateTemplate : funciton for Validation a tempalte +func NewStepValidateTemplate(conn *ncloud.Conn, ui packer.Ui, config *Config) *StepValidateTemplate { + var step = &StepValidateTemplate{ + Conn: conn, + Say: func(message string) { ui.Say(message) }, + Error: func(e error) { ui.Error(e.Error()) }, + Config: config, + } + + step.Validate = step.validateTemplate + + return step +} + +// getZoneNo : get zoneNo +func (s *StepValidateTemplate) getZoneNo() error { + if s.Config.Region == "" { + return nil + } + + regionList, err := s.Conn.GetRegionList() + if err != nil { + return fmt.Errorf("error code: %d , error message: %s", regionList.ReturnCode, regionList.ReturnMessage) + } + + var regionNo string + for _, region := range regionList.RegionList { + if strings.EqualFold(region.RegionName, s.Config.Region) { + regionNo = region.RegionNo + } + } + + if regionNo == "" { + return fmt.Errorf("region %s is invalid", s.Config.Region) + } + + s.regionNo = regionNo + + // Get ZoneNo + ZoneList, err := s.Conn.GetZoneList(regionNo) + if err != nil { + return fmt.Errorf("error code: %d , error message: %s", ZoneList.ReturnCode, ZoneList.ReturnMessage) + } + + if len(ZoneList.Zone) > 0 { + s.zoneNo = ZoneList.Zone[0].ZoneNo + } + + return nil +} + +func (s *StepValidateTemplate) validateMemberServerImage() error { + var serverImageName = s.Config.ServerImageName + + reqParams := new(ncloud.RequestServerImageList) + reqParams.RegionNo = s.regionNo + + memberServerImageList, err := s.Conn.GetMemberServerImageList(reqParams) + if err != nil { + return err + } + + var isExistMemberServerImageNo = false + for _, image := range memberServerImageList.MemberServerImageList { + // Check duplicate server_image_name + if image.MemberServerImageName == serverImageName { + return fmt.Errorf("server_image_name %s is exists", serverImageName) + } + + if image.MemberServerImageNo == s.Config.MemberServerImageNo { + isExistMemberServerImageNo = true + if s.Config.ServerProductCode == "" { + s.Config.ServerProductCode = image.OriginalServerProductCode + s.Say("server_product_code for member server image '" + image.OriginalServerProductCode + "' is configured automatically") + } + s.Config.ServerImageProductCode = image.OriginalServerImageProductCode + } + } + + if s.Config.MemberServerImageNo != "" && !isExistMemberServerImageNo { + return fmt.Errorf("member_server_image_no %s does not exist", s.Config.MemberServerImageNo) + } + + return nil +} + +func (s *StepValidateTemplate) validateServerImageProduct() error { + var serverImageProductCode = s.Config.ServerImageProductCode + if serverImageProductCode == "" { + return nil + } + + reqParams := new(ncloud.RequestGetServerImageProductList) + reqParams.RegionNo = s.regionNo + + serverImageProductList, err := s.Conn.GetServerImageProductList(reqParams) + if err != nil { + return err + } + + var isExistServerImage = false + var buf bytes.Buffer + var productName string + table := tablewriter.NewWriter(&buf) + table.SetHeader([]string{"Name", "Code"}) + + for _, product := range serverImageProductList.Product { + // Check exist server image product code + if product.ProductCode == serverImageProductCode { + isExistServerImage = true + productName = product.ProductName + break + } + + table.Append([]string{product.ProductName, product.ProductCode}) + } + + if !isExistServerImage { + reqParams.BlockStorageSize = 100 + + serverImageProductList, err := s.Conn.GetServerImageProductList(reqParams) + if err != nil { + return err + } + + for _, product := range serverImageProductList.Product { + // Check exist server image product code + if product.ProductCode == serverImageProductCode { + isExistServerImage = true + productName = product.ProductName + break + } + + table.Append([]string{product.ProductName, product.ProductCode}) + } + } + + if !isExistServerImage { + table.Render() + s.Say(buf.String()) + + return fmt.Errorf("server_image_product_code %s does not exist", serverImageProductCode) + } + + if strings.Contains(productName, "mssql") { + s.Config.FeeSystemTypeCode = "FXSUM" + } + + return nil +} + +func (s *StepValidateTemplate) validateServerProductCode() error { + var serverImageProductCode = s.Config.ServerImageProductCode + var productCode = s.Config.ServerProductCode + + reqParams := new(ncloud.RequestGetServerProductList) + reqParams.ServerImageProductCode = serverImageProductCode + reqParams.RegionNo = s.regionNo + + productList, err := s.Conn.GetServerProductList(reqParams) + if err != nil { + return err + } + + var isExistProductCode = false + for _, product := range productList.Product { + // Check exist server image product code + if product.ProductCode == productCode { + isExistProductCode = true + if strings.Contains(product.ProductName, "mssql") { + s.Config.FeeSystemTypeCode = "FXSUM" + } + + if product.ProductType.Code == "VDS" { + return errors.New("You cannot create my server image for VDS servers") + } + + break + } else if productCode == "" && product.ProductType.Code == "STAND" { + isExistProductCode = true + s.Config.ServerProductCode = product.ProductCode + s.Say("server_product_code '" + product.ProductCode + "' is configured automatically") + break + } + } + + if !isExistProductCode { + var buf bytes.Buffer + table := tablewriter.NewWriter(&buf) + table.SetHeader([]string{"Name", "Code"}) + for _, product := range productList.Product { + table.Append([]string{product.ProductName, product.ProductCode}) + } + table.Render() + + s.Say(buf.String()) + + return fmt.Errorf("server_product_code %s does not exist", productCode) + } + + return nil +} + +// Check ImageName / Product Code / Server Image Product Code / Server Product Code... +func (s *StepValidateTemplate) validateTemplate() error { + // Get RegionNo, ZoneNo + if err := s.getZoneNo(); err != nil { + return err + } + + // Validate member_server_image_no and member_server_image_no + if err := s.validateMemberServerImage(); err != nil { + return err + } + + // Validate server_image_product_code + if err := s.validateServerImageProduct(); err != nil { + return err + } + + // Validate server_product_code + return s.validateServerProductCode() +} + +// Run : main funciton for validation a template +func (s *StepValidateTemplate) Run(state multistep.StateBag) multistep.StepAction { + s.Say("Validating deployment template ...") + + err := s.Validate() + + state.Put("ZoneNo", s.zoneNo) + + return processStepResult(err, s.Error, state) +} + +// Cleanup : cleanup on error +func (s *StepValidateTemplate) Cleanup(multistep.StateBag) { +} diff --git a/builder/ncloud/step_validate_template_test.go b/builder/ncloud/step_validate_template_test.go new file mode 100644 index 000000000..98f45b4a0 --- /dev/null +++ b/builder/ncloud/step_validate_template_test.go @@ -0,0 +1,54 @@ +package ncloud + +import ( + "fmt" + "testing" + + "github.com/mitchellh/multistep" +) + +func TestStepValidateTemplateShouldFailIfValidateFails(t *testing.T) { + var testSubject = &StepValidateTemplate{ + Validate: func() error { return fmt.Errorf("!! Unit Test FAIL !!") }, + Say: func(message string) {}, + Error: func(e error) {}, + } + + stateBag := createTestStateBagStepValidateTemplate() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionHalt { + t.Fatalf("Expected the step to return 'ActionHalt', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == false { + t.Fatal("Expected the step to set stateBag['Error'], but it was not.") + } +} + +func TestStepValidateTemplateShouldPassIfValidatePasses(t *testing.T) { + var testSubject = &StepValidateTemplate{ + Validate: func() error { return nil }, + Say: func(message string) {}, + Error: func(e error) {}, + } + + stateBag := createTestStateBagStepValidateTemplate() + + var result = testSubject.Run(stateBag) + + if result != multistep.ActionContinue { + t.Fatalf("Expected the step to return 'ActionContinue', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk("Error"); ok == true { + t.Fatalf("Expected the step to not set stateBag['Error'], but it was.") + } +} + +func createTestStateBagStepValidateTemplate() multistep.StateBag { + stateBag := new(multistep.BasicStateBag) + + return stateBag +} diff --git a/builder/ncloud/waiter_block_storage_instance.go b/builder/ncloud/waiter_block_storage_instance.go new file mode 100644 index 000000000..9cfa5562a --- /dev/null +++ b/builder/ncloud/waiter_block_storage_instance.go @@ -0,0 +1,80 @@ +package ncloud + +import ( + "fmt" + "log" + "time" + + ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" +) + +func waiterBlockStorageInstanceStatus(conn *ncloud.Conn, blockStorageInstanceNo string, status string, timeout time.Duration) error { + reqParams := new(ncloud.RequestBlockStorageInstanceList) + reqParams.BlockStorageInstanceNoList = []string{blockStorageInstanceNo} + + c1 := make(chan error, 1) + + go func() { + for { + blockStorageInstanceList, err := conn.GetBlockStorageInstance(reqParams) + if err != nil { + c1 <- err + return + } + + if status == "DETAC" && len(blockStorageInstanceList.BlockStorageInstance) == 0 { + c1 <- nil + return + } + + code := blockStorageInstanceList.BlockStorageInstance[0].BlockStorageInstanceStatus.Code + operationCode := blockStorageInstanceList.BlockStorageInstance[0].BlockStorageInstanceOperation.Code + + if code == status && operationCode == "NULL" { + c1 <- nil + return + } + + log.Println(blockStorageInstanceList.BlockStorageInstance[0]) + time.Sleep(time.Second * 5) + } + }() + + select { + case res := <-c1: + return res + case <-time.After(timeout): + return fmt.Errorf("TIMEOUT : block storage instance status is not changed into status %s", status) + } +} + +func waiterDetachedBlockStorageInstance(conn *ncloud.Conn, serverInstanceNo string, timeout time.Duration) error { + reqParams := new(ncloud.RequestBlockStorageInstanceList) + reqParams.ServerInstanceNo = serverInstanceNo + + c1 := make(chan error, 1) + + go func() { + for { + blockStorageInstanceList, err := conn.GetBlockStorageInstance(reqParams) + if err != nil { + c1 <- err + return + } + + if blockStorageInstanceList.TotalRows == 1 { + c1 <- nil + return + } + + time.Sleep(time.Second * 5) + } + }() + + select { + case res := <-c1: + return res + case <-time.After(timeout): + return fmt.Errorf("TIMEOUT : attached block storage instance is not detached") + } +} diff --git a/builder/ncloud/waiter_server_image_status.go b/builder/ncloud/waiter_server_image_status.go new file mode 100644 index 000000000..5ba640874 --- /dev/null +++ b/builder/ncloud/waiter_server_image_status.go @@ -0,0 +1,43 @@ +package ncloud + +import ( + "fmt" + "log" + "time" + + ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" +) + +func waiterMemberServerImageStatus(conn *ncloud.Conn, memberServerImageNo string, status string, timeout time.Duration) error { + reqParams := new(ncloud.RequestServerImageList) + reqParams.MemberServerImageNoList = []string{memberServerImageNo} + + c1 := make(chan error, 1) + + go func() { + for { + memberServerImageList, err := conn.GetMemberServerImageList(reqParams) + if err != nil { + c1 <- err + return + } + + code := memberServerImageList.MemberServerImageList[0].MemberServerImageStatus.Code + if code == status { + c1 <- nil + return + } + + log.Printf("Status of member server image [%s] is %s\n", memberServerImageNo, code) + log.Println(memberServerImageList.MemberServerImageList[0]) + time.Sleep(time.Second * 5) + } + }() + + select { + case res := <-c1: + return res + case <-time.After(timeout): + return fmt.Errorf("TIMEOUT : member server image status is not changed into status %s", status) + } +} diff --git a/builder/ncloud/waiter_server_instance_status.go b/builder/ncloud/waiter_server_instance_status.go new file mode 100644 index 000000000..176cde701 --- /dev/null +++ b/builder/ncloud/waiter_server_instance_status.go @@ -0,0 +1,43 @@ +package ncloud + +import ( + "fmt" + "log" + "time" + + ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" +) + +func waiterServerInstanceStatus(conn *ncloud.Conn, serverInstanceNo string, status string, timeout time.Duration) error { + reqParams := new(ncloud.RequestGetServerInstanceList) + reqParams.ServerInstanceNoList = []string{serverInstanceNo} + + c1 := make(chan error, 1) + + go func() { + for { + serverInstanceList, err := conn.GetServerInstanceList(reqParams) + if err != nil { + c1 <- err + return + } + + code := serverInstanceList.ServerInstanceList[0].ServerInstanceStatus.Code + if code == status { + c1 <- nil + return + } + + log.Printf("Status of serverInstanceNo [%s] is %s\n", serverInstanceNo, code) + log.Println(serverInstanceList.ServerInstanceList[0]) + time.Sleep(time.Second * 5) + } + }() + + select { + case res := <-c1: + return res + case <-time.After(timeout): + return fmt.Errorf("TIMEOUT : server instance status is not changed into status %s", status) + } +} diff --git a/command/plugin.go b/command/plugin.go index d9e7ea577..73a04a035 100644 --- a/command/plugin.go +++ b/command/plugin.go @@ -29,6 +29,7 @@ import ( hypervvmcxbuilder "github.com/hashicorp/packer/builder/hyperv/vmcx" lxcbuilder "github.com/hashicorp/packer/builder/lxc" lxdbuilder "github.com/hashicorp/packer/builder/lxd" + ncloudbuilder "github.com/hashicorp/packer/builder/ncloud" nullbuilder "github.com/hashicorp/packer/builder/null" oneandonebuilder "github.com/hashicorp/packer/builder/oneandone" openstackbuilder "github.com/hashicorp/packer/builder/openstack" @@ -96,6 +97,7 @@ var Builders = map[string]packer.Builder{ "hyperv-vmcx": new(hypervvmcxbuilder.Builder), "lxc": new(lxcbuilder.Builder), "lxd": new(lxdbuilder.Builder), + "ncloud": new(ncloudbuilder.Builder), "null": new(nullbuilder.Builder), "oneandone": new(oneandonebuilder.Builder), "openstack": new(openstackbuilder.Builder), From 4f9754a75c79b70bf795a2286766571440bfb1f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=8B=E1=85=B2=E1=84=89=E1=85=A5=E1=86=BC=E1=84=83?= =?UTF-8?q?=E1=85=A5=E1=86=A8?= Date: Thu, 11 Jan 2018 19:41:47 +0900 Subject: [PATCH 5/7] add ncloud-sdk-go dependency to vendor --- .../NaverCloudPlatform/ncloud-sdk-go/LICENSE | 7 + .../NaverCloudPlatform/ncloud-sdk-go/NOTICE | 26 ++ .../ncloud-sdk-go/common/commonResponse.go | 14 + .../ncloud-sdk-go/common/commoncode.go | 10 + .../common/parseErrorResponse.go | 20 + .../ncloud-sdk-go/common/region.go | 7 + .../ncloud-sdk-go/common/zone.go | 7 + .../ncloud-sdk-go/oauth/oauth.go | 370 ++++++++++++++++++ .../ncloud-sdk-go/request/request.go | 38 ++ .../ncloud-sdk-go/sdk/connection.go | 21 + .../sdk/createBlockStorageInstance.go | 87 ++++ .../ncloud-sdk-go/sdk/createLoginKey.go | 64 +++ .../sdk/createPublicIpInstance.go | 74 ++++ .../ncloud-sdk-go/sdk/createServerImage.go | 71 ++++ .../sdk/createServerInstances.go | 148 +++++++ .../sdk/deleteBlockStorageInstances.go | 60 +++ .../ncloud-sdk-go/sdk/deleteLoginKey.go | 59 +++ .../sdk/deletePublicIpInstances.go | 62 +++ .../disassociatePublicIpFromServerInstance.go | 54 +++ .../sdk/getAccessControlGroupList.go | 89 +++++ .../sdk/getAccessControlRuleList.go | 61 +++ .../sdk/getBlockStorageInstanceList.go | 144 +++++++ .../ncloud-sdk-go/sdk/getLoginKeyList.go | 77 ++++ .../sdk/getMemberServerImagesList.go | 87 ++++ .../sdk/getPublicIpInstanceList.go | 130 ++++++ .../ncloud-sdk-go/sdk/getRegionList.go | 40 ++ .../ncloud-sdk-go/sdk/getRootPassword.go | 67 ++++ .../sdk/getServerImageProductList.go | 88 +++++ .../sdk/getServerInstanceList.go | 133 +++++++ .../ncloud-sdk-go/sdk/getServerProductList.go | 79 ++++ .../ncloud-sdk-go/sdk/getZoneList.go | 44 +++ .../ncloud-sdk-go/sdk/model.go | 359 +++++++++++++++++ .../ncloud-sdk-go/sdk/stopServerInstances.go | 62 +++ .../sdk/terminateServerInstances.go | 62 +++ vendor/vendor.json | 24 ++ 35 files changed, 2745 insertions(+) create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/LICENSE create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/NOTICE create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/common/commonResponse.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/common/commoncode.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/common/parseErrorResponse.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/common/region.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/common/zone.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/oauth/oauth.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/request/request.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/connection.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/createBlockStorageInstance.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/createLoginKey.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/createPublicIpInstance.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/createServerImage.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/createServerInstances.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/deleteBlockStorageInstances.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/deleteLoginKey.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/deletePublicIpInstances.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/disassociatePublicIpFromServerInstance.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getAccessControlGroupList.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getAccessControlRuleList.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getBlockStorageInstanceList.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getLoginKeyList.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getMemberServerImagesList.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getPublicIpInstanceList.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getRegionList.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getRootPassword.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getServerImageProductList.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getServerInstanceList.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getServerProductList.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getZoneList.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/model.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/stopServerInstances.go create mode 100644 vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/terminateServerInstances.go diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/LICENSE b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/LICENSE new file mode 100644 index 000000000..4ae922683 --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/LICENSE @@ -0,0 +1,7 @@ +Copyright 2017 NAVER BUSINESS PLATFORM Corp. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/NOTICE b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/NOTICE new file mode 100644 index 000000000..f495434a4 --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/NOTICE @@ -0,0 +1,26 @@ +ncp-sdk-go + +This project contains subcomponents with separate copyright notices and license terms. +Your use of the source code for these subcomponents is subject to the terms and conditions of the following licenses. + +======================================================================= +OAuth 1.0 Library for Go (https://github.com/mrjones/oauth/) +======================================================================= + +Copyright (C) 2013 Matthew R. Jones + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/common/commonResponse.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/common/commonResponse.go new file mode 100644 index 000000000..33f12f983 --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/common/commonResponse.go @@ -0,0 +1,14 @@ +package common + +import "encoding/xml" + +type CommonResponse struct { + RequestID string `xml:"requestId"` + ReturnCode int `xml:"returnCode"` + ReturnMessage string `xml:"returnMessage"` +} + +type ResponseError struct { + ResponseError xml.Name `xml:"responseError"` + CommonResponse +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/common/commoncode.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/common/commoncode.go new file mode 100644 index 000000000..aff8bcf98 --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/common/commoncode.go @@ -0,0 +1,10 @@ +package common + +type CommonCode struct { + CodeKind string `xml:"codeKind"` + DetailCategorizeCode string `xml:"detailCategorizeCode"` + Code string `xml:"code"` + CodeName string `xml:"codeName"` + CodeOrder int `xml:"codeOrder"` + JavaConstantCode string `xml:"javaConstantCode"` +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/common/parseErrorResponse.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/common/parseErrorResponse.go new file mode 100644 index 000000000..10c76f58c --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/common/parseErrorResponse.go @@ -0,0 +1,20 @@ +package common + +import ( + "encoding/xml" + "strings" +) + +func ParseErrorResponse(bytes []byte) (*ResponseError, error) { + responseError := ResponseError{} + + if err := xml.Unmarshal([]byte(bytes), &responseError); err != nil { + return nil, err + } + + if responseError.ReturnMessage != "" { + responseError.ReturnMessage = strings.TrimSpace(responseError.ReturnMessage) + } + + return &responseError, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/common/region.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/common/region.go new file mode 100644 index 000000000..eaa055f6e --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/common/region.go @@ -0,0 +1,7 @@ +package common + +type Region struct { + RegionNo string `xml:"regionNo"` + RegionCode string `xml:"regionCode"` + RegionName string `xml:"regionName"` +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/common/zone.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/common/zone.go new file mode 100644 index 000000000..f2ec78381 --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/common/zone.go @@ -0,0 +1,7 @@ +package common + +type Zone struct { + ZoneNo string `xml:"zoneNo"` + ZoneName string `xml:"zoneName"` + ZoneDescription string `xml:"zoneDescription"` +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/oauth/oauth.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/oauth/oauth.go new file mode 100644 index 000000000..c6b917b4c --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/oauth/oauth.go @@ -0,0 +1,370 @@ +package oauth + +import ( + "crypto" + "crypto/hmac" + _ "crypto/sha1" + "encoding/base64" + "fmt" + "math/rand" + "net/url" + "os" + "sort" + "strconv" + "sync" + "time" +) + +const ( + OAUTH_VERSION = "1.0" + SIGNATURE_METHOD_HMAC = "HMAC-" + + HTTP_AUTH_HEADER = "Authorization" + OAUTH_HEADER = "OAuth " + CONSUMER_KEY_PARAM = "oauth_consumer_key" + NONCE_PARAM = "oauth_nonce" + SIGNATURE_METHOD_PARAM = "oauth_signature_method" + SIGNATURE_PARAM = "oauth_signature" + TIMESTAMP_PARAM = "oauth_timestamp" + TOKEN_PARAM = "oauth_token" + TOKEN_SECRET_PARAM = "oauth_token_secret" + VERSION_PARAM = "oauth_version" +) + +var HASH_METHOD_MAP = map[crypto.Hash]string{ + crypto.SHA1: "SHA1", + crypto.SHA256: "SHA256", +} + +// Creates a new Consumer instance, with a HMAC-SHA1 signer +func NewConsumer(consumerKey string, consumerSecret string, requestMethod string, requestURL string) *Consumer { + clock := &defaultClock{} + consumer := &Consumer{ + consumerKey: consumerKey, + consumerSecret: consumerSecret, + requestMethod: requestMethod, + requestURL: requestURL, + clock: clock, + nonceGenerator: newLockedNonceGenerator(clock), + + AdditionalParams: make(map[string]string), + } + + consumer.signer = &HMACSigner{ + consumerSecret: consumerSecret, + hashFunc: crypto.SHA1, + } + + return consumer +} + +// lockedNonceGenerator wraps a non-reentrant random number generator with alock +type lockedNonceGenerator struct { + nonceGenerator nonceGenerator + lock sync.Mutex +} + +func newLockedNonceGenerator(c clock) *lockedNonceGenerator { + return &lockedNonceGenerator{ + nonceGenerator: rand.New(rand.NewSource(c.Nanos())), + } +} + +func (n *lockedNonceGenerator) Int63() int64 { + n.lock.Lock() + r := n.nonceGenerator.Int63() + n.lock.Unlock() + return r +} + +type clock interface { + Seconds() int64 + Nanos() int64 +} + +type nonceGenerator interface { + Int63() int64 +} + +type signer interface { + Sign(message string) (string, error) + Verify(message string, signature string) error + SignatureMethod() string + HashFunc() crypto.Hash + Debug(enabled bool) +} + +type defaultClock struct{} + +func (*defaultClock) Seconds() int64 { + return time.Now().Unix() +} + +func (*defaultClock) Nanos() int64 { + return time.Now().UnixNano() +} + +type Consumer struct { + AdditionalParams map[string]string + + // The rest of this class is configured via the NewConsumer function. + consumerKey string + + consumerSecret string + + requestMethod string + + requestURL string + + debug bool + + // Private seams for mocking dependencies when testing + clock clock + // Seeded generators are not reentrant + nonceGenerator nonceGenerator + signer signer +} + +type HMACSigner struct { + consumerSecret string + hashFunc crypto.Hash + debug bool +} + +func (s *HMACSigner) Debug(enabled bool) { + s.debug = enabled +} + +func (s *HMACSigner) Sign(message string) (string, error) { + key := escape(s.consumerSecret) + if s.debug { + fmt.Println("Signing:", message) + fmt.Println("Key:", key) + } + + h := hmac.New(s.HashFunc().New, []byte(key+"&")) + h.Write([]byte(message)) + rawSignature := h.Sum(nil) + + base64signature := base64.StdEncoding.EncodeToString(rawSignature) + if s.debug { + fmt.Println("Base64 signature:", base64signature) + } + return base64signature, nil +} + +func (s *HMACSigner) Verify(message string, signature string) error { + if s.debug { + fmt.Println("Verifying Base64 signature:", signature) + } + validSignature, err := s.Sign(message) + if err != nil { + return err + } + + if validSignature != signature { + decodedSigniture, _ := url.QueryUnescape(signature) + if validSignature != decodedSigniture { + return fmt.Errorf("signature did not match") + } + } + + return nil +} + +func (s *HMACSigner) SignatureMethod() string { + return SIGNATURE_METHOD_HMAC + HASH_METHOD_MAP[s.HashFunc()] +} + +func (s *HMACSigner) HashFunc() crypto.Hash { + return s.hashFunc +} + +func escape(s string) string { + t := make([]byte, 0, 3*len(s)) + for i := 0; i < len(s); i++ { + c := s[i] + if isEscapable(c) { + t = append(t, '%') + t = append(t, "0123456789ABCDEF"[c>>4]) + t = append(t, "0123456789ABCDEF"[c&15]) + } else { + t = append(t, s[i]) + } + } + return string(t) +} + +func isEscapable(b byte) bool { + return !('A' <= b && b <= 'Z' || 'a' <= b && b <= 'z' || '0' <= b && b <= '9' || b == '-' || b == '.' || b == '_' || b == '~') +} + +func (c *Consumer) Debug(enabled bool) { + c.debug = enabled + c.signer.Debug(enabled) +} + +func (c *Consumer) GetRequestUrl() (loginUrl string, err error) { + if os.Getenv("GO_ENV") == "development" { + c.AdditionalParams["approachKey"] = c.consumerKey + c.AdditionalParams["secretKey"] = c.consumerSecret + } + c.AdditionalParams["responseFormatType"] = "xml" + + params := c.baseParams(c.consumerKey, c.AdditionalParams) + + if c.debug { + fmt.Println("params:", params) + } + + req := &request{ + method: c.requestMethod, + url: c.requestURL, + oauthParams: params, + } + + signature, err := c.signRequest(req) + if err != nil { + return "", err + } + + result := req.url + "?" + for pos, key := range req.oauthParams.Keys() { + for innerPos, value := range req.oauthParams.Get(key) { + if pos+innerPos != 0 { + result += "&" + } + result += fmt.Sprintf("%s=%s", key, value) + } + } + + result += fmt.Sprintf("&%s=%s", SIGNATURE_PARAM, escape(signature)) + + if c.debug { + fmt.Println("req: ", result) + } + + return result, nil +} + +func (c *Consumer) baseParams(consumerKey string, additionalParams map[string]string) *OrderedParams { + params := NewOrderedParams() + params.Add(VERSION_PARAM, OAUTH_VERSION) + params.Add(SIGNATURE_METHOD_PARAM, c.signer.SignatureMethod()) + params.Add(TIMESTAMP_PARAM, strconv.FormatInt(c.clock.Seconds(), 10)) + params.Add(NONCE_PARAM, strconv.FormatInt(c.nonceGenerator.Int63(), 10)) + params.Add(CONSUMER_KEY_PARAM, consumerKey) + + for key, value := range additionalParams { + params.Add(key, value) + } + + return params +} + +func (c *Consumer) signRequest(req *request) (string, error) { + baseString := c.requestString(req.method, req.url, req.oauthParams) + + if c.debug { + fmt.Println("baseString: ", baseString) + } + + signature, err := c.signer.Sign(baseString) + if err != nil { + return "", err + } + + return signature, nil +} + +func (c *Consumer) requestString(method string, url string, params *OrderedParams) string { + result := method + "&" + escape(url) + for pos, key := range params.Keys() { + for innerPos, value := range params.Get(key) { + if pos+innerPos == 0 { + result += "&" + } else { + result += escape("&") + } + result += escape(fmt.Sprintf("%s=%s", key, value)) + } + } + return result +} + +type request struct { + method string + url string + oauthParams *OrderedParams + userParams map[string]string +} + +// +// String Sorting helpers +// + +type ByValue []string + +func (a ByValue) Len() int { + return len(a) +} + +func (a ByValue) Swap(i, j int) { + a[i], a[j] = a[j], a[i] +} + +func (a ByValue) Less(i, j int) bool { + return a[i] < a[j] +} + +// +// ORDERED PARAMS +// + +type OrderedParams struct { + allParams map[string][]string + keyOrdering []string +} + +func NewOrderedParams() *OrderedParams { + return &OrderedParams{ + allParams: make(map[string][]string), + keyOrdering: make([]string, 0), + } +} + +func (o *OrderedParams) Get(key string) []string { + sort.Sort(ByValue(o.allParams[key])) + return o.allParams[key] +} + +func (o *OrderedParams) Keys() []string { + sort.Sort(o) + return o.keyOrdering +} + +func (o *OrderedParams) Add(key, value string) { + o.AddUnescaped(key, escape(value)) +} + +func (o *OrderedParams) AddUnescaped(key, value string) { + if _, exists := o.allParams[key]; !exists { + o.keyOrdering = append(o.keyOrdering, key) + o.allParams[key] = make([]string, 1) + o.allParams[key][0] = value + } else { + o.allParams[key] = append(o.allParams[key], value) + } +} + +func (o *OrderedParams) Len() int { + return len(o.keyOrdering) +} + +func (o *OrderedParams) Less(i int, j int) bool { + return o.keyOrdering[i] < o.keyOrdering[j] +} + +func (o *OrderedParams) Swap(i int, j int) { + o.keyOrdering[i], o.keyOrdering[j] = o.keyOrdering[j], o.keyOrdering[i] +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/request/request.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/request/request.go new file mode 100644 index 000000000..2f0d77d14 --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/request/request.go @@ -0,0 +1,38 @@ +package request + +import ( + "io/ioutil" + "net/http" + + "github.com/NaverCloudPlatform/ncloud-sdk-go/oauth" +) + +// NewRequest is http request with oauth +func NewRequest(accessKey string, secretKey string, method string, url string, params map[string]string) ([]byte, *http.Response, error) { + c := oauth.NewConsumer(accessKey, secretKey, method, url) + + for k, v := range params { + c.AdditionalParams[k] = v + } + + reqURL, err := c.GetRequestUrl() + if err != nil { + return nil, nil, err + } + + req, err := http.NewRequest(method, reqURL, nil) + if err != nil { + return nil, nil, err + } + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + return nil, nil, err + } + defer resp.Body.Close() + + bytes, _ := ioutil.ReadAll(resp.Body) + + return bytes, resp, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/connection.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/connection.go new file mode 100644 index 000000000..27f8a6197 --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/connection.go @@ -0,0 +1,21 @@ +package sdk + +import ( + "os" +) + +// NewConnection create connection for server api +func NewConnection(accessKey string, secretKey string) *Conn { + conn := &Conn{ + accessKey: accessKey, + secretKey: secretKey, + apiURL: "https://api.ncloud.com/", + } + + // for other phase(dev, test, beta ...) test + if os.Getenv("NCLOUD_API_GW") != "" { + conn.apiURL = os.Getenv("NCLOUD_API_GW") + } + + return conn +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/createBlockStorageInstance.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/createBlockStorageInstance.go new file mode 100644 index 000000000..3fd8e61b7 --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/createBlockStorageInstance.go @@ -0,0 +1,87 @@ +package sdk + +import ( + "encoding/xml" + "errors" + "fmt" + "strconv" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +func processCreateBlockStorageInstanceParams(reqParams *RequestBlockStorageInstance) (map[string]string, error) { + params := make(map[string]string) + + if reqParams.BlockStorageName != "" { + if len := len(reqParams.BlockStorageName); len < 3 || len > 30 { + return nil, errors.New("Length of BlockStorageName should be min 3 or max 30") + } + params["blockStorageName"] = reqParams.BlockStorageName + } + + if reqParams.BlockStorageSize < 10 || reqParams.BlockStorageSize > 2000 { + return nil, errors.New("BlockStorageSize should be min 10 or max 2000") + } + + if reqParams.BlockStorageDescription != "" { + if len := len(reqParams.BlockStorageDescription); len > 1000 { + return nil, errors.New("Length of BlockStorageDescription should be max 1000") + } + params["blockStorageDescription"] = reqParams.BlockStorageDescription + } + + if int(reqParams.BlockStorageSize/10)*10 != reqParams.BlockStorageSize { + return nil, errors.New("BlockStorageSize must be a multiple of 10 GB") + } + + if reqParams.BlockStorageSize == 0 { + return nil, errors.New("BlockStorageSize field is required") + } + + params["blockStorageSize"] = strconv.Itoa(reqParams.BlockStorageSize) + + if reqParams.ServerInstanceNo == "" { + return nil, errors.New("ServerInstanceNo field is required") + } + + params["serverInstanceNo"] = reqParams.ServerInstanceNo + + return params, nil +} + +// CreateBlockStorageInstance create block storage instance +func (s *Conn) CreateBlockStorageInstance(reqParams *RequestBlockStorageInstance) (*BlockStorageInstanceList, error) { + + params, err := processCreateBlockStorageInstanceParams(reqParams) + if err != nil { + return nil, err + } + + params["action"] = "createBlockStorageInstance" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := BlockStorageInstanceList{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + var blockStorageInstanceList = BlockStorageInstanceList{} + if err := xml.Unmarshal([]byte(bytes), &blockStorageInstanceList); err != nil { + return nil, err + } + + return &blockStorageInstanceList, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/createLoginKey.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/createLoginKey.go new file mode 100644 index 000000000..b2cd490dc --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/createLoginKey.go @@ -0,0 +1,64 @@ +package sdk + +import ( + "encoding/xml" + "errors" + "fmt" + "strings" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +func processCreateLoginKeyParams(keyName string) error { + if keyName == "" { + return errors.New("KeyName is required field") + } + + if len := len(keyName); len < 3 || len > 30 { + return errors.New("Length of KeyName should be min 3 or max 30") + } + + return nil +} + +// CreateLoginKey create loginkey with keyName +func (s *Conn) CreateLoginKey(keyName string) (*PrivateKey, error) { + if err := processCreateLoginKeyParams(keyName); err != nil { + return nil, err + } + + params := make(map[string]string) + + params["keyName"] = keyName + params["action"] = "createLoginKey" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := PrivateKey{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + privateKey := PrivateKey{} + if err := xml.Unmarshal([]byte(bytes), &privateKey); err != nil { + return nil, err + } + + if privateKey.PrivateKey != "" { + privateKey.PrivateKey = strings.TrimSpace(privateKey.PrivateKey) + } + + return &privateKey, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/createPublicIpInstance.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/createPublicIpInstance.go new file mode 100644 index 000000000..6dc5aa0fe --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/createPublicIpInstance.go @@ -0,0 +1,74 @@ +package sdk + +import ( + "encoding/xml" + "errors" + "fmt" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +func processCreatePublicIPInstanceParams(reqParams *RequestCreatePublicIPInstance) (map[string]string, error) { + params := make(map[string]string) + + if reqParams.ServerInstanceNo != "" { + params["serverInstanceNo"] = reqParams.ServerInstanceNo + } + + if reqParams.PublicIPDescription != "" { + if len := len(reqParams.PublicIPDescription); len > 1000 { + return params, errors.New("Length of publicIpDescription should be max 1000") + } + params["publicIpDescription"] = reqParams.PublicIPDescription + } + + if reqParams.InternetLineTypeCode != "" { + if reqParams.InternetLineTypeCode != "PUBLC" && reqParams.InternetLineTypeCode != "GLBL" { + return params, errors.New("InternetLineTypeCode should be PUBLC or GLBL") + } + params["internetLineTypeCode"] = reqParams.InternetLineTypeCode + } + + if reqParams.RegionNo != "" { + params["regionNo"] = reqParams.RegionNo + } + + return params, nil +} + +// CreatePublicIPInstance create public ip instance and allocate it to server instance +func (s *Conn) CreatePublicIPInstance(reqParams *RequestCreatePublicIPInstance) (*PublicIPInstanceList, error) { + params, err := processCreatePublicIPInstanceParams(reqParams) + if err != nil { + return nil, err + } + + params["action"] = "createPublicIpInstance" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := PublicIPInstanceList{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + var responseCreatePublicIPInstances = PublicIPInstanceList{} + if err := xml.Unmarshal([]byte(bytes), &responseCreatePublicIPInstances); err != nil { + fmt.Println(err) + return nil, err + } + + return &responseCreatePublicIPInstances, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/createServerImage.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/createServerImage.go new file mode 100644 index 000000000..11fb9b308 --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/createServerImage.go @@ -0,0 +1,71 @@ +package sdk + +import ( + "encoding/xml" + "errors" + "fmt" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +func processCreateMemberServerImageParams(reqParams *RequestCreateServerImage) (map[string]string, error) { + params := make(map[string]string) + + if reqParams == nil || reqParams.ServerInstanceNo == "" { + return params, errors.New("ServerInstanceNo is required field") + } + + if reqParams.MemberServerImageName != "" { + if len := len(reqParams.MemberServerImageName); len < 3 || len > 30 { + return nil, errors.New("Length of MemberServerImageName should be min 3 or max 30") + } + params["memberServerImageName"] = reqParams.MemberServerImageName + } + + if reqParams.MemberServerImageDescription != "" { + if len := len(reqParams.MemberServerImageDescription); len > 1000 { + return nil, errors.New("Length of MemberServerImageDescription should be smaller than 1000") + } + params["memberServerImageDescription"] = reqParams.MemberServerImageDescription + } + + params["serverInstanceNo"] = reqParams.ServerInstanceNo + + return params, nil +} + +// CreateMemberServerImage create member server image and retrun member server image list +func (s *Conn) CreateMemberServerImage(reqParams *RequestCreateServerImage) (*MemberServerImageList, error) { + params, err := processCreateMemberServerImageParams(reqParams) + if err != nil { + return nil, err + } + + params["action"] = "createMemberServerImage" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := MemberServerImageList{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + var serverImageListsResp = MemberServerImageList{} + if err := xml.Unmarshal([]byte(bytes), &serverImageListsResp); err != nil { + return nil, err + } + + return &serverImageListsResp, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/createServerInstances.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/createServerInstances.go new file mode 100644 index 000000000..a00da9145 --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/createServerInstances.go @@ -0,0 +1,148 @@ +package sdk + +import ( + "encoding/base64" + "encoding/xml" + "errors" + "fmt" + "strconv" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +func processCreateServerInstancesParams(reqParams *RequestCreateServerInstance) (map[string]string, error) { + params := make(map[string]string) + + if reqParams == nil { + return params, nil + } + + if reqParams.ServerImageProductCode != "" { + if len := len(reqParams.ServerImageProductCode); len > 20 { + return nil, errors.New("Length of ServerImageProductCode should be min 1 or max 20") + } + params["serverImageProductCode"] = reqParams.ServerImageProductCode + } + + if reqParams.ServerProductCode != "" { + if len := len(reqParams.ServerProductCode); len > 20 { + return nil, errors.New("Length of ServerProductCode should be min 1 or max 20") + } + params["serverProductCode"] = reqParams.ServerProductCode + } + + if reqParams.MemberServerImageNo != "" { + params["memberServerImageNo"] = reqParams.MemberServerImageNo + } + + if reqParams.ServerName != "" { + if len := len(reqParams.ServerName); len < 3 || len > 30 { + return nil, errors.New("Length of ServerName should be min 3 or max 30") + } + params["serverName"] = reqParams.ServerName + } + + if reqParams.ServerDescription != "" { + if len := len(reqParams.ServerDescription); len > 1000 { + return nil, errors.New("Length of ServerDescription should be min 1 or max 1000") + } + params["serverDescription"] = reqParams.ServerDescription + } + + if reqParams.LoginKeyName != "" { + if len := len(reqParams.LoginKeyName); len < 3 || len > 30 { + return nil, errors.New("Length of LoginKeyName should be min 3 or max 30") + } + params["loginKeyName"] = reqParams.LoginKeyName + } + + if reqParams.IsProtectServerTermination == true { + params["isProtectServerTermination"] = "true" + } + + if reqParams.ServerCreateCount > 0 { + if reqParams.ServerCreateCount > 20 { + return nil, errors.New("ServerCreateCount should be min 1 or max 20") + + } + params["serverCreateCount"] = strconv.Itoa(reqParams.ServerCreateCount) + } + + if reqParams.ServerCreateStartNo > 0 { + if reqParams.ServerCreateCount+reqParams.ServerCreateStartNo > 1000 { + return nil, errors.New("Sum of ServerCreateCount and ServerCreateStartNo should be less than 1000") + + } + params["serverCreateStartNo"] = strconv.Itoa(reqParams.ServerCreateStartNo) + } + + if reqParams.InternetLineTypeCode != "" { + if reqParams.InternetLineTypeCode != "PUBLC" && reqParams.InternetLineTypeCode != "GLBL" { + return nil, errors.New("InternetLineTypeCode should be PUBLC or GLBL") + } + params["internetLineTypeCode"] = reqParams.InternetLineTypeCode + } + + if reqParams.FeeSystemTypeCode != "" { + if reqParams.FeeSystemTypeCode != "FXSUM" && reqParams.FeeSystemTypeCode != "MTRAT" { + return nil, errors.New("FeeSystemTypeCode should be FXSUM or MTRAT") + } + params["feeSystemTypeCode"] = reqParams.FeeSystemTypeCode + } + + if reqParams.UserData != "" { + if len := len(reqParams.UserData); len > 21847 { + return nil, errors.New("Length of UserData should be min 1 or max 21847") + } + params["userData"] = base64.StdEncoding.EncodeToString([]byte(reqParams.UserData)) + } + + if reqParams.ZoneNo != "" { + params["zoneNo"] = reqParams.ZoneNo + } + + if len(reqParams.AccessControlGroupConfigurationNoList) > 0 { + for k, v := range reqParams.AccessControlGroupConfigurationNoList { + params[fmt.Sprintf("accessControlGroupConfigurationNoList.%d", k+1)] = v + } + } + + return params, nil +} + +// CreateServerInstances create server instances +func (s *Conn) CreateServerInstances(reqParams *RequestCreateServerInstance) (*ServerInstanceList, error) { + params, err := processCreateServerInstancesParams(reqParams) + if err != nil { + return nil, err + } + + params["action"] = "createServerInstances" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := ServerInstanceList{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + var responseCreateServerInstances = ServerInstanceList{} + if err := xml.Unmarshal([]byte(bytes), &responseCreateServerInstances); err != nil { + fmt.Println(err) + return nil, err + } + + return &responseCreateServerInstances, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/deleteBlockStorageInstances.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/deleteBlockStorageInstances.go new file mode 100644 index 000000000..c47f96bfb --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/deleteBlockStorageInstances.go @@ -0,0 +1,60 @@ +package sdk + +import ( + "encoding/xml" + "errors" + "fmt" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +func processDeleteBlockStorageInstancesParams(blockStorageInstanceNoList []string) (map[string]string, error) { + params := make(map[string]string) + + if len(blockStorageInstanceNoList) == 0 { + return params, errors.New("BlockStorageInstanceNoList field is Required") + } + + for k, v := range blockStorageInstanceNoList { + params[fmt.Sprintf("blockStorageInstanceNoList.%d", k+1)] = v + } + + return params, nil +} + +// DeleteBlockStorageInstances delete block storage instances +func (s *Conn) DeleteBlockStorageInstances(blockStorageInstanceNoList []string) (*BlockStorageInstanceList, error) { + params, err := processDeleteBlockStorageInstancesParams(blockStorageInstanceNoList) + if err != nil { + return nil, err + } + + params["action"] = "deleteBlockStorageInstances" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := BlockStorageInstanceList{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + var blockStorageInstanceList = BlockStorageInstanceList{} + if err := xml.Unmarshal([]byte(bytes), &blockStorageInstanceList); err != nil { + fmt.Println(err) + return nil, err + } + + return &blockStorageInstanceList, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/deleteLoginKey.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/deleteLoginKey.go new file mode 100644 index 000000000..7cc3cf257 --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/deleteLoginKey.go @@ -0,0 +1,59 @@ +package sdk + +import ( + "encoding/xml" + "errors" + "fmt" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +func processDeleteLoginKeyParams(keyName string) error { + if keyName == "" { + return errors.New("KeyName is required field") + } + + if len := len(keyName); len < 3 || len > 30 { + return errors.New("Length of KeyName should be min 3 or max 30") + } + + return nil +} + +// DeleteLoginKey delete login key with keyName +func (s *Conn) DeleteLoginKey(keyName string) (*common.CommonResponse, error) { + if err := processDeleteLoginKeyParams(keyName); err != nil { + return nil, err + } + + params := make(map[string]string) + + params["keyName"] = keyName + params["action"] = "deleteLoginKey" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := common.CommonResponse{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + var responseDeleteLoginKey = common.CommonResponse{} + if err := xml.Unmarshal([]byte(bytes), &responseDeleteLoginKey); err != nil { + return nil, err + } + + return &responseDeleteLoginKey, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/deletePublicIpInstances.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/deletePublicIpInstances.go new file mode 100644 index 000000000..5ea47602b --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/deletePublicIpInstances.go @@ -0,0 +1,62 @@ +package sdk + +import ( + "encoding/xml" + "errors" + "fmt" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +func processDeletePublicIPInstancesParams(reqParams *RequestDeletePublicIPInstances) (map[string]string, error) { + params := make(map[string]string) + + if reqParams == nil || len(reqParams.PublicIPInstanceNoList) == 0 { + return params, errors.New("Required field is not specified. location : publicIpInstanceNoList.N") + } + + if len(reqParams.PublicIPInstanceNoList) > 0 { + for k, v := range reqParams.PublicIPInstanceNoList { + params[fmt.Sprintf("publicIpInstanceNoList.%d", k+1)] = v + } + } + + return params, nil +} + +// DeletePublicIPInstances delete public ip instances +func (s *Conn) DeletePublicIPInstances(reqParams *RequestDeletePublicIPInstances) (*PublicIPInstanceList, error) { + params, err := processDeletePublicIPInstancesParams(reqParams) + if err != nil { + return nil, err + } + + params["action"] = "deletePublicIpInstances" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := PublicIPInstanceList{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + var publicIPInstanceList = PublicIPInstanceList{} + if err := xml.Unmarshal([]byte(bytes), &publicIPInstanceList); err != nil { + fmt.Println(err) + return nil, err + } + + return &publicIPInstanceList, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/disassociatePublicIpFromServerInstance.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/disassociatePublicIpFromServerInstance.go new file mode 100644 index 000000000..6d1db9efc --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/disassociatePublicIpFromServerInstance.go @@ -0,0 +1,54 @@ +package sdk + +import ( + "encoding/xml" + "errors" + "fmt" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +func processDisassociatePublicIPParams(PublicIPInstanceNo string) error { + if PublicIPInstanceNo == "" { + return errors.New("Required field is not specified. location : publicIpInstanceNo") + } + + return nil +} + +// DisassociatePublicIP diassociate public ip from server instance +func (s *Conn) DisassociatePublicIP(PublicIPInstanceNo string) (*PublicIPInstanceList, error) { + if err := processDisassociatePublicIPParams(PublicIPInstanceNo); err != nil { + return nil, err + } + + params := make(map[string]string) + params["publicIpInstanceNo"] = PublicIPInstanceNo + params["action"] = "disassociatePublicIpFromServerInstance" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := PublicIPInstanceList{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + var responseDisassociatePublicIPInstances = PublicIPInstanceList{} + if err := xml.Unmarshal([]byte(bytes), &responseDisassociatePublicIPInstances); err != nil { + return nil, err + } + + return &responseDisassociatePublicIPInstances, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getAccessControlGroupList.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getAccessControlGroupList.go new file mode 100644 index 000000000..937c877ce --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getAccessControlGroupList.go @@ -0,0 +1,89 @@ +package sdk + +import ( + "encoding/xml" + "errors" + "fmt" + "strconv" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +func processGetAccessControlGroupListParams(reqParams *RequestAccessControlGroupList) (map[string]string, error) { + params := make(map[string]string) + + if reqParams == nil { + return params, nil + } + + if len(reqParams.AccessControlGroupConfigurationNoList) > 0 { + for k, v := range reqParams.AccessControlGroupConfigurationNoList { + params[fmt.Sprintf("accessControlGroupConfigurationNoList.%d", k+1)] = v + } + } + + if reqParams.IsDefault { + params["isDefault"] = "true" + } + + if reqParams.AccessControlGroupName != "" { + if len(reqParams.AccessControlGroupName) < 3 || len(reqParams.AccessControlGroupName) > 30 { + return nil, errors.New("AccessControlGroupName must be between 3 and 30 characters in length") + } + params["accessControlGroupName"] = reqParams.AccessControlGroupName + } + + if reqParams.PageNo != 0 { + if reqParams.PageNo > 2147483647 { + return nil, errors.New("PageNo should be up to 2147483647") + } + + params["pageNo"] = strconv.Itoa(reqParams.PageNo) + } + + if reqParams.PageSize != 0 { + if reqParams.PageSize > 2147483647 { + return nil, errors.New("PageSize should be up to 2147483647") + } + + params["pageSize"] = strconv.Itoa(reqParams.PageSize) + } + + return params, nil +} + +// GetAccessControlGroupList get access control group list +func (s *Conn) GetAccessControlGroupList(reqParams *RequestAccessControlGroupList) (*AccessControlGroupList, error) { + params, err := processGetAccessControlGroupListParams(reqParams) + if err != nil { + return nil, err + } + + params["action"] = "getAccessControlGroupList" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := AccessControlGroupList{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + var AccessControlGroupList = AccessControlGroupList{} + if err := xml.Unmarshal([]byte(bytes), &AccessControlGroupList); err != nil { + return nil, err + } + + return &AccessControlGroupList, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getAccessControlRuleList.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getAccessControlRuleList.go new file mode 100644 index 000000000..c07f5985c --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getAccessControlRuleList.go @@ -0,0 +1,61 @@ +package sdk + +import ( + "encoding/xml" + "errors" + "fmt" + "strconv" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +func checkGetAccessControlRuleListParams(accessControlGroupConfigurationNo string) error { + if accessControlGroupConfigurationNo == "" { + return errors.New("accessControlGroupConfigurationNo is required") + } + + if no, err := strconv.Atoi(accessControlGroupConfigurationNo); err != nil { + return err + } else if no < 0 || no > 2147483647 { + return errors.New("accessControlGroupConfigurationNoeNo must be up to 2147483647") + } + + return nil +} + +// GetAccessControlRuleList get access control group list +func (s *Conn) GetAccessControlRuleList(accessControlGroupConfigurationNo string) (*AccessControlRuleList, error) { + if err := checkGetAccessControlRuleListParams(accessControlGroupConfigurationNo); err != nil { + return nil, err + } + + params := make(map[string]string) + params["accessControlGroupConfigurationNo"] = accessControlGroupConfigurationNo + params["action"] = "getAccessControlRuleList" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := AccessControlRuleList{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + var AccessControlRuleList = AccessControlRuleList{} + if err := xml.Unmarshal([]byte(bytes), &AccessControlRuleList); err != nil { + return nil, err + } + + return &AccessControlRuleList, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getBlockStorageInstanceList.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getBlockStorageInstanceList.go new file mode 100644 index 000000000..48f1506f3 --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getBlockStorageInstanceList.go @@ -0,0 +1,144 @@ +package sdk + +import ( + "encoding/xml" + "errors" + "fmt" + "strconv" + "strings" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +func processGetBlockStorageInstanceListParams(reqParams *RequestBlockStorageInstanceList) (map[string]string, error) { + params := make(map[string]string) + + if reqParams == nil { + return params, nil + } + + if reqParams.ServerInstanceNo != "" { + params["serverInstanceNo"] = reqParams.ServerInstanceNo + } + + if len(reqParams.BlockStorageInstanceNoList) > 0 { + for k, v := range reqParams.BlockStorageInstanceNoList { + params[fmt.Sprintf("blockStorageInstanceNoList.%d", k+1)] = v + } + } + + if reqParams.SearchFilterName != "" { + if reqParams.SearchFilterName != "blockStorageName" && reqParams.SearchFilterName != "attachmentInformation" { + return nil, errors.New("SearchFilterName should be blockStorageName or attachmentInformation") + } + params["searchFilterName"] = reqParams.SearchFilterName + } + + if reqParams.SearchFilterValue == "" { + params["searchFilterValue"] = reqParams.SearchFilterValue + } + + if len(reqParams.BlockStorageTypeCodeList) > 0 { + for k, v := range reqParams.BlockStorageTypeCodeList { + if v != "BASIC" && v != "SVRBS" { + return nil, errors.New("BlockStorageTypeCodeList value should be BASIC or SVRBS") + } + params[fmt.Sprintf("blockStorageTypeCodeList.%d", k+1)] = v + } + } + + if reqParams.PageNo != 0 { + if reqParams.PageNo > 2147483647 { + return nil, errors.New("PageNo should be up to 2147483647") + } + + params["pageNo"] = strconv.Itoa(reqParams.PageNo) + } + + if reqParams.PageSize != 0 { + if reqParams.PageSize > 2147483647 { + return nil, errors.New("PageSize should be up to 2147483647") + } + + params["pageSize"] = strconv.Itoa(reqParams.PageSize) + } + + if reqParams.BlockStorageInstanceStatusCode != "" { + if reqParams.BlockStorageInstanceStatusCode != "ATTAC" && reqParams.BlockStorageInstanceStatusCode != "CRAET" { + return nil, errors.New("BlockStorageInstanceStatusCode should be ATTAC or CRAET") + } + params["blockStorageInstanceStatusCode"] = reqParams.BlockStorageInstanceStatusCode + } + + if reqParams.DiskTypeCode != "" { + if reqParams.DiskTypeCode != "NET" && reqParams.DiskTypeCode != "LOCAL" { + return nil, errors.New("DiskTypeCode should be NET or LOCAL") + } + params["diskTypeCode"] = reqParams.DiskTypeCode + } + + if reqParams.DiskDetailTypeCode != "" { + if reqParams.DiskDetailTypeCode != "HDD" && reqParams.DiskDetailTypeCode != "SSD" { + return nil, errors.New("DiskDetailTypeCode should be HDD or SSD") + } + params["diskDetailTypeCode"] = reqParams.DiskDetailTypeCode + } + + if reqParams.RegionNo != "" { + params["regionNo"] = reqParams.RegionNo + } + + if reqParams.SortedBy != "" { + if strings.EqualFold(reqParams.SortedBy, "blockStorageName") || strings.EqualFold(reqParams.SortedBy, "blockStorageInstanceNo") { + params["sortedBy"] = reqParams.SortedBy + } else { + return nil, errors.New("SortedBy should be blockStorageName or blockStorageInstanceNo") + } + } + + if reqParams.SortingOrder != "" { + if strings.EqualFold(reqParams.SortingOrder, "ascending") || strings.EqualFold(reqParams.SortingOrder, "descending") { + params["sortingOrder"] = reqParams.SortingOrder + } else { + return nil, errors.New("SortingOrder should be ascending or descending") + } + } + + return params, nil +} + +// GetBlockStorageInstance Get block storage instance list +func (s *Conn) GetBlockStorageInstance(reqParams *RequestBlockStorageInstanceList) (*BlockStorageInstanceList, error) { + params, err := processGetBlockStorageInstanceListParams(reqParams) + if err != nil { + return nil, err + } + + params["action"] = "getBlockStorageInstanceList" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := BlockStorageInstanceList{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + var blockStorageInstanceList = BlockStorageInstanceList{} + if err := xml.Unmarshal([]byte(bytes), &blockStorageInstanceList); err != nil { + return nil, err + } + + return &blockStorageInstanceList, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getLoginKeyList.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getLoginKeyList.go new file mode 100644 index 000000000..d6866ebaf --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getLoginKeyList.go @@ -0,0 +1,77 @@ +package sdk + +import ( + "encoding/xml" + "errors" + "fmt" + "strconv" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +func processGetLoginKeyListParams(reqParams *RequestGetLoginKeyList) (map[string]string, error) { + params := make(map[string]string) + + if reqParams == nil { + return params, nil + } + + if reqParams.KeyName != "" { + if len := len(reqParams.KeyName); len < 3 || len > 20 { + return nil, errors.New("Length of KeyName should be min 3 or max 30") + } + params["keyName"] = reqParams.KeyName + } + + if reqParams.PageNo > 0 { + if reqParams.PageNo > 2147483647 { + return nil, errors.New("PageNo should be min 0 or max 2147483647") + } + params["pageNo"] = strconv.Itoa(reqParams.PageNo) + } + + if reqParams.PageSize > 0 { + if reqParams.PageSize > 2147483647 { + return nil, errors.New("PageSize should be min 0 or max 2147483647") + } + params["pageSize"] = strconv.Itoa(reqParams.PageSize) + } + + return params, nil +} + +// GetLoginKeyList get login key list +func (s *Conn) GetLoginKeyList(reqParams *RequestGetLoginKeyList) (*LoginKeyList, error) { + params, err := processGetLoginKeyListParams(reqParams) + if err != nil { + return nil, err + } + + params["action"] = "getLoginKeyList" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := LoginKeyList{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + loginKeyList := LoginKeyList{} + if err := xml.Unmarshal([]byte(bytes), &loginKeyList); err != nil { + return nil, err + } + + return &loginKeyList, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getMemberServerImagesList.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getMemberServerImagesList.go new file mode 100644 index 000000000..f5fe9f8bf --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getMemberServerImagesList.go @@ -0,0 +1,87 @@ +package sdk + +import ( + "encoding/xml" + "fmt" + "strconv" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +func processGetMemberServerImageListParams(reqParams *RequestServerImageList) (map[string]string, error) { + params := make(map[string]string) + + if reqParams == nil { + return params, nil + } + + if len(reqParams.MemberServerImageNoList) > 0 { + for k, v := range reqParams.MemberServerImageNoList { + params[fmt.Sprintf("memberServerImageNoList.%d", k+1)] = v + } + } + + if len(reqParams.PlatformTypeCodeList) > 0 { + for k, v := range reqParams.PlatformTypeCodeList { + params[fmt.Sprintf("platformTypeCodeList.%d", k+1)] = v + } + } + + if reqParams.PageNo != 0 { + params["pageNo"] = strconv.Itoa(reqParams.PageNo) + } + + if reqParams.PageSize != 0 { + params["pageSize"] = strconv.Itoa(reqParams.PageSize) + } + + if reqParams.RegionNo != "" { + params["regionNo"] = reqParams.RegionNo + } + + if reqParams.SortedBy != "" { + params["sortedBy"] = reqParams.SortedBy + } + + if reqParams.SortingOrder != "" { + params["sortingOrder"] = reqParams.SortingOrder + } + + return params, nil +} + +// GetMemberServerImageList get member server image list +func (s *Conn) GetMemberServerImageList(reqParams *RequestServerImageList) (*MemberServerImageList, error) { + params, err := processGetMemberServerImageListParams(reqParams) + if err != nil { + return nil, err + } + + params["action"] = "getMemberServerImageList" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := MemberServerImageList{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + var serverImageListsResp = MemberServerImageList{} + if err := xml.Unmarshal([]byte(bytes), &serverImageListsResp); err != nil { + return nil, err + } + + return &serverImageListsResp, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getPublicIpInstanceList.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getPublicIpInstanceList.go new file mode 100644 index 000000000..a781728c6 --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getPublicIpInstanceList.go @@ -0,0 +1,130 @@ +package sdk + +import ( + "encoding/xml" + "errors" + "fmt" + "strconv" + "strings" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +func processGetPublicIPInstanceListParams(reqParams *RequestPublicIPInstanceList) (map[string]string, error) { + params := make(map[string]string) + + if reqParams == nil { + return params, nil + } + + if reqParams.IsAssociated { + params["isAssociated"] = "true" + } + + if len(reqParams.PublicIPInstanceNoList) > 0 { + for k, v := range reqParams.PublicIPInstanceNoList { + params[fmt.Sprintf("publicIpInstanceNoList.%d", k+1)] = v + } + } + + if len(reqParams.PublicIPList) > 0 { + for k, v := range reqParams.PublicIPList { + if len(reqParams.PublicIPList) < 5 || len(reqParams.PublicIPList) > 15 { + return nil, errors.New("PublicIPList must be between 5 and 15 characters in length") + } + params[fmt.Sprintf("publicIpList.%d", k+1)] = v + } + } + + if reqParams.SearchFilterName != "" { + if reqParams.SearchFilterName != "publicIp" && reqParams.SearchFilterName != "associatedServerName" { + return nil, errors.New("SearchFilterName must be publicIp or associatedServerName") + } + params["searchFilterName"] = reqParams.SearchFilterName + } + + if reqParams.SearchFilterValue != "" { + params["searchFilterValue"] = reqParams.SearchFilterValue + } + + if reqParams.InternetLineTypeCode != "" { + if reqParams.InternetLineTypeCode != "PUBLC" && reqParams.InternetLineTypeCode != "GLBL" { + return params, errors.New("InternetLineTypeCode must be PUBLC or GLBL") + } + params["internetLineTypeCode"] = reqParams.InternetLineTypeCode + } + + if reqParams.RegionNo != "" { + params["regionNo"] = reqParams.RegionNo + } + + if reqParams.PageNo != 0 { + if reqParams.PageNo > 2147483647 { + return nil, errors.New("PageNo must be up to 2147483647") + } + + params["pageNo"] = strconv.Itoa(reqParams.PageNo) + } + + if reqParams.PageSize != 0 { + if reqParams.PageSize > 2147483647 { + return nil, errors.New("PageSize must be up to 2147483647") + } + + params["pageSize"] = strconv.Itoa(reqParams.PageSize) + } + + if reqParams.SortedBy != "" { + if strings.EqualFold(reqParams.SortedBy, "publicIp") || strings.EqualFold(reqParams.SortedBy, "publicIpInstanceNo") { + params["sortedBy"] = reqParams.SortedBy + } else { + return nil, errors.New("SortedBy must be publicIp or publicIpInstanceNo") + } + } + + if reqParams.SortingOrder != "" { + if strings.EqualFold(reqParams.SortingOrder, "ascending") || strings.EqualFold(reqParams.SortingOrder, "descending") { + params["sortingOrder"] = reqParams.SortingOrder + } else { + return nil, errors.New("SortingOrder must be ascending or descending") + } + } + + return params, nil +} + +// GetPublicIPInstanceList get public ip instance list +func (s *Conn) GetPublicIPInstanceList(reqParams *RequestPublicIPInstanceList) (*PublicIPInstanceList, error) { + params, err := processGetPublicIPInstanceListParams(reqParams) + if err != nil { + return nil, err + } + + params["action"] = "getPublicIpInstanceList" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := PublicIPInstanceList{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + var publicIPInstanceList = PublicIPInstanceList{} + if err := xml.Unmarshal([]byte(bytes), &publicIPInstanceList); err != nil { + return nil, err + } + + return &publicIPInstanceList, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getRegionList.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getRegionList.go new file mode 100644 index 000000000..0e1647684 --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getRegionList.go @@ -0,0 +1,40 @@ +package sdk + +import ( + "encoding/xml" + "fmt" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +// GetRegionList gets region list +func (s *Conn) GetRegionList() (*RegionList, error) { + params := make(map[string]string) + params["action"] = "getRegionList" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := RegionList{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + regionList := RegionList{} + if err := xml.Unmarshal([]byte(bytes), ®ionList); err != nil { + return nil, err + } + + return ®ionList, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getRootPassword.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getRootPassword.go new file mode 100644 index 000000000..9ec595f49 --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getRootPassword.go @@ -0,0 +1,67 @@ +package sdk + +import ( + "encoding/xml" + "errors" + "fmt" + "strings" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +func processGetRootPasswordParams(reqParams *RequestGetRootPassword) (map[string]string, error) { + params := make(map[string]string) + + if reqParams.ServerInstanceNo == "" { + return params, errors.New("Required field is not specified. location : serverInstanceNo") + } + + if reqParams.PrivateKey == "" { + return params, errors.New("Required field is not specified. location : privateKey") + } + + params["serverInstanceNo"] = reqParams.ServerInstanceNo + params["privateKey"] = reqParams.PrivateKey + + return params, nil +} + +// GetRootPassword get root password from server instance +func (s *Conn) GetRootPassword(reqParams *RequestGetRootPassword) (*RootPassword, error) { + params, err := processGetRootPasswordParams(reqParams) + if err != nil { + return nil, err + } + + params["action"] = "getRootPassword" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := RootPassword{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + responseGetRootPassword := RootPassword{} + if err := xml.Unmarshal([]byte(bytes), &responseGetRootPassword); err != nil { + return nil, err + } + + if responseGetRootPassword.RootPassword != "" { + responseGetRootPassword.RootPassword = strings.TrimSpace(responseGetRootPassword.RootPassword) + } + + return &responseGetRootPassword, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getServerImageProductList.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getServerImageProductList.go new file mode 100644 index 000000000..645649097 --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getServerImageProductList.go @@ -0,0 +1,88 @@ +package sdk + +import ( + "encoding/xml" + "errors" + "fmt" + "strconv" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +func processGetServerImageProductListParams(reqParams *RequestGetServerImageProductList) (map[string]string, error) { + params := make(map[string]string) + + if reqParams == nil { + return params, nil + } + + if reqParams.ExclusionProductCode != "" { + if len(reqParams.ExclusionProductCode) > 20 { + return params, errors.New("Length of exclusionProductCode should be max 20") + } + params["exclusionProductCode"] = reqParams.ExclusionProductCode + } + + if reqParams.ProductCode != "" { + if len(reqParams.ProductCode) > 20 { + return params, errors.New("Length of productCode should be max 20") + } + params["productCode"] = reqParams.ProductCode + } + + if len(reqParams.PlatformTypeCodeList) > 0 { + for k, v := range reqParams.PlatformTypeCodeList { + params[fmt.Sprintf("platformTypeCodeList.%d", k+1)] = v + } + } + + if reqParams.BlockStorageSize > 0 { + if reqParams.BlockStorageSize != 50 && reqParams.BlockStorageSize != 100 { + return nil, errors.New("blockStorageSize should be null, 50 or 100") + } + params["blockStorageSize"] = strconv.Itoa(reqParams.BlockStorageSize) + } + + if reqParams.RegionNo != "" { + params["regionNo"] = reqParams.RegionNo + } + + return params, nil +} + +// GetServerImageProductList gets server image product list +func (s *Conn) GetServerImageProductList(reqParams *RequestGetServerImageProductList) (*ProductList, error) { + params, err := processGetServerImageProductListParams(reqParams) + if err != nil { + return nil, err + } + + params["action"] = "getServerImageProductList" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := ProductList{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + var productList = ProductList{} + if err := xml.Unmarshal([]byte(bytes), &productList); err != nil { + fmt.Println(err) + return nil, err + } + + return &productList, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getServerInstanceList.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getServerInstanceList.go new file mode 100644 index 000000000..a4de2206e --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getServerInstanceList.go @@ -0,0 +1,133 @@ +package sdk + +import ( + "encoding/xml" + "errors" + "fmt" + "strconv" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +func processGetServerInstanceListParams(reqParams *RequestGetServerInstanceList) (map[string]string, error) { + params := make(map[string]string) + + if reqParams == nil { + return params, nil + } + + if len(reqParams.ServerInstanceNoList) > 0 { + for k, v := range reqParams.ServerInstanceNoList { + params[fmt.Sprintf("serverInstanceNoList.%d", k+1)] = v + } + } + + if reqParams.SearchFilterName != "" { + params["searchFilterName"] = reqParams.SearchFilterName + } + + if reqParams.SearchFilterValue != "" { + params["searchFilterValue"] = reqParams.SearchFilterValue + } + + if reqParams.PageNo > 0 { + if reqParams.PageNo > 2147483647 { + return nil, errors.New("PageNo should be less than 2147483647") + + } + params["pageNo"] = strconv.Itoa(reqParams.PageNo) + } + + if reqParams.PageSize > 0 { + if reqParams.PageSize > 2147483647 { + return nil, errors.New("PageSize should be less than 2147483647") + + } + params["pageSize"] = strconv.Itoa(reqParams.PageSize) + } + + if reqParams.ServerInstanceStatusCode != "" { + if reqParams.ServerInstanceStatusCode != "RUN" && reqParams.ServerInstanceStatusCode != "NSTOP" && reqParams.ServerInstanceStatusCode != "ING" { + return nil, errors.New("ServerInstanceStatusCode should be RUN, NSTOP or ING") + } + params["serverInstanceStatusCode"] = reqParams.ServerInstanceStatusCode + } + + if reqParams.InternetLineTypeCode != "" { + if reqParams.InternetLineTypeCode != "PUBLC" && reqParams.InternetLineTypeCode != "GLBL" { + return nil, errors.New("InternetLineTypeCode should be PUBLC or GLBL") + } + params["internetLineTypeCode"] = reqParams.InternetLineTypeCode + } + + if reqParams.RegionNo != "" { + params["regionNo"] = reqParams.RegionNo + } + + if reqParams.BaseBlockStorageDiskTypeCode != "" { + if reqParams.BaseBlockStorageDiskTypeCode != "NET" && reqParams.BaseBlockStorageDiskTypeCode != "LOCAL" { + return nil, errors.New("BaseBlockStorageDiskTypeCode should be NET or LOCAL") + } + params["baseBlockStorageDiskTypeCode"] = reqParams.BaseBlockStorageDiskTypeCode + } + + if reqParams.BaseBlockStorageDiskDetailTypeCode != "" { + if reqParams.BaseBlockStorageDiskDetailTypeCode != "HDD" && reqParams.BaseBlockStorageDiskDetailTypeCode != "SSD" { + return nil, errors.New("BaseBlockStorageDiskDetailTypeCode should be HDD or SSD") + } + params["baseBlockStorageDiskDetailTypeCode"] = reqParams.BaseBlockStorageDiskDetailTypeCode + } + + if reqParams.SortedBy != "" { + if reqParams.SortedBy != "serverName" && reqParams.SortedBy != "serverInstanceNo" { + return nil, errors.New("SortedBy should be serverName or serverInstanceNo") + } + params["sortedBy"] = reqParams.SortedBy + } + + if reqParams.SortingOrder != "" { + if reqParams.SortingOrder != "ascending" && reqParams.SortingOrder != "descending" { + return nil, errors.New("SortingOrder should be ascending or descending") + } + params["sortingOrder"] = reqParams.SortingOrder + } + + return params, nil +} + +// GetServerInstanceList get server instance list +func (s *Conn) GetServerInstanceList(reqParams *RequestGetServerInstanceList) (*ServerInstanceList, error) { + params, err := processGetServerInstanceListParams(reqParams) + if err != nil { + return nil, err + } + + params["action"] = "getServerInstanceList" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := ServerInstanceList{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + var serverInstanceList = ServerInstanceList{} + if err := xml.Unmarshal([]byte(bytes), &serverInstanceList); err != nil { + fmt.Println(err) + return nil, err + } + + return &serverInstanceList, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getServerProductList.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getServerProductList.go new file mode 100644 index 000000000..b932df876 --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getServerProductList.go @@ -0,0 +1,79 @@ +package sdk + +import ( + "encoding/xml" + "errors" + "fmt" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +func processGetServerProductListParams(reqParams *RequestGetServerProductList) (map[string]string, error) { + params := make(map[string]string) + + if reqParams == nil || reqParams.ServerImageProductCode == "" { + return params, errors.New("ServerImageProductCode field is required") + } + + if len(reqParams.ServerImageProductCode) > 20 { + return params, errors.New("Length of serverImageProductCode should be max 20") + } + + params["serverImageProductCode"] = reqParams.ServerImageProductCode + + if reqParams.ExclusionProductCode != "" { + if len(reqParams.ExclusionProductCode) > 20 { + return params, errors.New("Length of exclusionProductCode should be max 20") + } + params["exclusionProductCode"] = reqParams.ExclusionProductCode + } + + if reqParams.ProductCode != "" { + if len(reqParams.ProductCode) > 20 { + return params, errors.New("Length of productCode should be max 20") + } + params["productCode"] = reqParams.ProductCode + } + + if reqParams.RegionNo != "" { + params["regionNo"] = reqParams.RegionNo + } + + return params, nil +} + +// GetServerProductList : Get Server product list with server image product code by default. +func (s *Conn) GetServerProductList(reqParams *RequestGetServerProductList) (*ProductList, error) { + params, err := processGetServerProductListParams(reqParams) + if err != nil { + return nil, err + } + + params["action"] = "getServerProductList" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := ProductList{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + var productListResp = ProductList{} + if err := xml.Unmarshal([]byte(bytes), &productListResp); err != nil { + return nil, err + } + + return &productListResp, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getZoneList.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getZoneList.go new file mode 100644 index 000000000..42354eec0 --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/getZoneList.go @@ -0,0 +1,44 @@ +package sdk + +import ( + "encoding/xml" + "fmt" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +// GetZoneList get zone list +func (s *Conn) GetZoneList(regionNo string) (*ZoneList, error) { + params := make(map[string]string) + params["action"] = "getZoneList" + + if regionNo != "" { + params["regionNo"] = regionNo + } + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := ZoneList{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + ZoneList := ZoneList{} + if err := xml.Unmarshal([]byte(bytes), &ZoneList); err != nil { + return nil, err + } + + return &ZoneList, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/model.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/model.go new file mode 100644 index 000000000..02cac088e --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/model.go @@ -0,0 +1,359 @@ +package sdk + +import ( + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" +) + +type Conn struct { + accessKey string + secretKey string + apiURL string +} + +// ServerImage structures +type ServerImage struct { + MemberServerImageNo string `xml:"memberServerImageNo"` + MemberServerImageName string `xml:"memberServerImageName"` + MemberServerImageDescription string `xml:"memberServerImageDescription"` + OriginalServerInstanceNo string `xml:"originalServerInstanceNo"` + OriginalServerProductCode string `xml:"originalServerProductCode"` + OriginalServerName string `xml:"originalServerName"` + OriginalBaseBlockStorageDiskType common.CommonCode `xml:"originalBaseBlockStorageDiskType"` + OriginalServerImageProductCode string `xml:"originalServerImageProductCode"` + OriginalOsInformation string `xml:"originalOsInformation"` + OriginalServerImageName string `xml:"originalServerImageName"` + MemberServerImageStatusName string `xml:"memberServerImageStatusName"` + MemberServerImageStatus common.CommonCode `xml:"memberServerImageStatus"` + MemberServerImageOperation common.CommonCode `xml:"memberServerImageOperation"` + MemberServerImagePlatformType common.CommonCode `xml:"memberServerImagePlatformType"` + CreateDate string `xml:"createDate"` + Zone common.Zone `xml:"zone"` + Region common.Region `xml:"region"` + MemberServerImageBlockStorageTotalRows int `xml:"memberServerImageBlockStorageTotalRows"` + MemberServerImageBlockStorageTotalSize int `xml:"memberServerImageBlockStorageTotalSize"` +} + +type MemberServerImageList struct { + common.CommonResponse + TotalRows int `xml:"totalRows"` + MemberServerImageList []ServerImage `xml:"memberServerImageList>memberServerImage,omitempty"` +} + +type RequestServerImageList struct { + MemberServerImageNoList []string + PlatformTypeCodeList []string + PageNo int + PageSize int + RegionNo string + SortedBy string + SortingOrder string +} + +type RequestCreateServerImage struct { + MemberServerImageName string + MemberServerImageDescription string + ServerInstanceNo string +} + +type RequestGetServerImageProductList struct { + ExclusionProductCode string + ProductCode string + PlatformTypeCodeList []string + BlockStorageSize int + RegionNo string +} + +// ProductList : Response of server product list +type ProductList struct { + common.CommonResponse + TotalRows int `xml:"totalRows"` + Product []Product `xml:"productList>product,omitempty"` +} + +// Product : Product information of Server +type Product struct { + ProductCode string `xml:"productCode"` + ProductName string `xml:"productName"` + ProductType common.CommonCode `xml:"productType"` + ProductDescription string `xml:"productDescription"` + InfraResourceType common.CommonCode `xml:"infraResourceType"` + CPUCount int `xml:"cpuCount"` + MemorySize int `xml:"memorySize"` + BaseBlockStorageSize int `xml:"baseBlockStorageSize"` + PlatformType common.CommonCode `xml:"platformType"` + OsInformation string `xml:"osInformation"` + AddBlockStroageSize int `xml:"addBlockStroageSize"` +} + +// RequestCreateServerInstance is Server Instances structures +type RequestCreateServerInstance struct { + ServerImageProductCode string + ServerProductCode string + MemberServerImageNo string + ServerName string + ServerDescription string + LoginKeyName string + IsProtectServerTermination bool + ServerCreateCount int + ServerCreateStartNo int + InternetLineTypeCode string + FeeSystemTypeCode string + UserData string + ZoneNo string + AccessControlGroupConfigurationNoList []string +} + +type ServerInstanceList struct { + common.CommonResponse + TotalRows int `xml:"totalRows"` + ServerInstanceList []ServerInstance `xml:"serverInstanceList>serverInstance,omitempty"` +} + +type ServerInstance struct { + ServerInstanceNo string `xml:"serverInstanceNo"` + ServerName string `xml:"serverName"` + ServerDescription string `xml:"serverDescription"` + CPUCount int `xml:"cpuCount"` + MemorySize int `xml:"memorySize"` + BaseBlockStorageSize int `xml:"baseBlockStorageSize"` + PlatformType common.CommonCode `xml:"platformType"` + LoginKeyName string `xml:"loginKeyName"` + IsFeeChargingMonitoring bool `xml:"isFeeChargingMonitoring"` + PublicIP string `xml:"publicIp"` + PrivateIP string `xml:"privateIp"` + ServerImageName string `xml:"serverImageName"` + ServerInstanceStatus common.CommonCode `xml:"serverInstanceStatus"` + ServerInstanceOperation common.CommonCode `xml:"serverInstanceOperation"` + ServerInstanceStatusName string `xml:"serverInstanceStatusName"` + CreateDate string `xml:"createDate"` + Uptime string `xml:"uptime"` + ServerImageProductCode string `xml:"serverImageProductCode"` + ServerProductCode string `xml:"serverProductCode"` + IsProtectServerTermination bool `xml:"isProtectServerTermination"` + PortForwardingPublicIP string `xml:"portForwardingPublicIp"` + PortForwardingExternalPort int `xml:"portForwardingExternalPort"` + PortForwardingInternalPort int `xml:"portForwardingInternalPort"` + Zone common.Zone `xml:"zone"` + Region common.Region `xml:"region"` + BaseBlockStorageDiskType common.CommonCode `xml:"baseBlockStorageDiskType"` + BaseBlockStroageDiskDetailType common.CommonCode `xml:"baseBlockStroageDiskDetailType"` + InternetLineType common.CommonCode `xml:"internetLineType"` + UserData string `xml:"userData"` + AccessControlGroupList []AccessControlGroup `xml:"accessControlGroupList>accessControlGroup"` +} + +type AccessControlGroup struct { + AccessControlGroupConfigurationNo string `xml:"accessControlGroupConfigurationNo"` + AccessControlGroupName string `xml:"accessControlGroupName"` + AccessControlGroupDescription string `xml:"accessControlGroupDescription"` + IsDefault bool `xml:"isDefault"` + CreateDate string `xml:"createDate"` +} + +// RequestGetLoginKeyList is Login Key structures +type RequestGetLoginKeyList struct { + KeyName string + PageNo int + PageSize int +} + +type LoginKeyList struct { + common.CommonResponse + TotalRows int `xml:"totalRows"` + LoginKeyList []LoginKey `xml:"loginKeyList>loginKey,omitempty"` +} + +type LoginKey struct { + Fingerprint string `xml:"fingerprint"` + KeyName string `xml:"keyName"` + CreateDate string `xml:"createDate"` +} + +type PrivateKey struct { + common.CommonResponse + PrivateKey string `xml:"privateKey"` +} +type RequestCreatePublicIPInstance struct { + ServerInstanceNo string + PublicIPDescription string + InternetLineTypeCode string + RegionNo string +} + +type RequestPublicIPInstanceList struct { + IsAssociated bool + PublicIPInstanceNoList []string + PublicIPList []string + SearchFilterName string + SearchFilterValue string + InternetLineTypeCode string + RegionNo string + PageNo int + PageSize int + SortedBy string + SortingOrder string +} + +type PublicIPInstanceList struct { + common.CommonResponse + TotalRows int `xml:"totalRows"` + PublicIPInstanceList []PublicIPInstance `xml:"publicIpInstanceList>publicIpInstance,omitempty"` +} + +type PublicIPInstance struct { + PublicIPInstanceNo string `xml:"publicIpInstanceNo"` + PublicIP string `xml:"publicIp"` + PublicIPDescription string `xml:"publicIpDescription"` + CreateDate string `xml:"createDate"` + InternetLineType common.CommonCode `xml:"internetLineType"` + PublicIPInstanceStatusName string `xml:"publicIpInstanceStatusName"` + PublicIPInstanceStatus common.CommonCode `xml:"publicIpInstanceStatus"` + PublicIPInstanceOperation common.CommonCode `xml:"publicIpInstanceOperation"` + PublicIPKindType common.CommonCode `xml:"publicIpKindType"` + ServerInstance ServerInstance `xml:"serverInstanceAssociatedWithPublicIp"` +} + +type RequestDeletePublicIPInstances struct { + PublicIPInstanceNoList []string +} + +// RequestGetServerInstanceList : Get Server Instance List +type RequestGetServerInstanceList struct { + ServerInstanceNoList []string + SearchFilterName string + SearchFilterValue string + PageNo int + PageSize int + ServerInstanceStatusCode string + InternetLineTypeCode string + RegionNo string + BaseBlockStorageDiskTypeCode string + BaseBlockStorageDiskDetailTypeCode string + SortedBy string + SortingOrder string +} + +type RequestStopServerInstances struct { + ServerInstanceNoList []string +} + +type RequestTerminateServerInstances struct { + ServerInstanceNoList []string +} + +// RequestGetRootPassword : Request to get root password of the server +type RequestGetRootPassword struct { + ServerInstanceNo string + PrivateKey string +} + +// RootPassword : Response of getting root password of the server +type RootPassword struct { + common.CommonResponse + TotalRows int `xml:"totalRows"` + RootPassword string `xml:"rootPassword"` +} + +// RequestGetZoneList : Request to get zone list +type RequestGetZoneList struct { + regionNo string +} + +// ZoneList : Response of getting zone list +type ZoneList struct { + common.CommonResponse + TotalRows int `xml:"totalRows"` + Zone []common.Zone `xml:"zoneList>zone"` +} + +// RegionList : Response of getting region list +type RegionList struct { + common.CommonResponse + TotalRows int `xml:"totalRows"` + RegionList []common.Region `xml:"regionList>region,omitempty"` +} + +type RequestBlockStorageInstance struct { + BlockStorageName string + BlockStorageSize int + BlockStorageDescription string + ServerInstanceNo string +} + +type RequestBlockStorageInstanceList struct { + ServerInstanceNo string + BlockStorageInstanceNoList []string + SearchFilterName string + SearchFilterValue string + BlockStorageTypeCodeList []string + PageNo int + PageSize int + BlockStorageInstanceStatusCode string + DiskTypeCode string + DiskDetailTypeCode string + RegionNo string + SortedBy string + SortingOrder string +} + +type BlockStorageInstanceList struct { + common.CommonResponse + TotalRows int `xml:"totalRows"` + BlockStorageInstance []BlockStorageInstance `xml:"blockStorageInstanceList>blockStorageInstance,omitempty"` +} + +type BlockStorageInstance struct { + BlockStorageInstanceNo string `xml:"blockStorageInstanceNo"` + ServerInstanceNo string `xml:"serverInstanceNo"` + ServerName string `xml:"serverName"` + BlockStorageType common.CommonCode `xml:"blockStorageType"` + BlockStorageName string `xml:"blockStorageName"` + BlockStorageSize int `xml:"blockStorageSize"` + DeviceName string `xml:"deviceName"` + BlockStorageProductCode string `xml:"blockStorageProductCode"` + BlockStorageInstanceStatus common.CommonCode `xml:"blockStorageInstanceStatus"` + BlockStorageInstanceOperation common.CommonCode `xml:"blockStorageInstanceOperation"` + BlockStorageInstanceStatusName string `xml:"blockStorageInstanceStatusName"` + CreateDate string `xml:"createDate"` + BlockStorageInstanceDescription string `xml:"blockStorageInstanceDescription"` + DiskType common.CommonCode `xml:"diskType"` + DiskDetailType common.CommonCode `xml:"diskDetailType"` +} + +// RequestGetServerProductList : Request to get server product list +type RequestGetServerProductList struct { + ExclusionProductCode string + ProductCode string + ServerImageProductCode string + RegionNo string +} + +type RequestAccessControlGroupList struct { + AccessControlGroupConfigurationNoList []string + IsDefault bool + AccessControlGroupName string + PageNo int + PageSize int +} + +type AccessControlGroupList struct { + common.CommonResponse + TotalRows int `xml:"totalRows"` + AccessControlGroup []AccessControlGroup `xml:"accessControlGroupList>accessControlGroup,omitempty"` +} + +type AccessControlRuleList struct { + common.CommonResponse + TotalRows int `xml:"totalRows"` + AccessControlRuleList []AccessControlRule `xml:"accessControlRuleList>accessControlRule,omitempty"` +} + +type AccessControlRule struct { + AccessControlRuleConfigurationNo string `xml:"accessControlRuleConfigurationNo"` + AccessControlRuleDescription string `xml:"accessControlRuleDescription"` + SourceAccessControlRuleConfigurationNo string `xml:"sourceAccessControlRuleConfigurationNo"` + SourceAccessControlRuleName string `xml:"sourceAccessControlRuleName"` + ProtocolType common.CommonCode `xml:"protocolType"` + SourceIP string `xml:"sourceIp"` + DestinationPort string `xml:"destinationPort"` +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/stopServerInstances.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/stopServerInstances.go new file mode 100644 index 000000000..e3786e5fa --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/stopServerInstances.go @@ -0,0 +1,62 @@ +package sdk + +import ( + "encoding/xml" + "errors" + "fmt" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +func processStopServerInstancesParams(reqParams *RequestStopServerInstances) (map[string]string, error) { + params := make(map[string]string) + + if reqParams == nil || len(reqParams.ServerInstanceNoList) == 0 { + return params, errors.New("serverInstanceNoList is required") + } + + if len(reqParams.ServerInstanceNoList) > 0 { + for k, v := range reqParams.ServerInstanceNoList { + params[fmt.Sprintf("serverInstanceNoList.%d", k+1)] = v + } + } + + return params, nil +} + +// StopServerInstances stop server instances +func (s *Conn) StopServerInstances(reqParams *RequestStopServerInstances) (*ServerInstanceList, error) { + params, err := processStopServerInstancesParams(reqParams) + if err != nil { + return nil, err + } + + params["action"] = "stopServerInstances" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := ServerInstanceList{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + var serverInstanceList = ServerInstanceList{} + if err := xml.Unmarshal([]byte(bytes), &serverInstanceList); err != nil { + fmt.Println(err) + return nil, err + } + + return &serverInstanceList, nil +} diff --git a/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/terminateServerInstances.go b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/terminateServerInstances.go new file mode 100644 index 000000000..598f8efa1 --- /dev/null +++ b/vendor/github.com/NaverCloudPlatform/ncloud-sdk-go/sdk/terminateServerInstances.go @@ -0,0 +1,62 @@ +package sdk + +import ( + "encoding/xml" + "errors" + "fmt" + + common "github.com/NaverCloudPlatform/ncloud-sdk-go/common" + request "github.com/NaverCloudPlatform/ncloud-sdk-go/request" +) + +func processTerminateServerInstancesParams(reqParams *RequestTerminateServerInstances) (map[string]string, error) { + params := make(map[string]string) + + if reqParams == nil || len(reqParams.ServerInstanceNoList) == 0 { + return params, errors.New("serverInstanceNoList is required") + } + + if len(reqParams.ServerInstanceNoList) > 0 { + for k, v := range reqParams.ServerInstanceNoList { + params[fmt.Sprintf("serverInstanceNoList.%d", k+1)] = v + } + } + + return params, nil +} + +// TerminateServerInstances terminate server instances +func (s *Conn) TerminateServerInstances(reqParams *RequestTerminateServerInstances) (*ServerInstanceList, error) { + params, err := processTerminateServerInstancesParams(reqParams) + if err != nil { + return nil, err + } + + params["action"] = "terminateServerInstances" + + bytes, resp, err := request.NewRequest(s.accessKey, s.secretKey, "GET", s.apiURL+"server/", params) + if err != nil { + return nil, err + } + + if resp.StatusCode != 200 { + responseError, err := common.ParseErrorResponse(bytes) + if err != nil { + return nil, err + } + + respError := ServerInstanceList{} + respError.ReturnCode = responseError.ReturnCode + respError.ReturnMessage = responseError.ReturnMessage + + return &respError, fmt.Errorf("%s %s - error code: %d , error message: %s", resp.Status, string(bytes), responseError.ReturnCode, responseError.ReturnMessage) + } + + var serverInstanceList = ServerInstanceList{} + if err := xml.Unmarshal([]byte(bytes), &serverInstanceList); err != nil { + fmt.Println(err) + return nil, err + } + + return &serverInstanceList, nil +} diff --git a/vendor/vendor.json b/vendor/vendor.json index 4438b367e..c5714b58f 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -209,6 +209,30 @@ "revision": "4fe03583929022c9c96829401ffabc755e69782e", "revisionTime": "2017-06-25T21:53:50Z" }, + { + "checksumSHA1": "N0jIjg2HeB8fM7dt8OED2BiRZz0=", + "path": "github.com/NaverCloudPlatform/ncloud-sdk-go/common", + "revision": "c2e73f942591b0f033a3c6df00f44badb2347c38", + "revisionTime": "2018-01-10T05:50:12Z" + }, + { + "checksumSHA1": "7lT5Xmeo2MhE6CJvIInZyLBu6S8=", + "path": "github.com/NaverCloudPlatform/ncloud-sdk-go/oauth", + "revision": "c2e73f942591b0f033a3c6df00f44badb2347c38", + "revisionTime": "2018-01-10T05:50:12Z" + }, + { + "checksumSHA1": "DpfU1gyyhIc1BuKZUZDRVDBkeSc=", + "path": "github.com/NaverCloudPlatform/ncloud-sdk-go/request", + "revision": "c2e73f942591b0f033a3c6df00f44badb2347c38", + "revisionTime": "2018-01-10T05:50:12Z" + }, + { + "checksumSHA1": "QnZ2RMlms/zYbD8jg+lyS8ncQOY=", + "path": "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk", + "revision": "c2e73f942591b0f033a3c6df00f44badb2347c38", + "revisionTime": "2018-01-10T05:50:12Z" + }, { "checksumSHA1": "HttiPj314X1a0i2Jen1p6lRH/vE=", "path": "github.com/aliyun/aliyun-oss-go-sdk/oss", From 26030d750cd47eba3713b4d85ab6313f8bfefb81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=8B=E1=85=B2=E1=84=89=E1=85=A5=E1=86=BC=E1=84=83?= =?UTF-8?q?=E1=85=A5=E1=86=A8?= Date: Fri, 12 Jan 2018 10:12:47 +0900 Subject: [PATCH 6/7] update err format --- builder/ncloud/step_create_block_storage_instance.go | 2 +- builder/ncloud/step_create_login_key.go | 2 +- builder/ncloud/step_create_public_ip_instance.go | 4 ++-- builder/ncloud/step_delete_block_storage_instance.go | 2 +- builder/ncloud/step_delete_login_key.go | 2 +- builder/ncloud/step_get_rootpassword.go | 2 +- builder/ncloud/step_stop_server_instance.go | 2 +- builder/ncloud/step_terminate_server_instance.go | 4 ++-- builder/ncloud/step_validate_template.go | 4 ++-- 9 files changed, 12 insertions(+), 12 deletions(-) diff --git a/builder/ncloud/step_create_block_storage_instance.go b/builder/ncloud/step_create_block_storage_instance.go index ef7306264..7e4d4b54a 100644 --- a/builder/ncloud/step_create_block_storage_instance.go +++ b/builder/ncloud/step_create_block_storage_instance.go @@ -42,7 +42,7 @@ func (s *StepCreateBlockStorageInstance) createBlockStorageInstance(serverInstan blockStorageInstanceList, err := s.Conn.CreateBlockStorageInstance(reqParams) if err != nil { - return "", fmt.Errorf("error code: %d, error message: %s", blockStorageInstanceList.ReturnCode, blockStorageInstanceList.ReturnMessage) + return "", err } log.Println("Block Storage Instance information : ", blockStorageInstanceList.BlockStorageInstance[0]) diff --git a/builder/ncloud/step_create_login_key.go b/builder/ncloud/step_create_login_key.go index 7dddebd25..d200c3106 100644 --- a/builder/ncloud/step_create_login_key.go +++ b/builder/ncloud/step_create_login_key.go @@ -38,7 +38,7 @@ func (s *StepCreateLoginKey) createLoginKey() (*LoginKey, error) { privateKey, err := s.Conn.CreateLoginKey(KeyName) if err != nil { - return nil, fmt.Errorf("error code: %d , error message: %s", privateKey.ReturnCode, privateKey.ReturnMessage) + return nil, err } return &LoginKey{KeyName, privateKey.PrivateKey}, nil diff --git a/builder/ncloud/step_create_public_ip_instance.go b/builder/ncloud/step_create_public_ip_instance.go index 88d98eb6c..1ea1517c5 100644 --- a/builder/ncloud/step_create_public_ip_instance.go +++ b/builder/ncloud/step_create_public_ip_instance.go @@ -72,7 +72,7 @@ func (s *StepCreatePublicIPInstance) createPublicIPInstance(serverInstanceNo str publicIPInstanceList, err := s.Conn.CreatePublicIPInstance(reqParams) if err != nil { - return nil, fmt.Errorf("error code: %d, error message: %s", publicIPInstanceList.ReturnCode, publicIPInstanceList.ReturnMessage) + return nil, err } publicIPInstance := publicIPInstanceList.PublicIPInstanceList[0] @@ -143,7 +143,7 @@ func (s *StepCreatePublicIPInstance) waitPublicIPInstanceStatus(publicIPInstance for { resp, err := s.Conn.GetPublicIPInstanceList(reqParams) if err != nil { - log.Printf("error code: %d, error message: %s", resp.ReturnCode, resp.ReturnMessage) + log.Printf(err.Error()) c1 <- err return } diff --git a/builder/ncloud/step_delete_block_storage_instance.go b/builder/ncloud/step_delete_block_storage_instance.go index 3c6c44b82..a077d4880 100644 --- a/builder/ncloud/step_delete_block_storage_instance.go +++ b/builder/ncloud/step_delete_block_storage_instance.go @@ -65,7 +65,7 @@ func (s *StepDeleteBlockStorageInstance) deleteBlockStorageInstance(serverInstan result, err := s.Conn.DeleteBlockStorageInstances(blockStorageInstanceList) if err != nil { - return fmt.Errorf("error code: %d , error message: %s", result.ReturnCode, result.ReturnMessage) + return err } s.Say(fmt.Sprintf("Block Storage Instance is deleted. Block Storage InstanceNo is %s", blockStorageInstanceList)) diff --git a/builder/ncloud/step_delete_login_key.go b/builder/ncloud/step_delete_login_key.go index b0cfbf7a1..c53dc3d1c 100644 --- a/builder/ncloud/step_delete_login_key.go +++ b/builder/ncloud/step_delete_login_key.go @@ -30,7 +30,7 @@ func NewStepDeleteLoginKey(conn *ncloud.Conn, ui packer.Ui) *StepDeleteLoginKey func (s *StepDeleteLoginKey) deleteLoginKey(keyName string) error { resp, err := s.Conn.DeleteLoginKey(keyName) if err != nil { - return fmt.Errorf("error code: %d , error message: %s", resp.ReturnCode, resp.ReturnMessage) + return err } return nil diff --git a/builder/ncloud/step_get_rootpassword.go b/builder/ncloud/step_get_rootpassword.go index c5070d179..3766d86df 100644 --- a/builder/ncloud/step_get_rootpassword.go +++ b/builder/ncloud/step_get_rootpassword.go @@ -34,7 +34,7 @@ func (s *StepGetRootPassword) getRootPassword(serverInstanceNo string, privateKe rootPassword, err := s.Conn.GetRootPassword(reqParams) if err != nil { - return "", fmt.Errorf("error code: %d, error message: %s", rootPassword.ReturnCode, rootPassword.ReturnMessage) + return "", err } return rootPassword.RootPassword, nil diff --git a/builder/ncloud/step_stop_server_instance.go b/builder/ncloud/step_stop_server_instance.go index 1c9252ed2..f9cce7d9f 100644 --- a/builder/ncloud/step_stop_server_instance.go +++ b/builder/ncloud/step_stop_server_instance.go @@ -35,7 +35,7 @@ func (s *StepStopServerInstance) stopServerInstance(serverInstanceNo string) err serverInstanceList, err := s.Conn.StopServerInstances(reqParams) if err != nil { - return fmt.Errorf("error code: %d , error message: %s", serverInstanceList.ReturnCode, serverInstanceList.ReturnMessage) + return err } s.Say(fmt.Sprintf("Server Instance is stopping. Server InstanceNo is %s", serverInstanceList.ServerInstanceList[0].ServerInstanceNo)) diff --git a/builder/ncloud/step_terminate_server_instance.go b/builder/ncloud/step_terminate_server_instance.go index 5d60236f0..208e6f1e6 100644 --- a/builder/ncloud/step_terminate_server_instance.go +++ b/builder/ncloud/step_terminate_server_instance.go @@ -35,7 +35,7 @@ func (s *StepTerminateServerInstance) terminateServerInstance(serverInstanceNo s serverInstanceList, err := s.Conn.TerminateServerInstances(reqParams) if err != nil { - return fmt.Errorf("error code: %d , error message: %s", serverInstanceList.ReturnCode, serverInstanceList.ReturnMessage) + return err } c1 := make(chan error, 1) @@ -48,7 +48,7 @@ func (s *StepTerminateServerInstance) terminateServerInstance(serverInstanceNo s serverInstanceList, err := s.Conn.GetServerInstanceList(reqParams) if err != nil { - c1 <- fmt.Errorf("error code: %d , error message: %s", serverInstanceList.ReturnCode, serverInstanceList.ReturnMessage) + c1 <- err return } else if serverInstanceList.TotalRows == 0 { c1 <- nil diff --git a/builder/ncloud/step_validate_template.go b/builder/ncloud/step_validate_template.go index 0007bfa40..d645111c4 100644 --- a/builder/ncloud/step_validate_template.go +++ b/builder/ncloud/step_validate_template.go @@ -45,7 +45,7 @@ func (s *StepValidateTemplate) getZoneNo() error { regionList, err := s.Conn.GetRegionList() if err != nil { - return fmt.Errorf("error code: %d , error message: %s", regionList.ReturnCode, regionList.ReturnMessage) + return err } var regionNo string @@ -64,7 +64,7 @@ func (s *StepValidateTemplate) getZoneNo() error { // Get ZoneNo ZoneList, err := s.Conn.GetZoneList(regionNo) if err != nil { - return fmt.Errorf("error code: %d , error message: %s", ZoneList.ReturnCode, ZoneList.ReturnMessage) + return err } if len(ZoneList.Zone) > 0 { From b909e9d4e672f7536afd0bdda25b3b5478463134 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=8B=E1=85=B2=E1=84=89=E1=85=A5=E1=86=BC=E1=84=83?= =?UTF-8?q?=E1=85=A5=E1=86=A8?= Date: Fri, 12 Jan 2018 10:15:40 +0900 Subject: [PATCH 7/7] remove not used variables --- builder/ncloud/step_create_server_image.go | 2 +- builder/ncloud/step_create_server_instance.go | 2 +- builder/ncloud/step_delete_block_storage_instance.go | 2 +- builder/ncloud/step_delete_login_key.go | 2 +- builder/ncloud/step_get_rootpassword.go | 2 -- builder/ncloud/step_terminate_server_instance.go | 3 +-- 6 files changed, 5 insertions(+), 8 deletions(-) diff --git a/builder/ncloud/step_create_server_image.go b/builder/ncloud/step_create_server_image.go index 4256664f4..ea0784058 100644 --- a/builder/ncloud/step_create_server_image.go +++ b/builder/ncloud/step_create_server_image.go @@ -44,7 +44,7 @@ func (s *StepCreateServerImage) createServerImage(serverInstanceNo string) (*ncl memberServerImageList, err := s.Conn.CreateMemberServerImage(reqParams) if err != nil { - return nil, fmt.Errorf("error code: %d , error message: %s", memberServerImageList.ReturnCode, memberServerImageList.ReturnMessage) + return nil, err } serverImage := memberServerImageList.MemberServerImageList[0] diff --git a/builder/ncloud/step_create_server_instance.go b/builder/ncloud/step_create_server_instance.go index 040e72eb1..d7decd4d8 100644 --- a/builder/ncloud/step_create_server_instance.go +++ b/builder/ncloud/step_create_server_instance.go @@ -55,7 +55,7 @@ func (s *StepCreateServerInstance) createServerInstance(loginKeyName string, zon serverInstanceList, err := s.Conn.CreateServerInstances(reqParams) if err != nil { - return "", fmt.Errorf("error code: %d, error message: %s", serverInstanceList.ReturnCode, serverInstanceList.ReturnMessage) + return "", err } s.serverInstanceNo = serverInstanceList.ServerInstanceList[0].ServerInstanceNo diff --git a/builder/ncloud/step_delete_block_storage_instance.go b/builder/ncloud/step_delete_block_storage_instance.go index a077d4880..61f8b7c3c 100644 --- a/builder/ncloud/step_delete_block_storage_instance.go +++ b/builder/ncloud/step_delete_block_storage_instance.go @@ -63,7 +63,7 @@ func (s *StepDeleteBlockStorageInstance) deleteBlockStorageInstance(serverInstan return nil } - result, err := s.Conn.DeleteBlockStorageInstances(blockStorageInstanceList) + _, err := s.Conn.DeleteBlockStorageInstances(blockStorageInstanceList) if err != nil { return err } diff --git a/builder/ncloud/step_delete_login_key.go b/builder/ncloud/step_delete_login_key.go index c53dc3d1c..18256c7d8 100644 --- a/builder/ncloud/step_delete_login_key.go +++ b/builder/ncloud/step_delete_login_key.go @@ -28,7 +28,7 @@ func NewStepDeleteLoginKey(conn *ncloud.Conn, ui packer.Ui) *StepDeleteLoginKey } func (s *StepDeleteLoginKey) deleteLoginKey(keyName string) error { - resp, err := s.Conn.DeleteLoginKey(keyName) + _, err := s.Conn.DeleteLoginKey(keyName) if err != nil { return err } diff --git a/builder/ncloud/step_get_rootpassword.go b/builder/ncloud/step_get_rootpassword.go index 3766d86df..b696e594d 100644 --- a/builder/ncloud/step_get_rootpassword.go +++ b/builder/ncloud/step_get_rootpassword.go @@ -1,8 +1,6 @@ package ncloud import ( - "fmt" - ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" "github.com/hashicorp/packer/packer" "github.com/mitchellh/multistep" diff --git a/builder/ncloud/step_terminate_server_instance.go b/builder/ncloud/step_terminate_server_instance.go index 208e6f1e6..aa154812b 100644 --- a/builder/ncloud/step_terminate_server_instance.go +++ b/builder/ncloud/step_terminate_server_instance.go @@ -2,7 +2,6 @@ package ncloud import ( "errors" - "fmt" "time" ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk" @@ -33,7 +32,7 @@ func (s *StepTerminateServerInstance) terminateServerInstance(serverInstanceNo s reqParams := new(ncloud.RequestTerminateServerInstances) reqParams.ServerInstanceNoList = []string{serverInstanceNo} - serverInstanceList, err := s.Conn.TerminateServerInstances(reqParams) + _, err := s.Conn.TerminateServerInstances(reqParams) if err != nil { return err }