mirror of
https://github.com/yunionio/cloudpods.git
synced 2026-09-01 15:07:17 +08:00
resolve conflict
This commit is contained in:
Generated
+58
@@ -352,6 +352,53 @@
|
||||
revision = "7c663266750e7d82587642f65e60bc4083f1f84e"
|
||||
version = "v0.2.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:324591cd9122f94cc39a87bd44ec71153672c239e2cff5743bfad96b60be3749"
|
||||
name = "github.com/googollee/go-engine.io"
|
||||
packages = [
|
||||
".",
|
||||
"message",
|
||||
"parser",
|
||||
"polling",
|
||||
"transport",
|
||||
"websocket",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "e2f255711dcb2ea41e42c6d9d98c172d7edf6509"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:62db7727ec8e026e51e1b46696e0fdf6a956a701032eca4d63e311816820717c"
|
||||
name = "github.com/googollee/go-socket.io"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "f12da5711bc66c18a0724987fff7f4f3db35c70f"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:c79fb010be38a59d657c48c6ba1d003a8aa651fa56b579d959d74573b7dff8e1"
|
||||
name = "github.com/gorilla/context"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "08b5f424b9271eedf6f9f0ce86cb9396ed337a42"
|
||||
version = "v1.1.1"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:e73f5b0152105f18bc131fba127d9949305c8693f8a762588a82a48f61756f5f"
|
||||
name = "github.com/gorilla/mux"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "e3702bed27f0d39777b0b37b664b6280e8ef8fbf"
|
||||
version = "v1.6.2"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:7b5c6e2eeaa9ae5907c391a91c132abfd5c9e8a784a341b5625e750c67e6825d"
|
||||
name = "github.com/gorilla/websocket"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "66b9c49e59c6c48f0ffce28c2d8b8a5678502c6d"
|
||||
version = "v1.4.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:4e08dc2383a46b3107f0b34ca338c4459e8fc8ee90e46a60e728aa8a2b21d558"
|
||||
@@ -442,6 +489,14 @@
|
||||
pruneopts = "UT"
|
||||
revision = "b84e30acd515aadc4b783ad4ff83aff3299bdfe0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:094e04c4742b596bce4455eb535d4e4365016b44016db76f8593211406d77299"
|
||||
name = "github.com/kr/pty"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "fa756f09eeb418bf1cc6268c66ceaad9bb98f598"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:c658e84ad3916da105a761660dcaeb01e63416c8ec7bc62256a9b411a05fcd67"
|
||||
name = "github.com/mattn/go-colorable"
|
||||
@@ -1150,11 +1205,14 @@
|
||||
"github.com/fatih/color",
|
||||
"github.com/go-sql-driver/mysql",
|
||||
"github.com/golang-plus/uuid",
|
||||
"github.com/googollee/go-socket.io",
|
||||
"github.com/gorilla/mux",
|
||||
"github.com/gosuri/uitable",
|
||||
"github.com/hako/durafmt",
|
||||
"github.com/jinzhu/gorm",
|
||||
"github.com/jinzhu/gorm/dialects/mysql",
|
||||
"github.com/json-iterator/go",
|
||||
"github.com/kr/pty",
|
||||
"github.com/mholt/caddy",
|
||||
"github.com/mholt/caddy/startupshutdown",
|
||||
"github.com/miekg/dns",
|
||||
|
||||
+14
-2
@@ -85,7 +85,19 @@
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/hako/durafmt"
|
||||
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/Azure/azure-sdk-for-go"
|
||||
version = "19.1.0"
|
||||
version = "19.1.0"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/googollee/go-socket.io"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/kr/pty"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/Microsoft/azure-vhd-utils"
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
region = 'LzxHQ'
|
||||
address = '10.168.222.245'
|
||||
port = 8899
|
||||
auth_uri = 'http://10.168.222.245:35357/v3'
|
||||
admin_user = 'regionadmin'
|
||||
admin_password = 'iygPtGX6r7NZ_tW_'
|
||||
admin_tenant_name = 'system'
|
||||
|
||||
api_server = "http://webconsole.yunion.io"
|
||||
|
||||
log_level = "debug"
|
||||
@@ -0,0 +1 @@
|
||||
DESCRIPTION="Yunion Cloud Webconsole Service"
|
||||
+16
-8
@@ -9,7 +9,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
prompt "github.com/c-bata/go-prompt"
|
||||
"github.com/c-bata/go-prompt"
|
||||
|
||||
"yunion.io/x/log"
|
||||
"yunion.io/x/pkg/util/version"
|
||||
@@ -28,7 +28,7 @@ type BaseOptions struct {
|
||||
Version bool `help:"Show version"`
|
||||
Timeout int `default:"600" help:"Number of seconds to wait for a response"`
|
||||
Insecure bool `default:"false" help:"Allow skip server cert verification if URL is https" short-token:"k"`
|
||||
NoCachedToken bool `default:"false" help:"Force not use cached token"`
|
||||
NoCachedToken bool `default:"$NO_CACHED_TOKEN|false" help:"Force not use cached token"`
|
||||
OsUsername string `default:"$OS_USERNAME" help:"Username, defaults to env[OS_USERNAME]"`
|
||||
OsPassword string `default:"$OS_PASSWORD" help:"Password, defaults to env[OS_PASSWORD]"`
|
||||
// OsProjectId string `default:"$OS_PROJECT_ID" help:"Proejct ID, defaults to env[OS_PROJECT_ID]"`
|
||||
@@ -126,8 +126,11 @@ func newClientSession(options *BaseOptions) (*mcclient.ClientSession, error) {
|
||||
options.Insecure)
|
||||
|
||||
var cacheToken mcclient.TokenCredential
|
||||
tokenCachePath := filepath.Join(os.TempDir(), "OS_AUTH_CACHE_TOKEN")
|
||||
authUrlAlter := strings.Replace(options.OsAuthURL, "/", "", -1)
|
||||
authUrlAlter = strings.Replace(authUrlAlter, ":", "", -1)
|
||||
tokenCachePath := filepath.Join(os.TempDir(), fmt.Sprintf("OS_AUTH_CACHE_TOKEN-%s-%s-%s-%s", authUrlAlter, options.OsUsername, options.OsDomainName, options.OsProjectName))
|
||||
cacheFile, err := os.Open(tokenCachePath)
|
||||
|
||||
if err == nil && cacheFile != nil && !options.NoCachedToken {
|
||||
fileInfo, _ := cacheFile.Stat()
|
||||
dur, err := time.ParseDuration("-24h")
|
||||
@@ -138,13 +141,14 @@ func newClientSession(options *BaseOptions) (*mcclient.ClientSession, error) {
|
||||
err := json.Unmarshal(bytesToken, token)
|
||||
if err != nil {
|
||||
fmt.Printf("Unmarshal token error:%s", err)
|
||||
} else {
|
||||
} else if token.IsValid() {
|
||||
cacheToken = token
|
||||
}
|
||||
}
|
||||
cacheFile.Close()
|
||||
}
|
||||
}
|
||||
|
||||
if cacheToken == nil {
|
||||
token, err := client.Authenticate(options.OsUsername,
|
||||
options.OsPassword,
|
||||
@@ -158,12 +162,16 @@ func newClientSession(options *BaseOptions) (*mcclient.ClientSession, error) {
|
||||
if err != nil {
|
||||
fmt.Printf("Marshal token error:%s", err)
|
||||
} else {
|
||||
fo, _ := os.Create(tokenCachePath)
|
||||
fo.Write(bytesCacheToken)
|
||||
fo.Close()
|
||||
fo, err := os.Create(tokenCachePath)
|
||||
if err != nil {
|
||||
fmt.Printf("Save token cache fail: %s", err)
|
||||
} else {
|
||||
fo.Write(bytesCacheToken)
|
||||
fo.Close()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
fmt.Printf("******** Use Token Cache At %s ********\n", tokenCachePath)
|
||||
// fmt.Printf("******** Use Token Cache At %s ********\n", tokenCachePath)
|
||||
}
|
||||
|
||||
session := client.NewSession(options.OsRegionName,
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
package shell
|
||||
|
||||
import (
|
||||
"yunion.io/x/jsonutils"
|
||||
|
||||
"yunion.io/x/onecloud/pkg/mcclient"
|
||||
"yunion.io/x/onecloud/pkg/mcclient/modules"
|
||||
"yunion.io/x/onecloud/pkg/mcclient/options"
|
||||
)
|
||||
|
||||
func init() {
|
||||
type ElasticipListOptions struct {
|
||||
Manager string `help:"Show servers imported from manager"`
|
||||
Region string `help:"Show servers in cloudregion"`
|
||||
|
||||
options.BaseListOptions
|
||||
}
|
||||
R(&ElasticipListOptions{}, "eip-list", "List elastic IPs", func(s *mcclient.ClientSession, args *ElasticipListOptions) error {
|
||||
var params *jsonutils.JSONDict
|
||||
{
|
||||
var err error
|
||||
params, err = args.BaseListOptions.Params()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if len(args.Manager) > 0 {
|
||||
params.Add(jsonutils.NewString(args.Manager), "manager")
|
||||
}
|
||||
if len(args.Region) > 0 {
|
||||
params.Add(jsonutils.NewString(args.Region), "region")
|
||||
}
|
||||
results, err := modules.Elasticips.List(s, params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
printList(results, modules.Elasticips.GetColumns(s))
|
||||
return nil
|
||||
})
|
||||
|
||||
type EipCreateOptions struct {
|
||||
MANAGER string `help:"cloud provider"`
|
||||
REGION string `help:"cloud region in which EIP is allocated"`
|
||||
NAME string `help:"name of the EIP"`
|
||||
BW int `help:"Bandwidth in Mbps"`
|
||||
ChargeType string `help:"bandwidth charge type, either traffic or bandwidth" choices:"traffic|bandwidth"`
|
||||
}
|
||||
R(&EipCreateOptions{}, "eip-create", "Create an EIP", func(s *mcclient.ClientSession, args *EipCreateOptions) error {
|
||||
params := jsonutils.NewDict()
|
||||
params.Add(jsonutils.NewString(args.MANAGER), "manager")
|
||||
params.Add(jsonutils.NewString(args.REGION), "region")
|
||||
params.Add(jsonutils.NewString(args.NAME), "name")
|
||||
params.Add(jsonutils.NewInt(int64(args.BW)), "bandwidth")
|
||||
|
||||
if len(args.ChargeType) > 0 {
|
||||
params.Add(jsonutils.NewString(args.ChargeType), "charge_type")
|
||||
}
|
||||
|
||||
result, err := modules.Elasticips.Create(s, params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
printObject(result)
|
||||
return nil
|
||||
})
|
||||
|
||||
type EipDeleteOptions struct {
|
||||
ID string `help:"ID or name of EIP"`
|
||||
}
|
||||
R(&EipDeleteOptions{}, "eip-delete", "Delete an EIP", func(s *mcclient.ClientSession, args *EipDeleteOptions) error {
|
||||
result, err := modules.Elasticips.Delete(s, args.ID, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
printObject(result)
|
||||
return nil
|
||||
})
|
||||
|
||||
type EipUpdateOptions struct {
|
||||
ID string `help:"ID or name of EIP"`
|
||||
Name string `help:"New name of EIP"`
|
||||
Desc string `help:"New description of EIP"`
|
||||
}
|
||||
R(&EipUpdateOptions{}, "eip-update", "Update EIP properties", func(s *mcclient.ClientSession, args *EipUpdateOptions) error {
|
||||
params := jsonutils.NewDict()
|
||||
if len(args.Name) > 0 {
|
||||
params.Add(jsonutils.NewString(args.Name), "name")
|
||||
}
|
||||
if len(args.Desc) > 0 {
|
||||
params.Add(jsonutils.NewString(args.Desc), "description")
|
||||
}
|
||||
result, err := modules.Elasticips.Update(s, args.ID, params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
printObject(result)
|
||||
return nil
|
||||
})
|
||||
|
||||
type EipAssociateOptions struct {
|
||||
ID string `help:"ID or name of EIP"`
|
||||
INSTANCEID string `help:"ID of instance the eip associated with"`
|
||||
InstanceType string `default:"server" help:"Instance type that the eip associated with, default is server" choices:"server"`
|
||||
}
|
||||
R(&EipAssociateOptions{}, "eip-associate", "Associate an EIP to an instance", func(s *mcclient.ClientSession, args *EipAssociateOptions) error {
|
||||
params := jsonutils.NewDict()
|
||||
params.Add(jsonutils.NewString(args.InstanceType), "instance_type")
|
||||
params.Add(jsonutils.NewString(args.INSTANCEID), "instance_id")
|
||||
result, err := modules.Elasticips.PerformAction(s, args.ID, "associate", params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
printObject(result)
|
||||
return nil
|
||||
})
|
||||
|
||||
type EipSingleOptions struct {
|
||||
ID string `help:"ID or name of EIP"`
|
||||
}
|
||||
R(&EipSingleOptions{}, "eip-dissociate", "Dissociate an EIP from an instance", func(s *mcclient.ClientSession, args *EipSingleOptions) error {
|
||||
result, err := modules.Elasticips.PerformAction(s, args.ID, "dissociate", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
printObject(result)
|
||||
return nil
|
||||
})
|
||||
|
||||
R(&EipSingleOptions{}, "eip-sync", "Synchronize status of an EIP", func(s *mcclient.ClientSession, args *EipSingleOptions) error {
|
||||
result, err := modules.Elasticips.PerformAction(s, args.ID, "sync", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
printObject(result)
|
||||
return nil
|
||||
})
|
||||
|
||||
type ServerCreateEipOptions struct {
|
||||
ID string `help:"server ID or name"`
|
||||
BW int `help:"EIP bandwidth in Mbps"`
|
||||
ChargeType string `help:"bandwidth charge type, either traffic or bandwidth" choices:"traffic|bandwidth"`
|
||||
}
|
||||
R(&ServerCreateEipOptions{}, "server-create-eip", "allocate an EIP and associate EIP to server", func(s *mcclient.ClientSession, args *ServerCreateEipOptions) error {
|
||||
params := jsonutils.NewDict()
|
||||
params.Add(jsonutils.NewInt(int64(args.BW)), "bandwidth")
|
||||
|
||||
if len(args.ChargeType) > 0 {
|
||||
params.Add(jsonutils.NewString(args.ChargeType), "charge_type")
|
||||
}
|
||||
|
||||
result, err := modules.Servers.PerformAction(s, args.ID, "create-eip", params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
printObject(result)
|
||||
return nil
|
||||
})
|
||||
|
||||
type EipShowOptions struct {
|
||||
ID string `help:"ID or name of EIP"`
|
||||
}
|
||||
R(&EipShowOptions{}, "eip-show", "show details of an EIP", func(s *mcclient.ClientSession, args *EipShowOptions) error {
|
||||
result, err := modules.Servers.Get(s, args.ID, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
printObject(result)
|
||||
return nil
|
||||
})
|
||||
|
||||
type EipChangeBandwidthOptions struct {
|
||||
ID string `help:"ID or name of the EIP"`
|
||||
BW int `help:"new bandwidth of EIP"`
|
||||
}
|
||||
R(&EipChangeBandwidthOptions{}, "eip-change-bandwidth", "Change maximal bandwidth of EIP", func(s *mcclient.ClientSession, args *EipChangeBandwidthOptions) error {
|
||||
params := jsonutils.NewDict()
|
||||
params.Add(jsonutils.NewInt(int64(args.BW)), "bandwidth")
|
||||
result, err := modules.Elasticips.PerformAction(s, args.ID, "change-bandwidth", params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
printObject(result)
|
||||
return nil
|
||||
})
|
||||
|
||||
}
|
||||
@@ -3,6 +3,8 @@ package k8s
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"yunion.io/x/jsonutils"
|
||||
|
||||
"yunion.io/x/onecloud/pkg/mcclient"
|
||||
"yunion.io/x/onecloud/pkg/mcclient/modules/k8s"
|
||||
)
|
||||
@@ -28,6 +30,23 @@ func initPod() {
|
||||
return nil
|
||||
})
|
||||
|
||||
type getOpt struct {
|
||||
resourceGetOptions
|
||||
}
|
||||
R(&getOpt{}, cmdN("show"), "Get pod details", func(s *mcclient.ClientSession, args *getOpt) error {
|
||||
id := args.NAME
|
||||
params := args.ClusterParams()
|
||||
if args.Namespace != "" {
|
||||
params.Add(jsonutils.NewString(args.Namespace), "namespace")
|
||||
}
|
||||
ret, err := k8s.Pods.Get(s, id, params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
printObjectYAML(ret)
|
||||
return nil
|
||||
})
|
||||
|
||||
type deleteOpt struct {
|
||||
resourceGetOptions
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package shell
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
|
||||
"yunion.io/x/jsonutils"
|
||||
|
||||
"yunion.io/x/onecloud/pkg/mcclient"
|
||||
"yunion.io/x/onecloud/pkg/mcclient/modules"
|
||||
o "yunion.io/x/onecloud/pkg/mcclient/options"
|
||||
)
|
||||
|
||||
func init() {
|
||||
handleResult := func(opt o.WebConsoleFrontendOptions, obj jsonutils.JSONObject) error {
|
||||
if opt.WebUrl == "" {
|
||||
printObject(obj)
|
||||
return nil
|
||||
}
|
||||
u, err := url.Parse(opt.WebUrl)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
connParams, err := obj.GetString("connect_params")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
u.Path = "index.html"
|
||||
u.RawQuery = connParams
|
||||
fmt.Println(u.String())
|
||||
return nil
|
||||
}
|
||||
|
||||
R(&o.PodShellOptions{}, "webconsole-k8s-pod", "Show TTY console of given pod", func(s *mcclient.ClientSession, args *o.PodShellOptions) error {
|
||||
params, err := args.Params()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ret, err := modules.WebConsole.DoK8sShellConnect(s, args.NAME, params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
handleResult(args.WebConsoleFrontendOptions, ret)
|
||||
return nil
|
||||
})
|
||||
|
||||
R(&o.PodLogOptoins{}, "webconsole-k8s-pod-log", "Get logs of given pod", func(s *mcclient.ClientSession, args *o.PodLogOptoins) error {
|
||||
params, err := args.Params()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ret, err := modules.WebConsole.DoK8sLogConnect(s, args.NAME, params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
handleResult(args.WebConsoleFrontendOptions, ret)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"yunion.io/x/onecloud/pkg/webconsole/service"
|
||||
)
|
||||
|
||||
func main() {
|
||||
service.StartService()
|
||||
}
|
||||
@@ -133,6 +133,8 @@ const (
|
||||
ACT_GUEST_ATTACH_ISOLATED_DEVICE_FAIL = "guest_attach_isolated_deivce_fail"
|
||||
ACT_GUEST_DETACH_ISOLATED_DEVICE = "guest_detach_isolated_deivce"
|
||||
ACT_GUEST_DETACH_ISOLATED_DEVICE_FAIL = "guest_detach_isolated_deivce_fail"
|
||||
|
||||
ACT_CHANGE_BANDWIDTH = "eip_change_bandwidth"
|
||||
)
|
||||
|
||||
type SOpsLogManager struct {
|
||||
|
||||
@@ -29,6 +29,7 @@ type ICloudRegion interface {
|
||||
|
||||
GetIZones() ([]ICloudZone, error)
|
||||
GetIVpcs() ([]ICloudVpc, error)
|
||||
GetIEips() ([]ICloudEIP, error)
|
||||
|
||||
GetIZoneById(id string) (ICloudZone, error)
|
||||
GetIVpcById(id string) (ICloudVpc, error)
|
||||
@@ -38,6 +39,10 @@ type ICloudRegion interface {
|
||||
|
||||
CreateIVpc(name string, desc string, cidr string) (ICloudVpc, error)
|
||||
|
||||
CreateEIP(bwMbps int) (ICloudEIP, error)
|
||||
|
||||
GetIEipById(id string) (ICloudEIP, error)
|
||||
|
||||
GetProvider() string
|
||||
}
|
||||
|
||||
@@ -134,7 +139,7 @@ type ICloudVM interface {
|
||||
GetIDisks() ([]ICloudDisk, error)
|
||||
GetINics() ([]ICloudNic, error)
|
||||
|
||||
GetEIP() ICloudEIP
|
||||
GetIEIP() (ICloudEIP, error)
|
||||
|
||||
// GetStatus() string
|
||||
// GetRemoteStatus() string
|
||||
@@ -175,9 +180,25 @@ type ICloudNic interface {
|
||||
}
|
||||
|
||||
type ICloudEIP interface {
|
||||
GetIP() string
|
||||
GetAllocationId() string
|
||||
GetChargeType() string
|
||||
ICloudResource
|
||||
|
||||
GetIpAddr() string
|
||||
GetMode() string
|
||||
GetAssociationType() string
|
||||
GetAssociationExternalId() string
|
||||
|
||||
GetBandwidth() int
|
||||
|
||||
GetInternetChargeType() string
|
||||
|
||||
GetManagerId() string
|
||||
|
||||
Delete() error
|
||||
|
||||
Associate(instanceId string) error
|
||||
Dissociate() error
|
||||
|
||||
ChangeBandwidth(bw int) error
|
||||
}
|
||||
|
||||
type ICloudSecurityGroup interface {
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
package cloudprovider
|
||||
|
||||
import "time"
|
||||
import (
|
||||
"time"
|
||||
|
||||
"yunion.io/x/log"
|
||||
)
|
||||
|
||||
func WaitStatus(res ICloudResource, expect string, interval time.Duration, timeout time.Duration) error {
|
||||
startTime := time.Now()
|
||||
@@ -9,6 +13,7 @@ func WaitStatus(res ICloudResource, expect string, interval time.Duration, timeo
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Debugf("status %s expect %s", res.GetStatus(), expect)
|
||||
if res.GetStatus() == expect {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -3,10 +3,8 @@ package guestdrivers
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"yunion.io/x/log"
|
||||
"yunion.io/x/onecloud/pkg/cloudprovider"
|
||||
"yunion.io/x/onecloud/pkg/util/seclib2"
|
||||
"yunion.io/x/pkg/utils"
|
||||
|
||||
@@ -28,6 +26,31 @@ func (self *SAzureGuestDriver) GetHypervisor() string {
|
||||
return models.HYPERVISOR_AZURE
|
||||
}
|
||||
|
||||
func (self *SAzureGuestDriver) ChooseHostStorage(host *models.SHost, backend string) *models.SStorage {
|
||||
storages := host.GetAttachedStorages()
|
||||
for i := 0; i < len(storages); i += 1 {
|
||||
if storages[i].StorageType == backend {
|
||||
return &storages[i]
|
||||
}
|
||||
}
|
||||
for _, stype := range []string{"standard_lrs", "premium_lrs"} {
|
||||
for i := 0; i < len(storages); i += 1 {
|
||||
if storages[i].StorageType == stype {
|
||||
return &storages[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SAzureGuestDriver) GetDetachDiskStatus() ([]string, error) {
|
||||
return []string{models.VM_READY, models.VM_RUNNING}, nil
|
||||
}
|
||||
|
||||
func (self *SAzureGuestDriver) RequestDetachDisk(ctx context.Context, guest *models.SGuest, task taskman.ITask) error {
|
||||
return guest.StartSyncTask(ctx, task.GetUserCred(), false, task.GetTaskId())
|
||||
}
|
||||
|
||||
func (self *SAzureGuestDriver) RequestSyncConfigOnHost(ctx context.Context, guest *models.SGuest, host *models.SHost, task taskman.ITask) error {
|
||||
return fmt.Errorf("Not Implement")
|
||||
}
|
||||
@@ -48,6 +71,48 @@ type SAzureVMCreateConfig struct {
|
||||
PublicKey string
|
||||
}
|
||||
|
||||
func (self *SAzureGuestDriver) GetJsonDescAtHost(ctx context.Context, guest *models.SGuest, host *models.SHost) jsonutils.JSONObject {
|
||||
config := SAzureVMCreateConfig{}
|
||||
config.Name = guest.Name
|
||||
config.Cpu = int(guest.VcpuCount)
|
||||
config.Memory = guest.VmemSize
|
||||
config.Description = guest.Description
|
||||
|
||||
if len(guest.KeypairId) > 0 {
|
||||
config.PublicKey = guest.GetKeypairPublicKey()
|
||||
}
|
||||
|
||||
nics := guest.GetNetworks()
|
||||
net := nics[0].GetNetwork()
|
||||
config.ExternalNetworkId = net.ExternalId
|
||||
config.IpAddr = nics[0].IpAddr
|
||||
|
||||
disks := guest.GetDisks()
|
||||
config.DataDisks = make([]int, len(disks)-1)
|
||||
|
||||
for i := 0; i < len(disks); i += 1 {
|
||||
disk := disks[i].GetDisk()
|
||||
if i == 0 {
|
||||
log.Debugf("disk: %v", disk)
|
||||
storage := disk.GetStorage()
|
||||
log.Debugf("disk storage: %v", storage)
|
||||
config.StorageType = storage.StorageType
|
||||
cache := storage.GetStoragecache()
|
||||
imageId := disk.GetTemplateId()
|
||||
scimg := models.StoragecachedimageManager.GetStoragecachedimage(cache.Id, imageId)
|
||||
config.ExternalImageId = scimg.ExternalId
|
||||
img := scimg.GetCachedimage()
|
||||
config.OsDistribution, _ = img.Info.GetString("properties", "os_distribution")
|
||||
config.OsVersion, _ = img.Info.GetString("properties", "os_version")
|
||||
|
||||
config.SysDiskSize = disk.DiskSize / 1024 // MB => GB
|
||||
} else {
|
||||
config.DataDisks[i-1] = disk.DiskSize / 1024 // MB => GB
|
||||
}
|
||||
}
|
||||
return jsonutils.Marshal(&config)
|
||||
}
|
||||
|
||||
func (self *SAzureGuestDriver) RequestDeployGuestOnHost(ctx context.Context, guest *models.SGuest, host *models.SHost, task taskman.ITask) error {
|
||||
config := guest.GetDeployConfigOnHost(ctx, host, task.GetParams())
|
||||
|
||||
@@ -70,10 +135,6 @@ func (self *SAzureGuestDriver) RequestDeployGuestOnHost(ctx context.Context, gue
|
||||
} else {
|
||||
log.Debugf("VMcreated %s, wait status ready ...", iVM.GetGlobalId())
|
||||
|
||||
if err := cloudprovider.WaitStatus(iVM, models.VM_READY, time.Second*5, time.Second*1800); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if iVM, err = ihost.GetIVMById(iVM.GetGlobalId()); err != nil {
|
||||
log.Errorf("cannot find vm %s", err)
|
||||
return nil, err
|
||||
|
||||
@@ -2,9 +2,9 @@ package compute
|
||||
|
||||
import (
|
||||
"yunion.io/x/log"
|
||||
|
||||
"yunion.io/x/onecloud/pkg/appsrv"
|
||||
"yunion.io/x/onecloud/pkg/appsrv/dispatcher"
|
||||
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon/db"
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon/db/quotas"
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
|
||||
@@ -56,6 +56,7 @@ func InitHandlers(app *appsrv.Application) {
|
||||
models.SecurityGroupRuleManager,
|
||||
models.VCenterManager,
|
||||
models.DnsRecordManager,
|
||||
models.ElasticipManager,
|
||||
} {
|
||||
db.RegisterModelManager(manager)
|
||||
handler := db.NewModelHandler(manager)
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"yunion.io/x/jsonutils"
|
||||
"yunion.io/x/log"
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
|
||||
"yunion.io/x/onecloud/pkg/cloudprovider"
|
||||
"yunion.io/x/onecloud/pkg/compute/models"
|
||||
"yunion.io/x/onecloud/pkg/httperrors"
|
||||
)
|
||||
@@ -140,16 +141,19 @@ func (self *SAliyunHostDriver) RequestAllocateDiskOnStorage(ctx context.Context,
|
||||
}
|
||||
|
||||
func (self *SAliyunHostDriver) RequestDeallocateDiskOnHost(host *models.SHost, storage *models.SStorage, disk *models.SDisk, task taskman.ITask) error {
|
||||
data := jsonutils.NewDict()
|
||||
if iCloudStorage, err := storage.GetIStorage(); err != nil {
|
||||
return err
|
||||
} else if iDisk, err := iCloudStorage.GetIDisk(disk.GetExternalId()); err != nil {
|
||||
if err == cloudprovider.ErrNotFound {
|
||||
task.ScheduleRun(data)
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
} else if err := iDisk.Delete(); err != nil {
|
||||
return err
|
||||
} else {
|
||||
data := jsonutils.NewDict()
|
||||
task.ScheduleRun(data)
|
||||
}
|
||||
task.ScheduleRun(data)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -87,6 +87,10 @@ func (self *SCloudprovider) getStoragecacheCount() int {
|
||||
return StoragecacheManager.Query().Equals("manager_id", self.Id).Count()
|
||||
}
|
||||
|
||||
func (self *SCloudprovider) getEipCount() int {
|
||||
return ElasticipManager.Query().Equals("manager_id", self.Id).Count()
|
||||
}
|
||||
|
||||
func (self *SCloudprovider) ValidateUpdateData(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data *jsonutils.JSONDict) (*jsonutils.JSONDict, error) {
|
||||
return self.SEnabledStatusStandaloneResourceBase.ValidateUpdateData(ctx, userCred, query, data)
|
||||
}
|
||||
@@ -384,7 +388,9 @@ func (manager *SCloudproviderManager) FetchCloudproviderById(providerId string)
|
||||
func (manager *SCloudproviderManager) FetchCloudproviderByIdOrName(providerId string) *SCloudprovider {
|
||||
providerObj, err := manager.FetchByIdOrName("", providerId)
|
||||
if err != nil {
|
||||
log.Errorf("%s", err)
|
||||
if err != sql.ErrNoRows {
|
||||
log.Errorf("%s", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return providerObj.(*SCloudprovider)
|
||||
@@ -395,6 +401,7 @@ type SCloudproviderUsage struct {
|
||||
VpcCount int
|
||||
StorageCount int
|
||||
StorageCacheCount int
|
||||
EipCount int
|
||||
}
|
||||
|
||||
func (usage *SCloudproviderUsage) isEmpty() bool {
|
||||
@@ -410,6 +417,9 @@ func (usage *SCloudproviderUsage) isEmpty() bool {
|
||||
if usage.StorageCacheCount > 0 {
|
||||
return false
|
||||
}
|
||||
if usage.EipCount > 0 {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -419,6 +429,7 @@ func (self *SCloudprovider) getUsage() *SCloudproviderUsage {
|
||||
usage.VpcCount = self.getVpcCount()
|
||||
usage.StorageCount = self.getStorageCount()
|
||||
usage.StorageCacheCount = self.getStoragecacheCount()
|
||||
usage.EipCount = self.getEipCount()
|
||||
|
||||
return &usage
|
||||
}
|
||||
|
||||
@@ -757,6 +757,7 @@ func parseDiskInfo(ctx context.Context, userCred mcclient.TokenCredential, info
|
||||
return nil, err
|
||||
}
|
||||
parts := strings.Split(diskStr, ":")
|
||||
log.Debugf("diskStr: %s parts: %s", diskStr, parts)
|
||||
for _, p := range parts {
|
||||
if regutils.MatchSize(p) {
|
||||
diskConfig.Size, _ = fileutils.GetSizeMb(p, 'M', 1024)
|
||||
|
||||
@@ -0,0 +1,750 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
"yunion.io/x/pkg/util/compare"
|
||||
"yunion.io/x/pkg/utils"
|
||||
"yunion.io/x/pkg/tristate"
|
||||
"yunion.io/x/log"
|
||||
"yunion.io/x/jsonutils"
|
||||
"yunion.io/x/sqlchemy"
|
||||
|
||||
"yunion.io/x/onecloud/pkg/mcclient"
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon/db"
|
||||
"yunion.io/x/onecloud/pkg/cloudprovider"
|
||||
"yunion.io/x/onecloud/pkg/httperrors"
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon/db/quotas"
|
||||
)
|
||||
|
||||
const (
|
||||
EIP_MODE_INSTANCE_PUBLICIP = "public_ip"
|
||||
EIP_MODE_STANDALONE_EIP = "elastic_ip"
|
||||
|
||||
EIP_ASSOCIATE_TYPE_SERVER = "server"
|
||||
|
||||
EIP_STATUS_READY = "ready"
|
||||
EIP_STATUS_UNKNOWN = "unknown"
|
||||
EIP_STATUS_ALLOCATE = "allocate"
|
||||
EIP_STATUS_ALLOCATE_FAIL = "allocate_fail"
|
||||
EIP_STATUS_DEALLOCATE = "deallocate"
|
||||
EIP_STATUS_DEALLOCATE_FAIL = "deallocate_fail"
|
||||
EIP_STATUS_ASSOCIATE = "associate"
|
||||
EIP_STATUS_ASSOCIATE_FAIL = "associate_fail"
|
||||
EIP_STATUS_DISSOCIATE = "dissociate"
|
||||
EIP_STATUS_DISSOCIATE_FAIL = "dissociate_fail"
|
||||
|
||||
EIP_CHARGE_TYPE_BY_TRAFFIC = "traffic"
|
||||
EIP_CHARGE_TYPE_BY_BANDWIDTH = "bandwidth"
|
||||
EIP_CHARGE_TYPE_DEFAULT = EIP_CHARGE_TYPE_BY_TRAFFIC
|
||||
)
|
||||
|
||||
type SElasticipManager struct {
|
||||
db.SVirtualResourceBaseManager
|
||||
}
|
||||
|
||||
var ElasticipManager *SElasticipManager
|
||||
|
||||
func init() {
|
||||
ElasticipManager = &SElasticipManager{SVirtualResourceBaseManager: db.NewVirtualResourceBaseManager(SElasticip{}, "elasticips_tbl", "eip", "eips")}
|
||||
}
|
||||
|
||||
type SElasticip struct {
|
||||
db.SVirtualResourceBase
|
||||
|
||||
SManagedResourceBase
|
||||
|
||||
Mode string `width:"32" charset:"ascii" list:"user"`
|
||||
|
||||
IpAddr string `width:"17" charset:"ascii" list:"user"`
|
||||
|
||||
AssociateType string `width:"32" charset:"ascii" list:"user"`
|
||||
AssociateId string `width:"128" charset:"ascii" list:"user"`
|
||||
|
||||
Bandwidth int `list:"user" create:"required"`
|
||||
|
||||
ChargeType string `list:"user" create:"required" default:"traffic"`
|
||||
|
||||
AutoDellocate tristate.TriState `default:"false" get:"user" create:"optional"`
|
||||
|
||||
CloudregionId string `width:"36" charset:"ascii" nullable:"false" list:"user" create:"required"`
|
||||
}
|
||||
|
||||
|
||||
func (manager *SElasticipManager) ListItemFilter(ctx context.Context, q *sqlchemy.SQuery, userCred mcclient.TokenCredential, query jsonutils.JSONObject) (*sqlchemy.SQuery, error) {
|
||||
q, err := manager.SVirtualResourceBaseManager.ListItemFilter(ctx, q, userCred, query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
managerFilter, _ := query.GetString("manager")
|
||||
if len(managerFilter) > 0 {
|
||||
managerI, err := CloudproviderManager.FetchByIdOrName(userCred.GetProjectId(), managerFilter)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, httperrors.NewResourceNotFoundError("cloud provider %s not found", managerFilter)
|
||||
} else {
|
||||
return nil, httperrors.NewGeneralError(err)
|
||||
}
|
||||
}
|
||||
q = q.Equals("manager_id", managerI.GetId())
|
||||
}
|
||||
|
||||
regionFilter, _ := query.GetString("region")
|
||||
if len(regionFilter) > 0 {
|
||||
regionObj, err := CloudregionManager.FetchByIdOrName(userCred.GetProjectId(), regionFilter)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, httperrors.NewResourceNotFoundError("cloud region %s not found", regionFilter)
|
||||
} else {
|
||||
return nil, httperrors.NewGeneralError(err)
|
||||
}
|
||||
}
|
||||
q = q.Equals("cloudregion_id", regionObj.GetId())
|
||||
}
|
||||
|
||||
return q, nil
|
||||
}
|
||||
|
||||
func (manager *SElasticipManager) getEipsByRegion(region *SCloudregion, provider *SCloudprovider) ([]SElasticip, error) {
|
||||
eips := make([]SElasticip, 0)
|
||||
q := manager.Query().Equals("cloudregion_id", region.Id)
|
||||
if provider != nil {
|
||||
q = q.Equals("manager_id", provider.Id)
|
||||
}
|
||||
err := db.FetchModelObjects(manager, q, &eips)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return eips, nil
|
||||
}
|
||||
|
||||
func (self *SElasticip) GetRegion() *SCloudregion {
|
||||
return CloudregionManager.FetchRegionById(self.CloudregionId)
|
||||
}
|
||||
|
||||
func (manager *SElasticipManager) SyncEips(ctx context.Context, userCred mcclient.TokenCredential, provider *SCloudprovider, region *SCloudregion, eips []cloudprovider.ICloudEIP) (compare.SyncResult) {
|
||||
// localEips := make([]SElasticip, 0)
|
||||
// remoteEips := make([]cloudprovider.ICloudEIP, 0)
|
||||
syncResult := compare.SyncResult{}
|
||||
|
||||
dbEips, err := manager.getEipsByRegion(region, provider)
|
||||
if err != nil {
|
||||
syncResult.Error(err)
|
||||
return syncResult
|
||||
}
|
||||
|
||||
removed := make([]SElasticip, 0)
|
||||
commondb := make([]SElasticip, 0)
|
||||
commonext := make([]cloudprovider.ICloudEIP, 0)
|
||||
added := make([]cloudprovider.ICloudEIP, 0)
|
||||
|
||||
err = compare.CompareSets(dbEips, eips, &removed, &commondb, &commonext, &added)
|
||||
if err != nil {
|
||||
syncResult.Error(err)
|
||||
return syncResult
|
||||
}
|
||||
|
||||
for i := 0; i < len(removed); i += 1 {
|
||||
err = removed[i].SetStatus(userCred, EIP_STATUS_UNKNOWN, "sync to delete")
|
||||
if err != nil {
|
||||
syncResult.DeleteError(err)
|
||||
} else {
|
||||
syncResult.Delete()
|
||||
}
|
||||
}
|
||||
for i := 0; i < len(commondb); i += 1 {
|
||||
err = commondb[i].SyncWithCloudEip(userCred, commonext[i])
|
||||
if err != nil {
|
||||
syncResult.UpdateError(err)
|
||||
} else {
|
||||
syncResult.Update()
|
||||
}
|
||||
}
|
||||
for i := 0; i < len(added); i += 1 {
|
||||
_, err := manager.newFromCloudEip(userCred, added[i], region)
|
||||
if err != nil {
|
||||
syncResult.AddError(err)
|
||||
} else {
|
||||
syncResult.Add()
|
||||
}
|
||||
}
|
||||
|
||||
return syncResult
|
||||
}
|
||||
|
||||
func (self *SElasticip) SyncInstanceWithCloudEip(ctx context.Context, userCred mcclient.TokenCredential, ext cloudprovider.ICloudEIP) error {
|
||||
vm := self.getVM()
|
||||
vmExtId := ext.GetAssociationExternalId()
|
||||
|
||||
if vm == nil && len(vmExtId) == 0 {
|
||||
return nil
|
||||
}
|
||||
if vm != nil && vm.ExternalId == vmExtId {
|
||||
return nil
|
||||
}
|
||||
|
||||
if vm != nil { // dissociate
|
||||
err := self.Dissociate(ctx, userCred)
|
||||
if err != nil {
|
||||
log.Errorf("fail to dissociate vm: %s", err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if len(vmExtId) > 0 {
|
||||
newVM, err := GuestManager.FetchByExternalId(vmExtId)
|
||||
if err != nil {
|
||||
log.Errorf("fail to find vm by external ID %s", vmExtId)
|
||||
return err
|
||||
}
|
||||
err = self.AssociateVM(userCred, newVM.(*SGuest))
|
||||
if err != nil {
|
||||
log.Errorf("fail to associate with new vm %s", err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SElasticip) SyncWithCloudEip(userCred mcclient.TokenCredential, ext cloudprovider.ICloudEIP) error {
|
||||
_, err := self.GetModelManager().TableSpec().Update(self, func() error {
|
||||
|
||||
// self.Name = ext.GetName()
|
||||
self.Bandwidth = ext.GetBandwidth()
|
||||
self.IpAddr = ext.GetIpAddr()
|
||||
self.Mode = ext.GetMode()
|
||||
self.Status = ext.GetStatus()
|
||||
self.ExternalId = ext.GetGlobalId()
|
||||
// self.ManagerId = ext.GetManagerId()
|
||||
self.IsEmulated = ext.IsEmulated()
|
||||
// self.ProjectId = userCred.GetProjectId()
|
||||
self.ChargeType = ext.GetInternetChargeType()
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorf("SyncWithCloudEip fail %s", err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (manager *SElasticipManager) newFromCloudEip(userCred mcclient.TokenCredential, extEip cloudprovider.ICloudEIP, region *SCloudregion) (*SElasticip, error) {
|
||||
eip := SElasticip{}
|
||||
eip.SetModelManager(manager)
|
||||
|
||||
eip.Name = extEip.GetName()
|
||||
eip.Status = extEip.GetStatus()
|
||||
eip.ExternalId = extEip.GetGlobalId()
|
||||
eip.IpAddr = extEip.GetIpAddr()
|
||||
eip.Mode = extEip.GetMode()
|
||||
eip.IsEmulated = extEip.IsEmulated()
|
||||
eip.ManagerId = extEip.GetManagerId()
|
||||
eip.CloudregionId = region.Id
|
||||
eip.ChargeType = extEip.GetInternetChargeType()
|
||||
|
||||
eip.ProjectId = userCred.GetProjectId()
|
||||
|
||||
err := manager.TableSpec().Insert(&eip)
|
||||
if err != nil {
|
||||
log.Errorf("newFromCloudEip fail %s", err)
|
||||
return nil, err
|
||||
}
|
||||
return &eip, nil
|
||||
}
|
||||
|
||||
func (manager *SElasticipManager) getEipForInstance(instanceType string, instanceId string) (*SElasticip, error) {
|
||||
eip := SElasticip{}
|
||||
|
||||
q := manager.Query()
|
||||
q = q.Equals("associate_type", instanceType)
|
||||
q = q.Equals("associate_id", instanceId)
|
||||
|
||||
err := q.First(&eip)
|
||||
|
||||
if err != nil {
|
||||
if err != sql.ErrNoRows {
|
||||
log.Errorf("getEipForInstance query fail %s", err)
|
||||
return nil, err
|
||||
} else {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
eip.SetModelManager(manager)
|
||||
|
||||
return &eip, nil
|
||||
}
|
||||
|
||||
func (self *SElasticip) getVM() *SGuest {
|
||||
if self.AssociateType == "server" && len(self.AssociateId) > 0 {
|
||||
return GuestManager.FetchGuestById(self.AssociateId)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SElasticip) Dissociate(ctx context.Context, userCred mcclient.TokenCredential) error {
|
||||
if len(self.AssociateType) == 0 {
|
||||
return nil
|
||||
}
|
||||
vm := self.getVM()
|
||||
if vm == nil {
|
||||
log.Errorf("dissociate VM not exists???")
|
||||
}
|
||||
_, err := self.GetModelManager().TableSpec().Update(self, func() error {
|
||||
self.AssociateId = ""
|
||||
self.AssociateType = ""
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if vm != nil {
|
||||
db.OpsLog.LogEvent(self, db.ACT_EIP_DETACH, vm.GetShortDesc(), userCred)
|
||||
}
|
||||
if self.Mode == EIP_MODE_INSTANCE_PUBLICIP {
|
||||
self.Delete(ctx, userCred)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SElasticip) AssociateVM(userCred mcclient.TokenCredential, vm *SGuest) error {
|
||||
if len(self.AssociateType) > 0 {
|
||||
return fmt.Errorf("EIP has been associated!!")
|
||||
}
|
||||
_, err := self.GetModelManager().TableSpec().Update(self, func() error {
|
||||
self.AssociateType = "server"
|
||||
self.AssociateId = vm.Id
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
db.OpsLog.LogEvent(self, db.ACT_EIP_ATTACH, vm.GetShortDesc(), userCred)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (manager *SElasticipManager) getEipByExtEip(userCred mcclient.TokenCredential, extEip cloudprovider.ICloudEIP, region *SCloudregion) (*SElasticip, error) {
|
||||
eipObj, err := manager.FetchByExternalId(extEip.GetGlobalId())
|
||||
if err == nil {
|
||||
return eipObj.(*SElasticip), nil
|
||||
}
|
||||
if err != sql.ErrNoRows {
|
||||
log.Errorf("FetchByExternalId fail %s", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return manager.newFromCloudEip(userCred, extEip, region)
|
||||
}
|
||||
|
||||
func (manager *SElasticipManager) ValidateCreateData(ctx context.Context, userCred mcclient.TokenCredential, ownerProjId string, query jsonutils.JSONObject, data *jsonutils.JSONDict) (*jsonutils.JSONDict, error) {
|
||||
regionStr := jsonutils.GetAnyString(data, []string {"region", "region_id"})
|
||||
if len(regionStr) == 0 {
|
||||
return nil, httperrors.NewInputParameterError("Missing region/region_id")
|
||||
}
|
||||
region, err := CloudregionManager.FetchByIdOrName("", regionStr)
|
||||
if err != nil {
|
||||
if err != sql.ErrNoRows {
|
||||
return nil, httperrors.NewGeneralError(err)
|
||||
} else {
|
||||
return nil, httperrors.NewResourceNotFoundError("Region %s not found", regionStr)
|
||||
}
|
||||
}
|
||||
data.Add(jsonutils.NewString(region.GetId()), "cloudregion_id")
|
||||
|
||||
managerStr := jsonutils.GetAnyString(data, []string{"manager", "manager_id"})
|
||||
if len(managerStr) == 0 {
|
||||
return nil, httperrors.NewInputParameterError("Missing manager/manager_id")
|
||||
}
|
||||
|
||||
provider, err := CloudproviderManager.FetchByIdOrName("", managerStr)
|
||||
if err != nil {
|
||||
if err != sql.ErrNoRows {
|
||||
return nil, httperrors.NewGeneralError(err)
|
||||
} else {
|
||||
return nil, httperrors.NewResourceNotFoundError("Cloud provider %s not found", managerStr)
|
||||
}
|
||||
}
|
||||
data.Add(jsonutils.NewString(provider.GetId()), "manager_id")
|
||||
|
||||
chargeType := jsonutils.GetAnyString(data, []string{"charge_type"})
|
||||
if len(chargeType) == 0 {
|
||||
chargeType = EIP_CHARGE_TYPE_DEFAULT
|
||||
}
|
||||
|
||||
if ! utils.IsInStringArray(chargeType, []string{EIP_CHARGE_TYPE_BY_BANDWIDTH, EIP_CHARGE_TYPE_BY_TRAFFIC}) {
|
||||
return nil, httperrors.NewInputParameterError("charge type %s not supported", chargeType)
|
||||
}
|
||||
|
||||
data.Add(jsonutils.NewString(chargeType), "charge_type")
|
||||
|
||||
eipPendingUsage := &SQuota{Eip: 1}
|
||||
err = QuotaManager.CheckSetPendingQuota(ctx, userCred, userCred.GetProjectId(), eipPendingUsage)
|
||||
if err != nil {
|
||||
return nil, httperrors.NewOutOfQuotaError("Out of eip quota: %s", err)
|
||||
}
|
||||
|
||||
data, err = manager.SVirtualResourceBaseManager.ValidateCreateData(ctx, userCred, ownerProjId, query, data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (self *SElasticip) PostCreate(ctx context.Context, userCred mcclient.TokenCredential, ownerProjId string, query jsonutils.JSONObject, data jsonutils.JSONObject) {
|
||||
self.SVirtualResourceBase.PostCreate(ctx, userCred, ownerProjId, query, data)
|
||||
eipPendingUsage := &SQuota{Eip: 1}
|
||||
self.startEipAllocateTask(ctx, userCred, nil, eipPendingUsage)
|
||||
}
|
||||
|
||||
func (self *SElasticip) startEipAllocateTask(ctx context.Context, userCred mcclient.TokenCredential, params *jsonutils.JSONDict, pendingUsage quotas.IQuota) error {
|
||||
/*params := jsonutils.NewDict()
|
||||
params.Add(jsonutils.NewString(instanceExtId), "instance_external_id")
|
||||
params.Add(jsonutils.NewString(instanceId), "instance_id")
|
||||
params.Add(jsonutils.NewString(instanceType), "instance_type")
|
||||
*/
|
||||
|
||||
task, err := taskman.TaskManager.NewTask(ctx, "EipAllocateTask", self, userCred, params, "", "", pendingUsage)
|
||||
if err != nil {
|
||||
log.Errorf("newtask EipAllocateTask fail %s", err)
|
||||
return err
|
||||
}
|
||||
self.SetStatus(userCred, EIP_STATUS_ALLOCATE, "start allocate")
|
||||
task.ScheduleRun(nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SElasticip) Delete(ctx context.Context, userCred mcclient.TokenCredential) error {
|
||||
log.Infof("Elasticip delete do nothing")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SElasticip) RealDelete(ctx context.Context, userCred mcclient.TokenCredential) error {
|
||||
return self.SVirtualResourceBase.Delete(ctx, userCred)
|
||||
}
|
||||
|
||||
func (self *SElasticip) CustomizeDelete(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) error {
|
||||
return self.StartEipDeallocateTask(ctx, userCred, "")
|
||||
}
|
||||
|
||||
func (self *SElasticip) ValidateDeleteCondition(ctx context.Context) error {
|
||||
if len(self.AssociateId) > 0 {
|
||||
return fmt.Errorf("eip is associated with instance")
|
||||
}
|
||||
return self.SVirtualResourceBase.ValidateDeleteCondition(ctx)
|
||||
}
|
||||
|
||||
func (self *SElasticip) StartEipDeallocateTask(ctx context.Context, userCred mcclient.TokenCredential, parentTaskId string) error {
|
||||
task, err := taskman.TaskManager.NewTask(ctx, "EipDeallocateTask", self, userCred, nil, parentTaskId, "", nil)
|
||||
if err != nil {
|
||||
log.Errorf("newTask EipDeallocateTask fail %s", err)
|
||||
return err
|
||||
}
|
||||
self.SetStatus(userCred, EIP_STATUS_DEALLOCATE, "start to delete")
|
||||
task.ScheduleRun(nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SElasticip) AllowPerformAssociate(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) bool {
|
||||
return self.IsOwner(userCred)
|
||||
}
|
||||
|
||||
func (self *SElasticip) PerformAssociate(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) (jsonutils.JSONObject, error) {
|
||||
if len(self.AssociateId) > 0 {
|
||||
return nil, httperrors.NewConflictError("eip has been associated with instance")
|
||||
}
|
||||
|
||||
if self.Status != EIP_STATUS_READY {
|
||||
return nil, httperrors.NewInvalidStatusError("eip cannot associate in status %s", self.Status)
|
||||
}
|
||||
|
||||
if self.Mode == EIP_MODE_INSTANCE_PUBLICIP {
|
||||
return nil, httperrors.NewUnsupportOperationError("fixed eip cannot be associated")
|
||||
}
|
||||
|
||||
instanceId := jsonutils.GetAnyString(data, []string{"instance", "instance_id"})
|
||||
if len(instanceId) == 0 {
|
||||
return nil, httperrors.NewInputParameterError("Missing instance_id")
|
||||
}
|
||||
instanceType := jsonutils.GetAnyString(data, []string{"instance_type"})
|
||||
if len(instanceType) == 0 {
|
||||
instanceType = EIP_ASSOCIATE_TYPE_SERVER
|
||||
}
|
||||
|
||||
if instanceType != EIP_ASSOCIATE_TYPE_SERVER {
|
||||
return nil, httperrors.NewInputParameterError("Unsupported %s", instanceType)
|
||||
}
|
||||
|
||||
vmObj, err := GuestManager.FetchByIdOrName(userCred.GetProjectId(), instanceId)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, httperrors.NewResourceNotFoundError("server %s not found", instanceId)
|
||||
} else {
|
||||
return nil, httperrors.NewGeneralError(err)
|
||||
}
|
||||
}
|
||||
|
||||
server := vmObj.(*SGuest)
|
||||
|
||||
if ok, _ := utils.InStringArray(server.Status, []string{VM_READY, VM_RUNNING}); !ok {
|
||||
return nil, httperrors.NewInvalidStatusError("cannot associate server in status %s", server.Status)
|
||||
}
|
||||
|
||||
serverRegion := server.getRegion()
|
||||
if serverRegion == nil {
|
||||
return nil, httperrors.NewInputParameterError("server region is not found???")
|
||||
}
|
||||
|
||||
eipRegion := self.GetRegion()
|
||||
if eipRegion == nil {
|
||||
return nil, httperrors.NewInputParameterError("eip region is not found???")
|
||||
}
|
||||
|
||||
if serverRegion.Id != eipRegion.Id {
|
||||
return nil, httperrors.NewInputParameterError("eip and server are not in the same region")
|
||||
}
|
||||
|
||||
srvHost := server.GetHost()
|
||||
if srvHost == nil {
|
||||
return nil, httperrors.NewInputParameterError("server host is not found???")
|
||||
}
|
||||
|
||||
if srvHost.ManagerId != self.ManagerId {
|
||||
return nil, httperrors.NewInputParameterError("server and eip are not managed by the same provider")
|
||||
}
|
||||
|
||||
params := jsonutils.NewDict()
|
||||
params.Add(jsonutils.NewString(server.ExternalId), "instance_external_id")
|
||||
params.Add(jsonutils.NewString(server.Id), "instance_id")
|
||||
params.Add(jsonutils.NewString(EIP_ASSOCIATE_TYPE_SERVER), "instance_type")
|
||||
|
||||
err = self.StartEipAssociateTask(ctx, userCred, params)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (self *SElasticip) StartEipAssociateTask(ctx context.Context, userCred mcclient.TokenCredential, params *jsonutils.JSONDict) error {
|
||||
task, err := taskman.TaskManager.NewTask(ctx, "EipAssociateTask", self, userCred, params, "", "", nil)
|
||||
if err != nil {
|
||||
log.Errorf("create EipAssociateTask task fail %s", err)
|
||||
return err
|
||||
}
|
||||
self.SetStatus(userCred, EIP_STATUS_ASSOCIATE, "start to associate")
|
||||
task.ScheduleRun(nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SElasticip) AllowPerformDissociate(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) bool {
|
||||
return self.IsOwner(userCred)
|
||||
}
|
||||
|
||||
func (self *SElasticip) PerformDissociate(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) (jsonutils.JSONObject, error) {
|
||||
if len(self.AssociateId) == 0 {
|
||||
return nil, httperrors.NewConflictError("eip is not associated with instance")
|
||||
}
|
||||
|
||||
if self.Status != EIP_STATUS_READY {
|
||||
return nil, httperrors.NewInvalidStatusError("eip cannot dissociate in status %s", self.Status)
|
||||
}
|
||||
|
||||
if self.Mode == EIP_MODE_INSTANCE_PUBLICIP {
|
||||
return nil, httperrors.NewUnsupportOperationError("fixed public eip cannot be dissociated")
|
||||
}
|
||||
|
||||
err := self.StartEipDissociateTask(ctx, userCred, "")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (self *SElasticip) StartEipDissociateTask(ctx context.Context, userCred mcclient.TokenCredential, parentTaskId string) error {
|
||||
task, err := taskman.TaskManager.NewTask(ctx, "EipDissociateTask", self, userCred, nil, parentTaskId, "", nil)
|
||||
if err != nil {
|
||||
log.Errorf("create EipDissociateTask fail %s", err)
|
||||
return nil
|
||||
}
|
||||
self.SetStatus(userCred, EIP_STATUS_DISSOCIATE, "start to dissociate")
|
||||
task.ScheduleRun(nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SElasticip) GetIRegion() (cloudprovider.ICloudRegion, error) {
|
||||
provider, err := self.GetDriver()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
region := self.GetRegion()
|
||||
if region == nil {
|
||||
return nil, fmt.Errorf("fail to find region for eip")
|
||||
}
|
||||
|
||||
return provider.GetIRegionById(region.GetExternalId())
|
||||
}
|
||||
|
||||
func (self *SElasticip) GetIEip() (cloudprovider.ICloudEIP, error) {
|
||||
iregion, err := self.GetIRegion()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return iregion.GetIEipById(self.GetExternalId())
|
||||
}
|
||||
|
||||
func (self *SElasticip) AllowPerformSync(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) bool {
|
||||
return self.IsOwner(userCred)
|
||||
}
|
||||
|
||||
func (self *SElasticip) PerformSync(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) (jsonutils.JSONObject, error) {
|
||||
/*if self.Status != EIP_STATUS_READY && ! strings.HasSuffix(self.Status, "_fail") {
|
||||
return nil, httperrors.NewInvalidStatusError("eip cannot syncstatus in status %s", self.Status)
|
||||
}*/
|
||||
|
||||
if self.Mode == EIP_MODE_INSTANCE_PUBLICIP {
|
||||
return nil, httperrors.NewUnsupportOperationError("fixed eip cannot be dissociated")
|
||||
}
|
||||
|
||||
err := self.StartEipSyncstatusTask(ctx, userCred, "")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (self *SElasticip) StartEipSyncstatusTask(ctx context.Context, userCred mcclient.TokenCredential, parentTaskId string) error {
|
||||
task, err := taskman.TaskManager.NewTask(ctx, "EipSyncstatusTask", self, userCred, nil, parentTaskId, "", nil)
|
||||
if err != nil {
|
||||
log.Errorf("create EipSyncstatusTask fail %s", err)
|
||||
return err
|
||||
}
|
||||
self.SetStatus(userCred, "sync", "synchronize")
|
||||
task.ScheduleRun(nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SElasticip) GetExtraDetails(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject) *jsonutils.JSONDict {
|
||||
extra := self.SVirtualResourceBase.GetExtraDetails(ctx, userCred, query)
|
||||
return self.getMoreDetails(extra)
|
||||
}
|
||||
|
||||
func (self *SElasticip) GetCustomizeColumns(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject) *jsonutils.JSONDict {
|
||||
extra := self.SVirtualResourceBase.GetCustomizeColumns(ctx, userCred, query)
|
||||
return self.getMoreDetails(extra)
|
||||
}
|
||||
|
||||
func (self *SElasticip) getMoreDetails(extra *jsonutils.JSONDict) *jsonutils.JSONDict {
|
||||
vm := self.getVM()
|
||||
if vm != nil {
|
||||
extra.Add(jsonutils.NewString(vm.GetName()), "associate_name")
|
||||
}
|
||||
return extra
|
||||
}
|
||||
|
||||
func (manager *SElasticipManager) allocateEipAndAssociateVM(ctx context.Context, userCred mcclient.TokenCredential, vm *SGuest, bw int, chargeType string, managerId string, regionId string) error {
|
||||
eipPendingUsage := &SQuota{Eip: 1}
|
||||
err := QuotaManager.CheckSetPendingQuota(ctx, userCred, userCred.GetProjectId(), eipPendingUsage)
|
||||
if err != nil {
|
||||
return httperrors.NewOutOfQuotaError("Out of eip quota: %s", err)
|
||||
}
|
||||
|
||||
eip := SElasticip{}
|
||||
eip.SetModelManager(manager)
|
||||
|
||||
eip.Mode = EIP_MODE_STANDALONE_EIP
|
||||
eip.AutoDellocate = tristate.True
|
||||
eip.Bandwidth = bw
|
||||
eip.ChargeType = chargeType
|
||||
eip.ProjectId = vm.ProjectId
|
||||
eip.ManagerId = managerId
|
||||
eip.CloudregionId = regionId
|
||||
eip.Name = fmt.Sprintf("eip-for-%s", vm.GetName())
|
||||
|
||||
err = manager.TableSpec().Insert(&eip)
|
||||
if err != nil {
|
||||
log.Errorf("create EIP record fail %s", err)
|
||||
return err
|
||||
}
|
||||
|
||||
params := jsonutils.NewDict()
|
||||
params.Add(jsonutils.NewString(vm.ExternalId), "instance_external_id")
|
||||
params.Add(jsonutils.NewString(vm.Id), "instance_id")
|
||||
params.Add(jsonutils.NewString(EIP_ASSOCIATE_TYPE_SERVER), "instance_type")
|
||||
|
||||
return eip.startEipAllocateTask(ctx, userCred, params, eipPendingUsage)
|
||||
}
|
||||
|
||||
func (self *SElasticip) AllowPerformChangeBandwidth(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) bool {
|
||||
return self.IsOwner(userCred)
|
||||
}
|
||||
|
||||
func (self *SElasticip) PerformChangeBandwidth(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) (jsonutils.JSONObject, error) {
|
||||
if self.Status != EIP_STATUS_READY {
|
||||
return nil, httperrors.NewInvalidStatusError("cannot change bandwidth in status %s", self.Status)
|
||||
}
|
||||
|
||||
bandwidth, err := data.Int("bandwidth")
|
||||
if err != nil || bandwidth <= 0 {
|
||||
return nil, httperrors.NewInputParameterError("Invalid bandwidth")
|
||||
}
|
||||
err = self.StartEipChangeBandwidthTask(ctx, userCred, bandwidth)
|
||||
if err != nil {
|
||||
return nil, httperrors.NewGeneralError(err)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (self *SElasticip) StartEipChangeBandwidthTask(ctx context.Context, userCred mcclient.TokenCredential, bandwidth int64) error {
|
||||
params := jsonutils.NewDict()
|
||||
params.Add(jsonutils.NewInt(bandwidth), "bandwidth")
|
||||
|
||||
task, err := taskman.TaskManager.NewTask(ctx, "EipChangeBandwidthTask", self, userCred, params, "", "", nil)
|
||||
if err != nil {
|
||||
log.Errorf("create EipChangeBandwidthTask fail %s", err)
|
||||
return err
|
||||
}
|
||||
task.ScheduleRun(nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SElasticip) DoChangeBandwidth(userCred mcclient.TokenCredential, bandwidth int) error {
|
||||
_, err := self.GetModelManager().TableSpec().Update(self, func() error {
|
||||
self.Bandwidth = bandwidth
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Errorf("DoChangeBandwidth update fail %s", err)
|
||||
return err
|
||||
}
|
||||
|
||||
changes := jsonutils.NewDict()
|
||||
changes.Add(jsonutils.NewInt(int64(self.Bandwidth)), "obw")
|
||||
changes.Add(jsonutils.NewInt(int64(bandwidth)), "nbw")
|
||||
db.OpsLog.LogEvent(self, db.ACT_CHANGE_BANDWIDTH, changes, userCred)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type EipUsage struct {
|
||||
PublicIPCount int
|
||||
EIPCount int
|
||||
EIPUsedCount int
|
||||
}
|
||||
|
||||
func (u EipUsage) Total() int {
|
||||
return u.PublicIPCount + u.EIPCount
|
||||
}
|
||||
|
||||
func (manager *SElasticipManager) TotalCount(projectId string) EipUsage {
|
||||
usage := EipUsage{}
|
||||
q1 := manager.Query().Equals("mode", EIP_MODE_INSTANCE_PUBLICIP)
|
||||
q2 := manager.Query().Equals("mode", EIP_MODE_STANDALONE_EIP)
|
||||
q3 := manager.Query().Equals("mode", EIP_MODE_STANDALONE_EIP).IsNotEmpty("associate_id")
|
||||
if len(projectId) > 0 {
|
||||
q1 = q1.Equals("tenant_id", projectId)
|
||||
q2 = q2.Equals("tenant_id", projectId)
|
||||
q3 = q3.Equals("tenant_id", projectId)
|
||||
}
|
||||
usage.PublicIPCount = q1.Count()
|
||||
usage.EIPCount = q2.Count()
|
||||
usage.EIPUsedCount = q3.Count()
|
||||
return usage
|
||||
}
|
||||
@@ -301,6 +301,24 @@ func (manager *SGuestManager) ListItemFilter(ctx context.Context, q *sqlchemy.SQ
|
||||
q = q.In("host_id", sq)
|
||||
}
|
||||
|
||||
regionFilter, _ := queryDict.GetString("region")
|
||||
if len(regionFilter) > 0 {
|
||||
regionObj, err := CloudregionManager.FetchByIdOrName(userCred.GetProjectId(), regionFilter)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, httperrors.NewResourceNotFoundError("cloud region %s not found", regionFilter)
|
||||
} else {
|
||||
return nil, httperrors.NewGeneralError(err)
|
||||
}
|
||||
}
|
||||
hosts := HostManager.Query().SubQuery()
|
||||
zones := ZoneManager.Query().SubQuery()
|
||||
sq := hosts.Query(hosts.Field("id"))
|
||||
sq = sq.Join(zones, sqlchemy.Equals(hosts.Field("zone_id"), zones.Field("id")))
|
||||
sq = sq.Filter(sqlchemy.Equals(zones.Field("cloudregion_id"), regionObj.GetId()))
|
||||
q = q.In("host_id", sq)
|
||||
}
|
||||
|
||||
gpu, _ := queryDict.GetString("gpu")
|
||||
if len(gpu) != 0 {
|
||||
isodev := IsolatedDeviceManager.Query().SubQuery()
|
||||
@@ -927,6 +945,10 @@ func (self *SGuest) GetCustomizeColumns(ctx context.Context, userCred mcclient.T
|
||||
}
|
||||
}
|
||||
extra.Add(jsonutils.NewString(strings.Join(self.getRealIPs(), ",")), "ips")
|
||||
eip, _ := self.GetEip()
|
||||
if eip != nil {
|
||||
extra.Add(jsonutils.NewString(eip.IpAddr), "eip")
|
||||
}
|
||||
extra.Add(jsonutils.NewInt(int64(self.getDiskSize())), "disk")
|
||||
// flavor??
|
||||
// extra.Add(jsonutils.NewString(self.getFlavorName()), "flavor")
|
||||
@@ -995,6 +1017,10 @@ func (self *SGuest) GetExtraDetails(ctx context.Context, userCred mcclient.Token
|
||||
}
|
||||
extra.Add(jsonutils.NewString(self.getAdminSecurityRules()), "admin_security_rules")
|
||||
}
|
||||
eip, _ := self.GetEip()
|
||||
if eip != nil {
|
||||
extra.Add(jsonutils.NewString(eip.IpAddr), "eip")
|
||||
}
|
||||
return self.moreExtraInfo(extra)
|
||||
}
|
||||
|
||||
@@ -1126,6 +1152,10 @@ func (self *SGuest) getIPs() []string {
|
||||
ips := self.getRealIPs()
|
||||
vips := self.getVirtualIPs()
|
||||
ips = append(ips, vips...)
|
||||
eip, _ := self.GetEip()
|
||||
if eip != nil {
|
||||
ips = append(ips, eip.IpAddr)
|
||||
}
|
||||
return ips
|
||||
}
|
||||
|
||||
@@ -1137,6 +1167,14 @@ func (self *SGuest) getZone() *SZone {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SGuest) getRegion() *SCloudregion {
|
||||
zone := self.getZone()
|
||||
if zone != nil {
|
||||
return zone.GetRegion()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SGuest) GetOS() string {
|
||||
if len(self.OsType) > 0 {
|
||||
return self.OsType
|
||||
@@ -3549,6 +3587,156 @@ func (manager *SGuestManager) CleanPendingDeleteServers(ctx context.Context, use
|
||||
}
|
||||
}
|
||||
|
||||
func (self *SGuest) GetEip() (*SElasticip, error) {
|
||||
return ElasticipManager.getEipForInstance("server", self.Id)
|
||||
}
|
||||
|
||||
func (self *SGuest) SyncVMEip(ctx context.Context, userCred mcclient.TokenCredential, extEip cloudprovider.ICloudEIP) compare.SyncResult {
|
||||
result := compare.SyncResult{}
|
||||
|
||||
eip, err := self.GetEip()
|
||||
if err != nil {
|
||||
result.Error(fmt.Errorf("getEip error %s", err))
|
||||
return result
|
||||
}
|
||||
|
||||
if eip == nil && extEip == nil {
|
||||
// do nothing
|
||||
} else if eip == nil && extEip != nil {
|
||||
// add
|
||||
neip, err := ElasticipManager.getEipByExtEip(userCred, extEip, self.getRegion())
|
||||
if err != nil {
|
||||
result.AddError(err)
|
||||
} else {
|
||||
err = neip.AssociateVM(userCred, self)
|
||||
if err != nil {
|
||||
result.AddError(err)
|
||||
} else {
|
||||
result.Add()
|
||||
}
|
||||
}
|
||||
} else if eip != nil && extEip == nil {
|
||||
// remove
|
||||
err = eip.Dissociate(ctx, userCred)
|
||||
if err != nil {
|
||||
result.DeleteError(err)
|
||||
} else {
|
||||
result.Delete()
|
||||
}
|
||||
} else {
|
||||
// sync
|
||||
if eip.IpAddr != extEip.GetIpAddr() {
|
||||
// remove then add
|
||||
err = eip.Dissociate(ctx, userCred)
|
||||
if err != nil {
|
||||
// fail to remove
|
||||
result.DeleteError(err)
|
||||
} else {
|
||||
result.Delete()
|
||||
neip, err := ElasticipManager.getEipByExtEip(userCred, extEip, self.getRegion())
|
||||
if err != nil {
|
||||
result.AddError(err)
|
||||
} else {
|
||||
err = neip.AssociateVM(userCred, self)
|
||||
if err != nil {
|
||||
result.AddError(err)
|
||||
} else {
|
||||
result.Add()
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// do nothing
|
||||
err := eip.SyncWithCloudEip(userCred, extEip)
|
||||
if err != nil {
|
||||
result.UpdateError(err)
|
||||
} else {
|
||||
result.Update()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (self *SGuest) GetIVM() (cloudprovider.ICloudVM, error) {
|
||||
if len(self.ExternalId) == 0 {
|
||||
msg := fmt.Sprintf("GetIVM: not managed by a provider")
|
||||
log.Errorf(msg)
|
||||
return nil, fmt.Errorf(msg)
|
||||
}
|
||||
host := self.GetHost()
|
||||
if host == nil {
|
||||
msg := fmt.Sprintf("GetIVM: No valid host")
|
||||
log.Errorf(msg)
|
||||
return nil, fmt.Errorf(msg)
|
||||
}
|
||||
ihost, err := host.GetIHost()
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("GetIVM: getihost fail %s", err)
|
||||
log.Errorf(msg)
|
||||
return nil, fmt.Errorf(msg)
|
||||
}
|
||||
return ihost.GetIVMById(self.ExternalId)
|
||||
}
|
||||
|
||||
func (self *SGuest) AllowPerformCreateEip(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) bool {
|
||||
return self.IsOwner(userCred)
|
||||
}
|
||||
|
||||
func (self *SGuest) PerformCreateEip(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) (jsonutils.JSONObject, error) {
|
||||
bw, err := data.Int("bandwidth")
|
||||
if err != nil {
|
||||
return nil, httperrors.NewInputParameterError("Missing bandwidth")
|
||||
}
|
||||
|
||||
chargeType, _ := data.GetString("charge_type")
|
||||
if len(chargeType) == 0 {
|
||||
chargeType = EIP_CHARGE_TYPE_DEFAULT
|
||||
}
|
||||
|
||||
if len(self.ExternalId) == 0 {
|
||||
return nil, httperrors.NewInvalidStatusError("Not a managed VM")
|
||||
}
|
||||
host := self.GetHost()
|
||||
if host == nil {
|
||||
return nil, httperrors.NewInvalidStatusError("No host???")
|
||||
}
|
||||
|
||||
_, err = host.GetDriver()
|
||||
if err != nil {
|
||||
return nil, httperrors.NewInvalidStatusError("No valid cloud provider")
|
||||
}
|
||||
|
||||
region := host.GetRegion()
|
||||
if region == nil {
|
||||
return nil, httperrors.NewInvalidStatusError("No cloudregion???")
|
||||
}
|
||||
|
||||
err = ElasticipManager.allocateEipAndAssociateVM(ctx, userCred, self, int(bw), chargeType, host.ManagerId, region.Id)
|
||||
if err != nil {
|
||||
return nil, httperrors.NewGeneralError(err)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (self *SGuest) DeleteEip(ctx context.Context, userCred mcclient.TokenCredential) error {
|
||||
eip, err := self.GetEip()
|
||||
if err != nil {
|
||||
log.Errorf("Delete eip fail for get Eip %s", err)
|
||||
return err
|
||||
}
|
||||
if eip == nil {
|
||||
return nil
|
||||
}
|
||||
err = eip.Delete(ctx, userCred)
|
||||
if err != nil {
|
||||
log.Errorf("Delete eip fail %s", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SGuest) SetDisableDelete(val bool) error {
|
||||
_, err := self.GetModelManager().TableSpec().Update(self, func() error {
|
||||
if val {
|
||||
|
||||
@@ -1436,13 +1436,6 @@ func (self *SHost) GetIHost() (cloudprovider.ICloudHost, error) {
|
||||
return nil, fmt.Errorf("No cloudprovide for host: %s", err)
|
||||
}
|
||||
ihost, err := provider.GetIHostById(self.ExternalId)
|
||||
|
||||
/* izone, err := self.GetIZone()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fail to find izone by id %s", err)
|
||||
}
|
||||
ihost, err := izone.GetIHostById(self.ExternalId)*/
|
||||
|
||||
if err != nil {
|
||||
log.Errorf("fail to find ihost by id %s", err)
|
||||
return nil, fmt.Errorf("fail to find ihost by id %s", err)
|
||||
|
||||
@@ -71,7 +71,7 @@ func (self *SQuota) FetchUsage(projectId string) error {
|
||||
diskSize := totalDiskSize(projectId, tristate.None, tristate.None, false)
|
||||
net := totalGuestNicCount(projectId, nil, false)
|
||||
guest := totalGuestResourceCount(projectId, nil, nil, "", false, false, "")
|
||||
|
||||
eipUsage := ElasticipManager.TotalCount(projectId)
|
||||
// XXX
|
||||
// keypair belongs to user
|
||||
// keypair := totalKeypairCount(projectId)
|
||||
@@ -80,7 +80,7 @@ func (self *SQuota) FetchUsage(projectId string) error {
|
||||
self.Memory = guest.TotalMemSize
|
||||
self.Storage = diskSize
|
||||
self.Port = net.InternalNicCount + net.InternalVirtualNicCount
|
||||
self.Eip = 0
|
||||
self.Eip = eipUsage.Total()
|
||||
self.Eport = net.ExternalNicCount + net.ExternalVirtualNicCount
|
||||
self.Bw = net.InternalBandwidth
|
||||
self.Ebw = net.ExternalBandwidth
|
||||
|
||||
@@ -57,7 +57,7 @@ type SStoragecachedimage struct {
|
||||
StoragecacheId string `width:"36" charset:"ascii" nullable:"false" list:"admin" create:"admin_required" key_index:"true"`
|
||||
CachedimageId string `width:"36" charset:"ascii" nullable:"false" list:"admin" create:"admin_required" key_index:"true"`
|
||||
|
||||
ExternalId string `width:"64" charset:"ascii" nullable:"false" get:"admin"`
|
||||
ExternalId string `width:"128" charset:"ascii" nullable:"false" get:"admin"`
|
||||
|
||||
Status string `width:"32" charset:"ascii" nullable:"false" default:"init" list:"admin" update:"admin" create:"admin_required"` // = Column(VARCHAR(32, charset='ascii'), nullable=False,
|
||||
Path string `width:"256" charset:"utf8" nullable:"true" list:"admin" update:"admin" create:"admin_optional"` // = Column(VARCHAR(256, charset='utf8'), nullable=True)
|
||||
|
||||
@@ -66,16 +66,16 @@ type SStorage struct {
|
||||
SInfrastructure
|
||||
SManagedResourceBase
|
||||
|
||||
Capacity int `nullable:"false" list:"admin" update:"admin" create:"admin_required"` // Column(Integer, nullable=False) # capacity of disk in MB
|
||||
Reserved int `nullable:"true" default:"0" list:"admin" update:"admin"` // Column(Integer, nullable=True, default=0)
|
||||
StorageType string `width:"32" charset:"ascii" nullable:"false" list:"user" update:"admin" create:"admin_required"` // Column(VARCHAR(32, charset='ascii'), nullable=False)
|
||||
MediumType string `width:"32" charset:"ascii" nullable:"false" list:"admin" update:"admin" create:"admin_required"` // Column(VARCHAR(32, charset='ascii'), nullable=False)
|
||||
Cmtbound float32 `nullable:"true" list:"admin" update:"admin"` // Column(Float, nullable=True)
|
||||
StorageConf jsonutils.JSONObject `nullable:"true" get:"admin" update:"admin"` // = Column(JSONEncodedDict, nullable=True)
|
||||
Capacity int `nullable:"false" list:"admin" update:"admin" create:"admin_required"` // Column(Integer, nullable=False) # capacity of disk in MB
|
||||
Reserved int `nullable:"true" default:"0" list:"admin" update:"admin"` // Column(Integer, nullable=True, default=0)
|
||||
StorageType string `width:"32" charset:"ascii" nullable:"false" list:"user" update:"admin" create:"admin_required"` // Column(VARCHAR(32, charset='ascii'), nullable=False)
|
||||
MediumType string `width:"32" charset:"ascii" nullable:"false" list:"user" update:"admin" create:"admin_required"` // Column(VARCHAR(32, charset='ascii'), nullable=False)
|
||||
Cmtbound float32 `nullable:"true" list:"admin" update:"admin"` // Column(Float, nullable=True)
|
||||
StorageConf jsonutils.JSONObject `nullable:"true" get:"admin" update:"admin"` // = Column(JSONEncodedDict, nullable=True)
|
||||
|
||||
ZoneId string `width:"36" charset:"ascii" nullable:"false" list:"admin" create:"admin_required"`
|
||||
ZoneId string `width:"36" charset:"ascii" nullable:"false" list:"user" create:"admin_required"`
|
||||
|
||||
StoragecacheId string `width:"36" charset:"ascii" nullable:"true" get:"admin"`
|
||||
StoragecacheId string `width:"36" charset:"ascii" nullable:"true" list:"admin" get:"admin"`
|
||||
}
|
||||
|
||||
func (manager *SStorageManager) GetContextManager() []db.IModelManager {
|
||||
|
||||
@@ -7,14 +7,15 @@ import (
|
||||
|
||||
"yunion.io/x/jsonutils"
|
||||
"yunion.io/x/log"
|
||||
"yunion.io/x/pkg/util/compare"
|
||||
"yunion.io/x/pkg/util/netutils"
|
||||
"yunion.io/x/sqlchemy"
|
||||
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon/db"
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
|
||||
"yunion.io/x/onecloud/pkg/cloudprovider"
|
||||
"yunion.io/x/onecloud/pkg/httperrors"
|
||||
"yunion.io/x/onecloud/pkg/mcclient"
|
||||
"yunion.io/x/pkg/util/compare"
|
||||
"yunion.io/x/pkg/util/netutils"
|
||||
"yunion.io/x/sqlchemy"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -35,7 +35,7 @@ type ComputeOptions struct {
|
||||
DefaultMemoryQuota int `default:"51200" help:"Common memory quota per tenant in MB, default 50G"`
|
||||
DefaultStorageQuota int `default:"3072000" help:"Common storage quota per tenant in MB, default 3000G"`
|
||||
DefaultPortQuota int `default:"50" help:"Common network port quota per tenant, default 50"`
|
||||
DefaultEipQuota int `default:"0" help:"Common floating IP quota per tenant, default 0"`
|
||||
DefaultEipQuota int `default:"5" help:"Common floating IP quota per tenant, default 0"`
|
||||
DefaultEportQuota int `default:"50" help:"Common exit network port quota per tenant, default 50"`
|
||||
DefaultBwQuota int `default:"500000" help:"Common network port bandwidth in mbps quota per tenant, default 50*10Gbps"`
|
||||
DefaultEbwQuota int `default:"1000" help:"Common exit network port bandwidth quota per tenant, default 1Gbps"`
|
||||
|
||||
@@ -109,6 +109,8 @@ func syncCloudProviderInfo(ctx context.Context, provider *models.SCloudprovider,
|
||||
continue
|
||||
}
|
||||
|
||||
syncRegionEips(ctx, provider, task, &localRegions[i], remoteRegions[i])
|
||||
|
||||
localZones, remoteZones := syncRegionZones(ctx, provider, task, &localRegions[i], remoteRegions[i])
|
||||
|
||||
syncRegionVPCs(ctx, provider, task, &localRegions[i], remoteRegions[i])
|
||||
@@ -126,6 +128,25 @@ func syncCloudProviderInfo(ctx context.Context, provider *models.SCloudprovider,
|
||||
}
|
||||
}
|
||||
|
||||
func syncRegionEips(ctx context.Context, provider *models.SCloudprovider, task *CloudProviderSyncInfoTask, localRegion *models.SCloudregion, remoteRegion cloudprovider.ICloudRegion) {
|
||||
eips, err := remoteRegion.GetIEips()
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("GetIEips for region %s failed %s", remoteRegion.GetName(), err)
|
||||
log.Errorf(msg)
|
||||
logSyncFailed(provider, task, msg)
|
||||
return
|
||||
}
|
||||
|
||||
result := models.ElasticipManager.SyncEips(ctx, task.UserCred, provider, localRegion, eips)
|
||||
msg := result.Result()
|
||||
log.Infof("SyncEips for region %s result: %s", localRegion.Name, msg)
|
||||
if result.IsError() {
|
||||
logSyncFailed(provider, task, msg)
|
||||
return
|
||||
}
|
||||
db.OpsLog.LogEvent(provider, db.ACT_SYNC_HOST_COMPLETE, msg, task.UserCred)
|
||||
}
|
||||
|
||||
func syncRegionZones(ctx context.Context, provider *models.SCloudprovider, task *CloudProviderSyncInfoTask, localRegion *models.SCloudregion, remoteRegion cloudprovider.ICloudRegion) ([]models.SZone, []cloudprovider.ICloudZone) {
|
||||
zones, err := remoteRegion.GetIZones()
|
||||
if err != nil {
|
||||
@@ -384,6 +405,7 @@ func syncHostVMs(ctx context.Context, provider *models.SCloudprovider, task *Clo
|
||||
for i := 0; i < len(localVMs); i += 1 {
|
||||
syncVMNics(ctx, provider, task, localHost, &localVMs[i], remoteVMs[i])
|
||||
syncVMDisks(ctx, provider, task, localHost, &localVMs[i], remoteVMs[i])
|
||||
syncVMEip(ctx, provider, task, &localVMs[i], remoteVMs[i])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -426,3 +448,21 @@ func syncVMDisks(ctx context.Context, provider *models.SCloudprovider, task *Clo
|
||||
db.OpsLog.LogEvent(provider, db.ACT_SYNC_HOST_COMPLETE, msg, task.UserCred)
|
||||
logclient.AddActionLog(provider, getAction(task.Params), notes, task.UserCred, true)
|
||||
}
|
||||
|
||||
func syncVMEip(ctx context.Context, provider *models.SCloudprovider, task *CloudProviderSyncInfoTask, localVM *models.SGuest, remoteVM cloudprovider.ICloudVM) {
|
||||
eip, err := remoteVM.GetIEIP()
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("GetIEIP for VM %s failed %s", remoteVM.GetName(), err)
|
||||
log.Errorf(msg)
|
||||
logSyncFailed(provider, task, msg)
|
||||
return
|
||||
}
|
||||
result := localVM.SyncVMEip(ctx, task.UserCred, eip)
|
||||
msg := result.Result()
|
||||
log.Infof("syncVMEip for VM %s result: %s", localVM.Name, msg)
|
||||
if result.IsError() {
|
||||
logSyncFailed(provider, task, msg)
|
||||
return
|
||||
}
|
||||
db.OpsLog.LogEvent(provider, db.ACT_SYNC_HOST_COMPLETE, msg, task.UserCred)
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package tasks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"yunion.io/x/jsonutils"
|
||||
"yunion.io/x/log"
|
||||
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon/db"
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
|
||||
"yunion.io/x/onecloud/pkg/compute/models"
|
||||
)
|
||||
|
||||
|
||||
type EipAllocateTask struct {
|
||||
taskman.STask
|
||||
}
|
||||
|
||||
func init() {
|
||||
taskman.RegisterTask(EipAllocateTask{})
|
||||
}
|
||||
|
||||
func (self *EipAllocateTask) OnInit(ctx context.Context, obj db.IStandaloneModel, data jsonutils.JSONObject) {
|
||||
eip := obj.(*models.SElasticip)
|
||||
|
||||
iregion, err := eip.GetIRegion()
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("fail to find iregion for eip %s", err)
|
||||
eip.SetStatus(self.UserCred, models.EIP_STATUS_ALLOCATE_FAIL, msg)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
return
|
||||
}
|
||||
|
||||
extEip, err := iregion.CreateEIP(eip.Bandwidth)
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("create eip fail %s", err)
|
||||
eip.SetStatus(self.UserCred, models.EIP_STATUS_ALLOCATE_FAIL, msg)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
return
|
||||
}
|
||||
|
||||
err = eip.SyncWithCloudEip(self.UserCred, extEip)
|
||||
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("sync eip fail %s", err)
|
||||
eip.SetStatus(self.UserCred, models.EIP_STATUS_ALLOCATE_FAIL, msg)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
return
|
||||
}
|
||||
|
||||
eipPendingUsage := &models.SQuota{Eip: 1}
|
||||
err = models.QuotaManager.CancelPendingUsage(ctx, self.UserCred, self.UserCred.GetProjectId(), eipPendingUsage, eipPendingUsage)
|
||||
|
||||
if err != nil {
|
||||
log.Errorf("CancelPendingUsage fail %s", err)
|
||||
}
|
||||
|
||||
if self.Params != nil && self.Params.Contains("instance_id") {
|
||||
self.SetStage("on_eip_associate_complete", nil)
|
||||
err = eip.StartEipAssociateTask(ctx, self.UserCred, self.Params)
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("start associate task fail %s", err)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
}
|
||||
} else {
|
||||
self.SetStageComplete(ctx, nil)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *EipAllocateTask) OnEipAssociateComplete(ctx context.Context, obj db.IStandaloneModel, data jsonutils.JSONObject) {
|
||||
self.SetStageComplete(ctx, nil)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package tasks
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"context"
|
||||
|
||||
"yunion.io/x/jsonutils"
|
||||
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon/db"
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
|
||||
"yunion.io/x/onecloud/pkg/compute/models"
|
||||
)
|
||||
|
||||
type EipAssociateTask struct {
|
||||
taskman.STask
|
||||
}
|
||||
|
||||
func init() {
|
||||
taskman.RegisterTask(EipAssociateTask{})
|
||||
}
|
||||
|
||||
func (self *EipAssociateTask) OnInit(ctx context.Context, obj db.IStandaloneModel, data jsonutils.JSONObject) {
|
||||
eip := obj.(*models.SElasticip)
|
||||
|
||||
extEip, err := eip.GetIEip()
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("fail to find iEIP for eip %s", err)
|
||||
eip.SetStatus(self.UserCred, models.EIP_STATUS_ASSOCIATE_FAIL, msg)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
return
|
||||
}
|
||||
|
||||
instanceId, _ := self.Params.GetString("instance_id")
|
||||
server := models.GuestManager.FetchGuestById(instanceId)
|
||||
if server == nil {
|
||||
msg := fmt.Sprintf("fail to find server for instanceId %s", instanceId)
|
||||
eip.SetStatus(self.UserCred, models.EIP_STATUS_ASSOCIATE_FAIL, msg)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
return
|
||||
}
|
||||
|
||||
err = extEip.Associate(server.ExternalId)
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("fail to remote associate EIP %s", err)
|
||||
eip.SetStatus(self.UserCred, models.EIP_STATUS_ASSOCIATE_FAIL, msg)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
return
|
||||
}
|
||||
|
||||
err = eip.AssociateVM(self.UserCred, server)
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("fail to local associate EIP %s", err)
|
||||
eip.SetStatus(self.UserCred, models.EIP_STATUS_ASSOCIATE_FAIL, msg)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
return
|
||||
}
|
||||
|
||||
eip.SetStatus(self.UserCred, models.EIP_STATUS_READY, "associate")
|
||||
|
||||
self.SetStageComplete(ctx, nil)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package tasks
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"context"
|
||||
|
||||
"yunion.io/x/jsonutils"
|
||||
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon/db"
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
|
||||
"yunion.io/x/onecloud/pkg/compute/models"
|
||||
|
||||
)
|
||||
|
||||
type EipChangeBandwidthTask struct {
|
||||
taskman.STask
|
||||
}
|
||||
|
||||
func init() {
|
||||
taskman.RegisterTask(EipChangeBandwidthTask{})
|
||||
}
|
||||
|
||||
func (self *EipChangeBandwidthTask) OnInit(ctx context.Context, obj db.IStandaloneModel, data jsonutils.JSONObject) {
|
||||
eip := obj.(*models.SElasticip)
|
||||
|
||||
extEip, err := eip.GetIEip()
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("fail to find iEip %s", err)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
return
|
||||
}
|
||||
|
||||
bandwidth, _ := self.Params.Int("bandwidth")
|
||||
if bandwidth <= 0 {
|
||||
msg := fmt.Sprintf("invalid bandwidth %d", bandwidth)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
return
|
||||
}
|
||||
|
||||
err = extEip.ChangeBandwidth(int(bandwidth))
|
||||
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("fail to find iEip %s", err)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
return
|
||||
}
|
||||
|
||||
err = eip.DoChangeBandwidth(self.UserCred, int(bandwidth))
|
||||
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("fail to synchronize iEip bandwidth %s", err)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
return
|
||||
}
|
||||
|
||||
self.SetStageComplete(ctx, nil)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package tasks
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"context"
|
||||
|
||||
"yunion.io/x/jsonutils"
|
||||
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon/db"
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
|
||||
"yunion.io/x/onecloud/pkg/compute/models"
|
||||
|
||||
)
|
||||
|
||||
type EipDeallocateTask struct {
|
||||
taskman.STask
|
||||
}
|
||||
|
||||
func init() {
|
||||
taskman.RegisterTask(EipDeallocateTask{})
|
||||
}
|
||||
|
||||
func (self *EipDeallocateTask) OnInit(ctx context.Context, obj db.IStandaloneModel, data jsonutils.JSONObject) {
|
||||
eip := obj.(*models.SElasticip)
|
||||
|
||||
if len(eip.ExternalId) > 0 {
|
||||
expEip, err := eip.GetIEip()
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("fail to find iEIP for eip %s", err)
|
||||
eip.SetStatus(self.UserCred, models.EIP_STATUS_DEALLOCATE_FAIL, msg)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
return
|
||||
}
|
||||
|
||||
err = expEip.Delete()
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("fail to delete iEIP %s", err)
|
||||
eip.SetStatus(self.UserCred, models.EIP_STATUS_DEALLOCATE_FAIL, msg)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err := eip.RealDelete(ctx, self.UserCred)
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("fail to delete EIP %s", err)
|
||||
eip.SetStatus(self.UserCred, models.EIP_STATUS_DEALLOCATE_FAIL, msg)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
return
|
||||
}
|
||||
|
||||
self.SetStageComplete(ctx, nil)
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package tasks
|
||||
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"context"
|
||||
|
||||
"yunion.io/x/jsonutils"
|
||||
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon/db"
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
|
||||
"yunion.io/x/onecloud/pkg/compute/models"
|
||||
)
|
||||
|
||||
type EipDissociateTask struct {
|
||||
taskman.STask
|
||||
}
|
||||
|
||||
func init() {
|
||||
taskman.RegisterTask(EipDissociateTask{})
|
||||
}
|
||||
|
||||
func (self *EipDissociateTask) OnInit(ctx context.Context, obj db.IStandaloneModel, data jsonutils.JSONObject) {
|
||||
eip := obj.(*models.SElasticip)
|
||||
|
||||
extEip, err := eip.GetIEip()
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("fail to find iEIP for eip %s", err)
|
||||
eip.SetStatus(self.UserCred, models.EIP_STATUS_DISSOCIATE_FAIL, msg)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
return
|
||||
}
|
||||
|
||||
if len(extEip.GetAssociationExternalId()) > 0 {
|
||||
err = extEip.Dissociate()
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("fail to remote dissociate eip %s", err)
|
||||
eip.SetStatus(self.UserCred, models.EIP_STATUS_DISSOCIATE_FAIL, msg)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err = eip.Dissociate(ctx, self.UserCred)
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("fail to local dissociate eip %s", err)
|
||||
eip.SetStatus(self.UserCred, models.EIP_STATUS_DISSOCIATE_FAIL, msg)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
return
|
||||
}
|
||||
|
||||
eip.SetStatus(self.UserCred, models.EIP_STATUS_READY, "dissociate")
|
||||
|
||||
if eip.AutoDellocate.IsTrue() {
|
||||
self.SetStage("on_auto_dellocate_complete", nil)
|
||||
eip.StartEipDeallocateTask(ctx, self.UserCred, self.Id)
|
||||
} else {
|
||||
self.SetStageComplete(ctx, nil)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *EipDissociateTask) OnAutoDellocateComplete(ctx context.Context, obj db.IStandaloneModel, data jsonutils.JSONObject) {
|
||||
self.SetStageComplete(ctx, nil)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package tasks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"yunion.io/x/jsonutils"
|
||||
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon/db"
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
|
||||
"yunion.io/x/onecloud/pkg/compute/models"
|
||||
)
|
||||
|
||||
|
||||
type EipSyncstatusTask struct {
|
||||
taskman.STask
|
||||
}
|
||||
|
||||
func init() {
|
||||
taskman.RegisterTask(EipSyncstatusTask{})
|
||||
}
|
||||
|
||||
func (self *EipSyncstatusTask) OnInit(ctx context.Context, obj db.IStandaloneModel, data jsonutils.JSONObject) {
|
||||
eip := obj.(*models.SElasticip)
|
||||
|
||||
extEip, err := eip.GetIEip()
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("fail to find ieip for eip %s", err)
|
||||
eip.SetStatus(self.UserCred, models.EIP_STATUS_UNKNOWN, msg)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
return
|
||||
}
|
||||
|
||||
err = extEip.Refresh()
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("fail to refresh eip status %s", err)
|
||||
eip.SetStatus(self.UserCred, models.EIP_STATUS_UNKNOWN, msg)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
return
|
||||
}
|
||||
|
||||
err = eip.SyncWithCloudEip(self.UserCred, extEip)
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("fail to sync eip status %s", err)
|
||||
eip.SetStatus(self.UserCred, models.EIP_STATUS_UNKNOWN, msg)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
return
|
||||
}
|
||||
|
||||
err = eip.SyncInstanceWithCloudEip(ctx, self.UserCred, extEip)
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("fail to sync eip status %s", err)
|
||||
eip.SetStatus(self.UserCred, models.EIP_STATUS_UNKNOWN, msg)
|
||||
self.SetStageFailed(ctx, msg)
|
||||
return
|
||||
}
|
||||
|
||||
self.SetStageComplete(ctx, nil)
|
||||
}
|
||||
@@ -31,6 +31,20 @@ func (self *GuestDeleteTask) OnInit(ctx context.Context, obj db.IStandaloneModel
|
||||
|
||||
func (self *GuestDeleteTask) OnGuestStopComplete(ctx context.Context, obj db.IStandaloneModel, data jsonutils.JSONObject) {
|
||||
guest := obj.(*models.SGuest)
|
||||
|
||||
eip, _ := guest.GetEip()
|
||||
if eip != nil && eip.Mode != models.EIP_MODE_INSTANCE_PUBLICIP {
|
||||
// detach floating EIP only
|
||||
self.SetStage("on_eip_dissociate_complete", nil)
|
||||
eip.StartEipDissociateTask(ctx, self.UserCred, self.GetTaskId())
|
||||
} else {
|
||||
self.OnEipDissociateComplete(ctx, obj, nil)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *GuestDeleteTask) OnEipDissociateComplete(ctx context.Context, obj db.IStandaloneModel, data jsonutils.JSONObject) {
|
||||
guest := obj.(*models.SGuest)
|
||||
|
||||
if options.Options.EnablePendingDelete && !guest.PendingDeleted &&
|
||||
!jsonutils.QueryBoolean(self.Params, "purge", false) &&
|
||||
!jsonutils.QueryBoolean(self.Params, "override_pending_delete", false) {
|
||||
@@ -102,6 +116,7 @@ func (self *GuestDeleteTask) OnGuestDeleteComplete(ctx context.Context, obj db.I
|
||||
guest.LeaveAllGroups(self.UserCred)
|
||||
guest.DetachAllNetworks(ctx, self.UserCred)
|
||||
guest.EjectIso(self.UserCred)
|
||||
guest.DeleteEip(ctx, self.UserCred)
|
||||
guest.GetDriver().OnDeleteGuestFinalCleanup(ctx, guest, self.UserCred)
|
||||
self.DeleteGuest(ctx, guest)
|
||||
}
|
||||
|
||||
@@ -212,6 +212,7 @@ func ReportGeneralUsage(userCred mcclient.TokenCredential, rangeObj db.IStandalo
|
||||
IsolatedDeviceUsage(rangeObj, hostTypes),
|
||||
WireUsage(rangeObj, hostTypes),
|
||||
NetworkUsage(userCred, rangeObj),
|
||||
EipUsage(),
|
||||
)
|
||||
|
||||
return
|
||||
@@ -336,3 +337,13 @@ func IsolatedDeviceUsage(rangeObj db.IStandaloneModel, hostType []string) Usage
|
||||
count[prefix] = ret.Devices
|
||||
return count
|
||||
}
|
||||
|
||||
func EipUsage() Usage {
|
||||
eipUsage := models.ElasticipManager.TotalCount("")
|
||||
count := make(map[string]interface{})
|
||||
count["eip.all"] = eipUsage.Total()
|
||||
count["eip.public_ip"] = eipUsage.PublicIPCount
|
||||
count["eip.floating_ip"] = eipUsage.EIPCount
|
||||
count["eip.floating_ip.used"] = eipUsage.EIPUsedCount
|
||||
return count
|
||||
}
|
||||
@@ -11,7 +11,7 @@ func NewJsonClientError(code int, title string, msg string, error httputils.Erro
|
||||
return &err
|
||||
}
|
||||
|
||||
func errorMessage(msg string, params ...interface{}) (string, httputils.Error) {
|
||||
func errorMessage(msg string, params []interface{}) (string, httputils.Error) {
|
||||
fileds := make([]string, len(params))
|
||||
for i, v := range params {
|
||||
fileds[i] = fmt.Sprint(v)
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package modules
|
||||
|
||||
var (
|
||||
Elasticips ResourceManager
|
||||
)
|
||||
|
||||
func init() {
|
||||
Elasticips = NewComputeManager("eip", "eips",
|
||||
[]string{"ID", "Name", "IP_Addr", "Status",
|
||||
"Associate_Type", "Associate_ID",
|
||||
"Associate_Name",
|
||||
"Bandwidth", "Charge_Type",
|
||||
},
|
||||
[]string{})
|
||||
|
||||
registerCompute(&Elasticips)
|
||||
}
|
||||
@@ -50,7 +50,7 @@ var (
|
||||
func init() {
|
||||
Servers = ServerManager{NewComputeManager("server", "servers",
|
||||
[]string{"ID", "Name", "Billing_type",
|
||||
"IPs", "Disk", "Status",
|
||||
"IPs", "EIP", "Disk", "Status",
|
||||
"vcpu_count", "vmem_size",
|
||||
"ext_bw", "Zone_name",
|
||||
"Secgroup", "Secgrp_id",
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package modules
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"yunion.io/x/jsonutils"
|
||||
"yunion.io/x/onecloud/pkg/mcclient"
|
||||
)
|
||||
|
||||
var (
|
||||
WebConsole WebConsoleManager
|
||||
)
|
||||
|
||||
func init() {
|
||||
WebConsole = WebConsoleManager{NewWebConsoleManager()}
|
||||
}
|
||||
|
||||
type WebConsoleManager struct {
|
||||
ResourceManager
|
||||
}
|
||||
|
||||
func NewWebConsoleManager() ResourceManager {
|
||||
return ResourceManager{BaseManager: BaseManager{serviceType: "webconsole"},
|
||||
Keyword: "webconsole", KeywordPlural: "webconsole"}
|
||||
}
|
||||
|
||||
func (m WebConsoleManager) DoConnect(
|
||||
s *mcclient.ClientSession,
|
||||
connType, id, action string,
|
||||
params jsonutils.JSONObject,
|
||||
) (jsonutils.JSONObject, error) {
|
||||
if len(connType) == 0 {
|
||||
return nil, fmt.Errorf("Empty connection resource type")
|
||||
}
|
||||
url := fmt.Sprintf("/webconsole/%s", connType)
|
||||
if id != "" {
|
||||
url = fmt.Sprintf("%s/%s", url, id)
|
||||
}
|
||||
if action != "" {
|
||||
url = fmt.Sprintf("%s/%s", url, action)
|
||||
}
|
||||
return m._post(s, url, params, "webconsole")
|
||||
}
|
||||
|
||||
func (m WebConsoleManager) DoK8sConnect(
|
||||
s *mcclient.ClientSession,
|
||||
id, action string,
|
||||
params jsonutils.JSONObject,
|
||||
) (jsonutils.JSONObject, error) {
|
||||
return m.DoConnect(s, "k8s", id, action, params)
|
||||
}
|
||||
|
||||
func (m WebConsoleManager) DoK8sShellConnect(
|
||||
s *mcclient.ClientSession,
|
||||
id string, params jsonutils.JSONObject,
|
||||
) (jsonutils.JSONObject, error) {
|
||||
return m.DoK8sConnect(s, id, "shell", params)
|
||||
}
|
||||
|
||||
func (m WebConsoleManager) DoK8sLogConnect(
|
||||
s *mcclient.ClientSession,
|
||||
id string, params jsonutils.JSONObject,
|
||||
) (jsonutils.JSONObject, error) {
|
||||
return m.DoK8sConnect(s, id, "log", params)
|
||||
}
|
||||
@@ -146,7 +146,7 @@ type BaseListOptions struct {
|
||||
Offset *int `default:"0" help:"Page offset"`
|
||||
OrderBy []string `help:"Name of the field to be ordered by"`
|
||||
Order string `help:"List order" choices:"desc|asc"`
|
||||
Details *bool `help:"Show more details"`
|
||||
Details *bool `help:"Show more details" default:"false"`
|
||||
Search string `help:"Filter results by a simple keyword search"`
|
||||
Meta *bool `help:"Piggyback metadata information"`
|
||||
Filter []string `help:"Filters"`
|
||||
|
||||
@@ -20,6 +20,8 @@ type ServerListOptions struct {
|
||||
AdminSecgroup string `help:"AdminSecgroup ID or Name"`
|
||||
Hypervisor string `help:"Show server of hypervisor" choices:"kvm|esxi|container|baremetal|aliyun|azure"`
|
||||
Manager string `help:"Show servers imported from manager"`
|
||||
Region string `help:"Show servers in cloudregion"`
|
||||
|
||||
BaseListOptions
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package options
|
||||
|
||||
import (
|
||||
"yunion.io/x/jsonutils"
|
||||
)
|
||||
|
||||
type WebConsoleFrontendOptions struct {
|
||||
WebUrl string `help:"Frontend terminal HTML web url" short-token:"w"`
|
||||
}
|
||||
|
||||
type PodBaseOptions struct {
|
||||
WebConsoleFrontendOptions
|
||||
NAME string `help:"Name of k8s pod to connect"`
|
||||
Namespace string `help:"Namespace of this pod"`
|
||||
Container string `help:"Container in this pod"`
|
||||
Cluster string `default:"$K8S_CLUSTER|default" help:"Kubernetes cluster name"`
|
||||
}
|
||||
|
||||
func (opt *PodBaseOptions) Params() (*jsonutils.JSONDict, error) {
|
||||
return StructToParams(opt)
|
||||
}
|
||||
|
||||
type PodShellOptions struct {
|
||||
PodBaseOptions
|
||||
}
|
||||
|
||||
type PodLogOptoins struct {
|
||||
PodBaseOptions
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
package aliyun
|
||||
|
||||
import (
|
||||
"time"
|
||||
"yunion.io/x/log"
|
||||
"fmt"
|
||||
|
||||
"yunion.io/x/pkg/utils"
|
||||
"yunion.io/x/jsonutils"
|
||||
|
||||
"yunion.io/x/onecloud/pkg/cloudprovider"
|
||||
"yunion.io/x/onecloud/pkg/compute/models"
|
||||
)
|
||||
|
||||
type TInternetChargeType string
|
||||
|
||||
const (
|
||||
InternetChargeByTraffic = TInternetChargeType("PayByTraffic")
|
||||
InternetChargeByBandwidth = TInternetChargeType("PayByBandwidth")
|
||||
)
|
||||
|
||||
const (
|
||||
EIP_STATUS_ASSOCIATING = "Associating"
|
||||
EIP_STATUS_UNASSOCIATING = "Unassociating"
|
||||
EIP_STATUS_INUSE = "InUse"
|
||||
EIP_STATUS_AVAILABLE = "Available"
|
||||
|
||||
EIP_OPERATION_LOCK_FINANCIAL = "financial"
|
||||
EIP_OPERATION_LOCK_SECURITY = "security"
|
||||
|
||||
|
||||
EIP_INSTANCE_TYPE_ECS = "EcsInstance" // (默认值):VPC类型的ECS实例
|
||||
EIP_INTANNCE_TYPE_SLB = "SlbInstance" // :VPC类型的SLB实例
|
||||
EIP_INSTANCE_TYPE_NAT = "Nat" // :NAT网关
|
||||
EIP_INSTANCE_TYPE_HAVIP = "HaVip" // :HAVIP
|
||||
)
|
||||
|
||||
type SEipAddress struct {
|
||||
region *SRegion
|
||||
|
||||
AllocationId string
|
||||
|
||||
InternetChargeType string
|
||||
|
||||
IpAddress string
|
||||
Status string
|
||||
|
||||
InstanceType string
|
||||
InstanceId string
|
||||
Bandwidth int /* Mbps */
|
||||
|
||||
AllocationTime time.Time
|
||||
|
||||
OperationLocks string
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetId() string {
|
||||
return self.AllocationId
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetName() string {
|
||||
return self.IpAddress
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetGlobalId() string {
|
||||
return self.AllocationId
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetStatus() string {
|
||||
switch self.Status {
|
||||
case EIP_STATUS_AVAILABLE, EIP_STATUS_INUSE:
|
||||
return models.EIP_STATUS_READY
|
||||
case EIP_STATUS_ASSOCIATING:
|
||||
return models.EIP_STATUS_ASSOCIATE
|
||||
case EIP_STATUS_UNASSOCIATING:
|
||||
return models.EIP_STATUS_DISSOCIATE
|
||||
default:
|
||||
return models.EIP_STATUS_UNKNOWN
|
||||
}
|
||||
}
|
||||
|
||||
func (self *SEipAddress) Refresh() error {
|
||||
if self.IsEmulated() {
|
||||
return nil
|
||||
}
|
||||
new, err := self.region.GetEip(self.AllocationId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return jsonutils.Update(self, new)
|
||||
}
|
||||
|
||||
func (self *SEipAddress) IsEmulated() bool {
|
||||
if self.AllocationId == self.InstanceId {
|
||||
// fixed Public IP
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetMetadata() *jsonutils.JSONDict {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetIpAddr() string {
|
||||
return self.IpAddress
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetMode() string {
|
||||
if self.InstanceId == self.AllocationId {
|
||||
return models.EIP_MODE_INSTANCE_PUBLICIP
|
||||
} else {
|
||||
return models.EIP_MODE_STANDALONE_EIP
|
||||
}
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetAssociationType() string {
|
||||
switch self.InstanceType {
|
||||
case EIP_INSTANCE_TYPE_ECS:
|
||||
return "server"
|
||||
default:
|
||||
log.Fatalf("unsupported type: %s", self.InstanceType)
|
||||
return "unsupported"
|
||||
}
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetAssociationExternalId() string {
|
||||
return self.InstanceId
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetManagerId() string {
|
||||
return self.region.client.providerId
|
||||
}
|
||||
|
||||
func (self *SEipAddress) Delete() error {
|
||||
return self.region.DeallocateEIP(self.AllocationId)
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetBandwidth() int {
|
||||
return self.Bandwidth
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetInternetChargeType() string {
|
||||
switch self.InternetChargeType {
|
||||
case string(InternetChargeByTraffic):
|
||||
return models.EIP_CHARGE_TYPE_BY_TRAFFIC
|
||||
case string(InternetChargeByBandwidth):
|
||||
return models.EIP_CHARGE_TYPE_BY_BANDWIDTH
|
||||
default:
|
||||
return models.EIP_CHARGE_TYPE_BY_TRAFFIC
|
||||
}
|
||||
}
|
||||
|
||||
func (self *SEipAddress) Associate(instanceId string) error {
|
||||
err := self.region.AssociateEip(self.AllocationId, instanceId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = cloudprovider.WaitStatus(self, models.EIP_STATUS_READY, 10*time.Second, 180*time.Second)
|
||||
return err
|
||||
}
|
||||
|
||||
func (self *SEipAddress) Dissociate() error {
|
||||
err := self.region.DissociateEip(self.AllocationId, self.InstanceId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = cloudprovider.WaitStatus(self, models.EIP_STATUS_READY, 10*time.Second, 180*time.Second)
|
||||
return err
|
||||
}
|
||||
|
||||
func (self *SEipAddress) ChangeBandwidth(bw int) error {
|
||||
return self.region.UpdateEipBandwidth(self.AllocationId, bw)
|
||||
}
|
||||
|
||||
func (region *SRegion) GetEips(eipId string, offset int, limit int) ([]SEipAddress, int, error) {
|
||||
if limit > 50 || limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
|
||||
params := make(map[string]string)
|
||||
params["RegionId"] = region.RegionId
|
||||
params["PageSize"] = fmt.Sprintf("%d", limit)
|
||||
params["PageNumber"] = fmt.Sprintf("%d", (offset/limit)+1)
|
||||
|
||||
if len(eipId) > 0 {
|
||||
params["AllocationId"] = eipId
|
||||
}
|
||||
|
||||
body, err := region.ecsRequest("DescribeEipAddresses", params)
|
||||
if err != nil {
|
||||
log.Errorf("DescribeEipAddresses fail %s", err)
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// log.Errorf("%s", body)
|
||||
|
||||
eips := make([]SEipAddress, 0)
|
||||
err = body.Unmarshal(&eips, "EipAddresses", "EipAddress")
|
||||
if err != nil {
|
||||
log.Errorf("Unmarshal EipAddress details fail %s", err)
|
||||
return nil, 0, err
|
||||
}
|
||||
total, _ := body.Int("TotalCount")
|
||||
for i := 0; i < len(eips); i += 1 {
|
||||
eips[i].region = region
|
||||
}
|
||||
return eips, int(total), nil
|
||||
}
|
||||
|
||||
func (region *SRegion) GetEip(eipId string) (*SEipAddress, error) {
|
||||
eips, total, err := region.GetEips(eipId, 0, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if total != 1 {
|
||||
return nil, cloudprovider.ErrNotFound
|
||||
}
|
||||
return &eips[0], nil
|
||||
}
|
||||
|
||||
func (region *SRegion) AllocateEIP(bwMbps int, chargeType TInternetChargeType) (*SEipAddress, error) {
|
||||
params := make(map[string]string)
|
||||
|
||||
params["Bandwidth"] = fmt.Sprintf("%d", bwMbps)
|
||||
params["InternetChargeType"] = string(chargeType)
|
||||
params["InstanceChargeType"] = "PostPaid"
|
||||
params["ClientToken"] = utils.GenRequestId(20)
|
||||
|
||||
body, err := region.ecsRequest("AllocateEipAddress", params)
|
||||
if err != nil {
|
||||
log.Errorf("AllocateEipAddress fail %s", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
eipId, err := body.GetString("AllocationId")
|
||||
if err != nil {
|
||||
log.Errorf("fail to get AllocationId after EIP allocation??? %s", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return region.GetEip(eipId)
|
||||
}
|
||||
|
||||
func (region *SRegion) CreateEIP(bwMbps int) (cloudprovider.ICloudEIP, error) {
|
||||
eip, err := region.AllocateEIP(bwMbps, InternetChargeByTraffic)
|
||||
return eip, err
|
||||
}
|
||||
|
||||
func (region *SRegion) DeallocateEIP(eipId string) (error) {
|
||||
params := make(map[string]string)
|
||||
params["AllocationId"] = eipId
|
||||
|
||||
_, err := region.ecsRequest("ReleaseEipAddress", params)
|
||||
if err != nil {
|
||||
log.Errorf("ReleaseEipAddress fail %s", err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (region *SRegion) AssociateEip(eipId string, instanceId string) (error) {
|
||||
params := make(map[string]string)
|
||||
params["AllocationId"] = eipId
|
||||
params["InstanceId"] = instanceId
|
||||
|
||||
_, err := region.ecsRequest("AssociateEipAddress", params)
|
||||
if err != nil {
|
||||
log.Errorf("AssociateEipAddress fail %s", err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (region *SRegion) DissociateEip(eipId string, instanceId string) (error) {
|
||||
params := make(map[string]string)
|
||||
params["AllocationId"] = eipId
|
||||
params["InstanceId"] = instanceId
|
||||
|
||||
_, err := region.ecsRequest("UnassociateEipAddress", params)
|
||||
if err != nil {
|
||||
log.Errorf("UnassociateEipAddress fail %s", err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (region *SRegion) UpdateEipBandwidth(eipId string, bw int) error {
|
||||
params := make(map[string]string)
|
||||
params["AllocationId"] = eipId
|
||||
params["Bandwidth"] = fmt.Sprintf("%d", bw)
|
||||
|
||||
_, err := region.ecsRequest("ModifyEipAddressAttribute", params)
|
||||
if err != nil {
|
||||
log.Errorf("ModifyEipAddressAttribute fail %s", err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
+20
-22
@@ -34,24 +34,6 @@ type SDedicatedHostAttribute struct {
|
||||
DedicatedHostName string
|
||||
}
|
||||
|
||||
type SEipAddress struct {
|
||||
AllocationId string
|
||||
InternetChargeType string
|
||||
IpAddress string
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetIP() string {
|
||||
return self.IpAddress
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetAllocationId() string {
|
||||
return self.AllocationId
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetChargeType() string {
|
||||
return self.GetChargeType()
|
||||
}
|
||||
|
||||
type SIpAddress struct {
|
||||
IpAddress []string
|
||||
}
|
||||
@@ -247,10 +229,6 @@ func (self *SInstance) GetINics() ([]cloudprovider.ICloudNic, error) {
|
||||
return nics, nil
|
||||
}
|
||||
|
||||
func (self *SInstance) GetEIP() cloudprovider.ICloudEIP {
|
||||
return &self.EipAddress
|
||||
}
|
||||
|
||||
func (self *SInstance) GetVcpuCount() int8 {
|
||||
return self.Cpu
|
||||
}
|
||||
@@ -723,3 +701,23 @@ func (self *SInstance) SyncSecurityGroup(secgroupId string, name string, rules [
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SInstance) GetIEIP() (cloudprovider.ICloudEIP, error) {
|
||||
if len(self.PublicIpAddress.IpAddress) > 0 {
|
||||
eip := SEipAddress{}
|
||||
eip.region = self.host.zone.region
|
||||
eip.IpAddress = self.PublicIpAddress.IpAddress[0]
|
||||
eip.InstanceId = self.InstanceId
|
||||
eip.InstanceType = EIP_INSTANCE_TYPE_ECS
|
||||
eip.Status = EIP_STATUS_INUSE
|
||||
eip.AllocationId = self.InstanceId // fixed
|
||||
eip.AllocationTime = self.CreationTime
|
||||
eip.Bandwidth = self.InternetMaxBandwidthOut
|
||||
eip.InternetChargeType = self.InternetChargeType
|
||||
return &eip, nil
|
||||
} else if len(self.EipAddress.IpAddress) > 0 {
|
||||
return self.host.zone.region.GetEip(self.EipAddress.AllocationId)
|
||||
} else {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
@@ -570,3 +570,37 @@ func (self *SRegion) updateInstance(instId string, name, desc, passwd, hostname
|
||||
func (self *SRegion) UpdateInstancePassword(instId string, passwd string) error {
|
||||
return self.updateInstance(instId, "", "", passwd, "")
|
||||
}
|
||||
|
||||
func (self *SRegion) GetIEips() ([]cloudprovider.ICloudEIP, error) {
|
||||
eips, total, err := self.GetEips("", 0, 50)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for len(eips) < total {
|
||||
var parts []SEipAddress
|
||||
parts, total, err = self.GetEips("", len(eips), 50)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
eips = append(eips, parts...)
|
||||
}
|
||||
ret := make([]cloudprovider.ICloudEIP, len(eips))
|
||||
for i := 0; i < len(eips); i += 1 {
|
||||
ret[i] = &eips[i]
|
||||
}
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
func (self *SRegion) GetIEipById(eipId string) (cloudprovider.ICloudEIP, error) {
|
||||
eips, total, err := self.GetEips(eipId, 0, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if total == 0 {
|
||||
return nil, cloudprovider.ErrNotFound
|
||||
}
|
||||
if total > 1 {
|
||||
return nil, cloudprovider.ErrDuplicateId
|
||||
}
|
||||
return &eips[0], nil
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package shell
|
||||
|
||||
import (
|
||||
"yunion.io/x/onecloud/pkg/util/aliyun"
|
||||
"yunion.io/x/onecloud/pkg/util/shellutils"
|
||||
)
|
||||
|
||||
func init() {
|
||||
type EipListOptions struct {
|
||||
Offset int `help:"List offset"`
|
||||
Limit int `help:"List limit"`
|
||||
}
|
||||
shellutils.R(&EipListOptions{}, "eip-list", "List eips", func(cli *aliyun.SRegion, args *EipListOptions) error {
|
||||
eips, total, e := cli.GetEips("", args.Offset, args.Limit)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
printList(eips, total, args.Offset, args.Limit, []string{})
|
||||
return nil
|
||||
})
|
||||
|
||||
type EipAllocateOptions struct {
|
||||
BW int `help:"Bandwidth limit in Mbps"`
|
||||
}
|
||||
shellutils.R(&EipAllocateOptions{}, "eip-create", "Allocate an EIP", func(cli *aliyun.SRegion, args *EipAllocateOptions) error {
|
||||
eip, err := cli.AllocateEIP(args.BW, aliyun.InternetChargeByTraffic)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
printObject(eip)
|
||||
return nil
|
||||
})
|
||||
|
||||
type EipReleaseOptions struct {
|
||||
ID string `help:"EIP allocation ID"`
|
||||
}
|
||||
shellutils.R(&EipReleaseOptions{}, "eip-delete", "Release an EIP", func(cli *aliyun.SRegion, args *EipReleaseOptions) error {
|
||||
err := cli.DeallocateEIP(args.ID)
|
||||
return err
|
||||
})
|
||||
|
||||
type EipAssociateOptions struct {
|
||||
ID string `help:"EIP allocation ID"`
|
||||
INSTANCE string `help:"Instance ID"`
|
||||
}
|
||||
shellutils.R(&EipAssociateOptions{}, "eip-associate", "Associate an EIP", func(cli *aliyun.SRegion, args *EipAssociateOptions) error {
|
||||
err := cli.AssociateEip(args.ID, args.INSTANCE)
|
||||
return err
|
||||
})
|
||||
shellutils.R(&EipAssociateOptions{}, "eip-dissociate", "Dissociate an EIP", func(cli *aliyun.SRegion, args *EipAssociateOptions) error {
|
||||
err := cli.DissociateEip(args.ID, args.INSTANCE)
|
||||
return err
|
||||
})
|
||||
}
|
||||
+23
-8
@@ -25,13 +25,28 @@ const (
|
||||
AZURE_API_VERSION = "2018-04-01"
|
||||
)
|
||||
|
||||
var DefaultResourceGroup = map[string]string{
|
||||
"disk": "YunionDiskResource",
|
||||
"instance": "YunionInstanceResource",
|
||||
"vpc": "YunionVpcResource",
|
||||
"network": "YunionNetworkResource",
|
||||
"image": "YunionImageResource",
|
||||
"storage": "YunionStorageResource",
|
||||
const (
|
||||
DISK_RESOURCE = "disk"
|
||||
INSTANCE_RESOURCE = "instance"
|
||||
VPC_RESOURCE = "vpc"
|
||||
NETWORK_RESOURCE = "network"
|
||||
NIC_RESOURCE = "nic"
|
||||
IMAGE_RESOURCE = "image"
|
||||
STORAGE_RESOURCE = "storage"
|
||||
SECGRP_RESOURCE = "secgroup"
|
||||
EIP_RESOURCE = "eip"
|
||||
)
|
||||
|
||||
var DefaultResourceGroups = map[string]string{
|
||||
DISK_RESOURCE: "YunionDiskResource",
|
||||
INSTANCE_RESOURCE: "YunionInstanceResource",
|
||||
VPC_RESOURCE: "YunionVpcResource",
|
||||
NETWORK_RESOURCE: "YunionNetworkResource",
|
||||
NIC_RESOURCE: "YunionNicInterface",
|
||||
IMAGE_RESOURCE: "YunionImageResource",
|
||||
STORAGE_RESOURCE: "YunionStorageResource",
|
||||
SECGRP_RESOURCE: "YunionSecgrpResource",
|
||||
EIP_RESOURCE: "YunionEipResource",
|
||||
}
|
||||
|
||||
type SAzureClient struct {
|
||||
@@ -98,7 +113,7 @@ func (self *SAzureClient) createResourceGroup(resourceGruop string) error {
|
||||
}
|
||||
|
||||
func (self *SAzureClient) fetchAzueResourceGroup() error {
|
||||
for _, value := range DefaultResourceGroup {
|
||||
for _, value := range DefaultResourceGroups {
|
||||
if exist, err := self.isResourceGroupExist(value); err != nil {
|
||||
log.Errorf("Check ResourceGroup error: %v", err)
|
||||
} else if !exist {
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
package azure
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"yunion.io/x/jsonutils"
|
||||
)
|
||||
|
||||
type SStorageAccount struct {
|
||||
region *SRegion
|
||||
}
|
||||
|
||||
func (self *SStorageAccount) GetMetadata() *jsonutils.JSONDict {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SStorageAccount) GetId() string {
|
||||
return fmt.Sprintf("%s-%s", self.region.client.providerId, self.region.GetId())
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package concurrent
|
||||
|
||||
import (
|
||||
"container/heap"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Balancer is a type that can balance load among a set of workers
|
||||
//
|
||||
type Balancer struct {
|
||||
errorChan chan error // The channel used by all workers to report error
|
||||
requestHandledChan chan *Worker // The channel used by a worker to signal balancer that a work has been executed
|
||||
tearDownChan chan bool // The channel that all workers listening for force quit signal
|
||||
workerFinishedChan chan *Worker // The channel that all worker used to signal balancer that it exiting
|
||||
allWorkersFinishedChan chan bool // The channel this balancer signals once all worker signals it's exit on workerFinishedChan
|
||||
pool Pool // Pool of workers that this load balancer balances
|
||||
workerCount int // The number of workers
|
||||
}
|
||||
|
||||
// The size of work channel associated with each worker this balancer manages.
|
||||
//
|
||||
const workerQueueSize int = 3
|
||||
|
||||
// NewBalancer creates a new instance of Balancer that needs to balance load between 'workerCount' workers
|
||||
//
|
||||
func NewBalancer(workerCount int) *Balancer {
|
||||
balancer := &Balancer{
|
||||
workerCount: workerCount,
|
||||
pool: Pool{
|
||||
Workers: make([]*Worker, workerCount),
|
||||
},
|
||||
}
|
||||
return balancer
|
||||
}
|
||||
|
||||
// Init initializes all channels and start the workers.
|
||||
//
|
||||
func (b *Balancer) Init() {
|
||||
b.errorChan = make(chan error, 0)
|
||||
b.requestHandledChan = make(chan *Worker, 0)
|
||||
b.workerFinishedChan = make(chan *Worker, 0)
|
||||
b.allWorkersFinishedChan = make(chan bool, 0)
|
||||
b.tearDownChan = make(chan bool, 0)
|
||||
for i := 0; i < b.workerCount; i++ {
|
||||
b.pool.Workers[i] = NewWorker(i, workerQueueSize, &(b.pool), b.errorChan, b.requestHandledChan, b.workerFinishedChan)
|
||||
(b.pool.Workers[i]).Run(b.tearDownChan)
|
||||
}
|
||||
}
|
||||
|
||||
// TearDownWorkers sends a force quit signal to all workers, which case worker to quit as soon as possible,
|
||||
// workers won't drain it's request channel in this case.
|
||||
//
|
||||
func (b *Balancer) TearDownWorkers() {
|
||||
close(b.tearDownChan)
|
||||
}
|
||||
|
||||
// Run read request from the request channel identified by the parameter requestChan and dispatch it the worker
|
||||
// with least load. This method returns two channels, a channel to communicate error from any worker back to
|
||||
// the consumer of balancer and second channel is used by the balancer to signal consumer that all workers has
|
||||
// been finished executing.
|
||||
//
|
||||
func (b *Balancer) Run(requestChan <-chan *Request) (<-chan error, <-chan bool) {
|
||||
// Request dispatcher
|
||||
go func() {
|
||||
for {
|
||||
requestToHandle, ok := <-requestChan
|
||||
if !ok {
|
||||
b.closeWorkersRequestChannel()
|
||||
return
|
||||
}
|
||||
b.dispatch(requestToHandle)
|
||||
}
|
||||
}()
|
||||
|
||||
// listener for worker status
|
||||
go func() {
|
||||
remainingWorkers := b.workerCount
|
||||
for {
|
||||
select {
|
||||
case w := <-b.requestHandledChan:
|
||||
b.completed(w)
|
||||
case _ = <-b.workerFinishedChan:
|
||||
remainingWorkers--
|
||||
if remainingWorkers == 0 {
|
||||
b.allWorkersFinishedChan <- true // All workers has been exited
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return b.errorChan, b.allWorkersFinishedChan
|
||||
}
|
||||
|
||||
// closeWorkersRequestChannel closes the Request channel of all workers, this indicates that no
|
||||
// more work will not be send the channel so that the workers can gracefully exit after handling
|
||||
// any pending work in the channel.
|
||||
//
|
||||
func (b *Balancer) closeWorkersRequestChannel() {
|
||||
for i := 0; i < b.workerCount; i++ {
|
||||
close((b.pool.Workers[i]).RequestsToHandleChan)
|
||||
}
|
||||
}
|
||||
|
||||
// dispatch dispatches the request to the worker with least load. If all workers are completely
|
||||
// busy (i.e. there Pending request count is currently equal to the maximum load) then this
|
||||
// method will poll until one worker is available.
|
||||
//
|
||||
func (b *Balancer) dispatch(request *Request) {
|
||||
for {
|
||||
if b.pool.Workers[0].Pending >= workerQueueSize {
|
||||
// Wait for a worker to be available
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
} else {
|
||||
b.pool.Lock()
|
||||
worker := b.pool.Workers[0]
|
||||
worker.Pending++
|
||||
heap.Fix(&b.pool, worker.Index)
|
||||
worker.RequestsToHandleChan <- request
|
||||
b.pool.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// completed is called when a worker finishes one work, it updates the load status of the given the
|
||||
// worker.
|
||||
//
|
||||
func (b *Balancer) completed(worker *Worker) {
|
||||
b.pool.Lock()
|
||||
worker.Pending--
|
||||
heap.Fix(&b.pool, worker.Index)
|
||||
b.pool.Unlock()
|
||||
}
|
||||
|
||||
// WorkersCurrentLoad returns the load of the workers this balancer manages as comma separated string
|
||||
// values where each value consists of worker id (Worker.Id property) and pending requests associated
|
||||
// with the worker.
|
||||
//
|
||||
func (b *Balancer) WorkersCurrentLoad() string {
|
||||
return b.pool.WorkersCurrentLoad()
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package concurrent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Pool is the collection of Worker, it is a min-heap that implements heap.Interface.
|
||||
// The priority is the number of pending works assigned to the worker. Lower the pending
|
||||
// work count higher the priority. Pool embeds sync.RWMutex to support concurrent heap
|
||||
// operation.
|
||||
//
|
||||
type Pool struct {
|
||||
sync.RWMutex // If consumer want to use workers in a concurrent environment
|
||||
Workers []*Worker // The workers
|
||||
}
|
||||
|
||||
// Len returns number of workers in the pool.
|
||||
//
|
||||
func (p *Pool) Len() int {
|
||||
return len(p.Workers)
|
||||
}
|
||||
|
||||
// Less returns true if priority of Worker instance at index i is less than priority of Worker
|
||||
// instance at j, lower the pending value higher the priority
|
||||
//
|
||||
func (p *Pool) Less(i, j int) bool {
|
||||
return p.Workers[i].Pending < p.Workers[j].Pending
|
||||
}
|
||||
|
||||
// Swap swaps the Worker instances at the given indices i and j
|
||||
//
|
||||
func (p *Pool) Swap(i, j int) {
|
||||
p.Workers[i], p.Workers[j] = p.Workers[j], p.Workers[i]
|
||||
p.Workers[i].Index = i
|
||||
p.Workers[j].Index = j
|
||||
}
|
||||
|
||||
// Push is used by heap.Push implementation, to add a worker w to a Pool pool, we call
|
||||
// heap.Push(&pool, w) which invokes this method to add the worker to the end of collection
|
||||
// then it fix the heap by moving the added item to its correct position.
|
||||
//
|
||||
func (p *Pool) Push(x interface{}) {
|
||||
n := len(p.Workers)
|
||||
worker := x.(*Worker)
|
||||
worker.Index = n
|
||||
(*p).Workers = append((*p).Workers, worker)
|
||||
}
|
||||
|
||||
// Pop is used by heap.Pop implementation, to pop a worker w with minimum priority from a Pool
|
||||
// p, we call w := heap.Pop(&p).(*Worker), which swap the min priority worker at the beginning
|
||||
// of the pool with the end of item, fix the heap and then invokes this method for popping the
|
||||
// worker from the end.
|
||||
//
|
||||
func (p *Pool) Pop() interface{} {
|
||||
n := len(p.Workers)
|
||||
w := (*p).Workers[n-1]
|
||||
w.Index = -1
|
||||
(*p).Workers = (*p).Workers[0 : n-1]
|
||||
return w
|
||||
}
|
||||
|
||||
// WorkersCurrentLoad returns the load of the workers as comma separated string values, where
|
||||
// each value consists of worker id (Worker.Id property) and pending requests associated with
|
||||
// the worker.
|
||||
//
|
||||
func (p *Pool) WorkersCurrentLoad() string {
|
||||
var buffer bytes.Buffer
|
||||
buffer.WriteString("Load [")
|
||||
for _, w := range p.Workers {
|
||||
buffer.WriteString(fmt.Sprintf("%d:%d, ", w.ID, w.Pending))
|
||||
}
|
||||
buffer.WriteString("]")
|
||||
return buffer.String()
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package concurrent
|
||||
|
||||
// Request represents a work that Worker needs to execute
|
||||
//
|
||||
type Request struct {
|
||||
ID string // The Id of the work (for debugging purposes)
|
||||
Work func() error // The work to be executed by a worker
|
||||
ShouldRetry func(err error) bool // The method used by worker to decide whether to retry if work execution fails
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package concurrent
|
||||
|
||||
import "fmt"
|
||||
|
||||
// Worker represents a type which can listen for work from a channel and run them
|
||||
//
|
||||
type Worker struct {
|
||||
RequestsToHandleChan chan *Request // The buffered channel of works this worker needs to handle
|
||||
Pending int // The number of pending requests this worker needs to handle (i.e. worker load)
|
||||
errorChan chan<- error // The channel to report failure in executing work
|
||||
requestHandledChan chan<- *Worker // The channel to report that a work is done (irrespective of success or failure)
|
||||
workerFinishedChan chan<- *Worker // The channel to signal that worker has finished (worker go-routine exited)
|
||||
ID int // Unique Id for worker (Debugging purpose)
|
||||
Index int // The index of the item in the heap.
|
||||
pool *Pool // The parent pool holding all workers (used for work stealing)
|
||||
}
|
||||
|
||||
// The maximum number of times a work needs to be retried before reporting failure on errorChan.
|
||||
//
|
||||
const maxRetryCount int = 5
|
||||
|
||||
// NewWorker creates a new instance of the worker with the given work channel size.
|
||||
// errorChan is the channel to report the failure in addressing a work request after all
|
||||
// retries, each time a work is completed (failure or success) doneChan will be signalled
|
||||
//
|
||||
func NewWorker(id int, workChannelSize int, pool *Pool, errorChan chan<- error, requestHandledChan chan<- *Worker, workerFinishedChan chan<- *Worker) *Worker {
|
||||
return &Worker{
|
||||
ID: id,
|
||||
RequestsToHandleChan: make(chan *Request, workChannelSize),
|
||||
errorChan: errorChan,
|
||||
requestHandledChan: requestHandledChan,
|
||||
workerFinishedChan: workerFinishedChan,
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
// Run starts a go-routine that read work from work-queue associated with the worker and executes one
|
||||
// at a time. The go-routine returns/exit once one of the following condition is met:
|
||||
// 1. The work-queue is closed and drained and there is no work to steal from peers worker's work-queue
|
||||
// 2. A signal is received in the tearDownChan channel parameter
|
||||
//
|
||||
// After executing each work, this method sends report to Worker::requestHandledChan channel
|
||||
// If a work fails after maximum retry, this method sends report to Worker::errorChan channel
|
||||
//
|
||||
func (w *Worker) Run(tearDownChan <-chan bool) {
|
||||
go func() {
|
||||
defer func() {
|
||||
// Signal balancer that worker is finished
|
||||
w.workerFinishedChan <- w
|
||||
}()
|
||||
|
||||
var requestToHandle *Request
|
||||
var ok bool
|
||||
for {
|
||||
select {
|
||||
case requestToHandle, ok = <-w.RequestsToHandleChan:
|
||||
if !ok {
|
||||
// Request channel is closed and drained, worker can try to steal work from others.
|
||||
//
|
||||
// Note: load balancer does not play any role in stealing, load balancer closes send-end
|
||||
// of all worker queue's at the same time, at this point we are sure that no more new job
|
||||
// will be scheduled. Once we start stealing "Worker::Pending" won't reflect correct load.
|
||||
requestToHandle = w.tryStealWork()
|
||||
if requestToHandle == nil {
|
||||
// Could not steal then return
|
||||
return
|
||||
}
|
||||
}
|
||||
case <-tearDownChan:
|
||||
// immediate stop, no need to drain the request channel
|
||||
return
|
||||
}
|
||||
|
||||
var err error
|
||||
// Do work, retry on failure.
|
||||
Loop:
|
||||
for count := 0; count < maxRetryCount+1; count++ {
|
||||
select {
|
||||
case <-tearDownChan:
|
||||
return
|
||||
default:
|
||||
err = requestToHandle.Work() // Run work
|
||||
if err == nil || !requestToHandle.ShouldRetry(err) {
|
||||
break Loop
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
select {
|
||||
case w.errorChan <- fmt.Errorf("%s: %v", requestToHandle.ID, err):
|
||||
case <-tearDownChan:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
select {
|
||||
case w.requestHandledChan <- w: // One work finished (successfully or unsuccessfully)
|
||||
case <-tearDownChan:
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// tryStealWork will try to steal a work from peer worker if available. If all peer channels are
|
||||
// empty then return nil
|
||||
//
|
||||
func (w *Worker) tryStealWork() *Request {
|
||||
for _, w1 := range w.pool.Workers {
|
||||
request, ok := <-w1.RequestsToHandleChan
|
||||
if ok {
|
||||
return request
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -54,8 +54,6 @@ const DiskResourceGroup = "YunionDiskResource"
|
||||
type SDisk struct {
|
||||
storage *SStorage
|
||||
|
||||
ResourceGroup string
|
||||
|
||||
ManagedBy string
|
||||
Sku DiskSku
|
||||
Zones []string
|
||||
@@ -78,7 +76,8 @@ func (self *SRegion) createDisk(storageType string, name string, sizeGb int32, d
|
||||
sku := compute.DiskSku{Name: compute.StorageAccountTypes(storageType)}
|
||||
properties := compute.DiskProperties{DiskSizeGB: &sizeGb, CreationData: &compute.CreationData{CreateOption: "Empty"}}
|
||||
disk := compute.Disk{Name: &name, Location: &self.Name, DiskProperties: &properties, Sku: &sku}
|
||||
if result, err := computeClient.CreateOrUpdate(context.Background(), DefaultResourceGroup["disk"], name, disk); err != nil {
|
||||
resourceGroup, diskName := PareResourceGroupWithName(name, DISK_RESOURCE)
|
||||
if result, err := computeClient.CreateOrUpdate(context.Background(), resourceGroup, diskName, disk); err != nil {
|
||||
return err
|
||||
} else if err := result.WaitForCompletion(context.Background(), computeClient.Client); err != nil {
|
||||
return err
|
||||
@@ -94,9 +93,8 @@ func (self *SRegion) DeleteDisk(diskId string) error {
|
||||
func (self *SRegion) deleteDisk(diskId string) error {
|
||||
diskClient := compute.NewDisksClientWithBaseURI(self.client.baseUrl, self.client.subscriptionId)
|
||||
diskClient.Authorizer = self.client.authorizer
|
||||
if resourceGroup, name, err := PareResourceGroupWithName(diskId); err != nil {
|
||||
return err
|
||||
} else if result, err := diskClient.Delete(context.Background(), resourceGroup, name); err != nil {
|
||||
resourceGroup, name := PareResourceGroupWithName(diskId, DISK_RESOURCE)
|
||||
if result, err := diskClient.Delete(context.Background(), resourceGroup, name); err != nil {
|
||||
return err
|
||||
} else if err := result.WaitForCompletion(context.Background(), diskClient.Client); err != nil {
|
||||
return err
|
||||
@@ -130,7 +128,6 @@ func (self *SRegion) GetDisks() ([]SDisk, error) {
|
||||
if err := jsonutils.Update(&disk, _disk); err != nil {
|
||||
return disks, err
|
||||
}
|
||||
disk.ResourceGroup, _, _ = PareResourceGroupWithName(disk.ID)
|
||||
disks = append(disks, disk)
|
||||
}
|
||||
}
|
||||
@@ -161,7 +158,8 @@ func (self *SRegion) getDisk(resourceGroup string, diskName string) (*SDisk, err
|
||||
}
|
||||
|
||||
func (self *SDisk) Refresh() error {
|
||||
if disk, err := self.storage.zone.region.GetDisk(self.ResourceGroup, self.Name); err != nil {
|
||||
resourceGropu, diskName := PareResourceGroupWithName(self.ID, DISK_RESOURCE)
|
||||
if disk, err := self.storage.zone.region.GetDisk(resourceGropu, diskName); err != nil {
|
||||
return cloudprovider.ErrNotFound
|
||||
} else {
|
||||
return jsonutils.Update(self, disk)
|
||||
@@ -185,7 +183,7 @@ func (self *SDisk) GetName() string {
|
||||
}
|
||||
|
||||
func (self *SDisk) GetGlobalId() string {
|
||||
resourceGroup, _, _ := PareResourceGroupWithName(self.ID)
|
||||
resourceGroup, _ := PareResourceGroupWithName(self.ID, DISK_RESOURCE)
|
||||
return fmt.Sprintf("resourceGroups/%s/providers/disk/%s", resourceGroup, self.Name)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
package azure
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-06-01/network"
|
||||
"yunion.io/x/jsonutils"
|
||||
"yunion.io/x/onecloud/pkg/cloudprovider"
|
||||
)
|
||||
|
||||
type PublicIPAddressSku struct {
|
||||
Name string
|
||||
}
|
||||
|
||||
type PublicIPAddressPropertiesFormat struct {
|
||||
PublicIPAddressVersion string
|
||||
IPAddress string
|
||||
PublicIPAllocationMethod string
|
||||
ProvisioningState string
|
||||
}
|
||||
|
||||
type SEipAddress struct {
|
||||
region *SRegion
|
||||
|
||||
ID string
|
||||
Name string
|
||||
Location string
|
||||
Properties PublicIPAddressPropertiesFormat
|
||||
Sku PublicIPAddressSku
|
||||
}
|
||||
|
||||
func (region *SRegion) CreateEIP(bwMbps int) (cloudprovider.ICloudEIP, error) {
|
||||
return nil, cloudprovider.ErrNotImplemented
|
||||
}
|
||||
|
||||
func (region *SRegion) GetIEips() ([]cloudprovider.ICloudEIP, error) {
|
||||
networkClient := network.NewPublicIPAddressesClientWithBaseURI(region.client.baseUrl, region.SubscriptionID)
|
||||
networkClient.Authorizer = region.client.authorizer
|
||||
if _eips, err := networkClient.ListAll(context.Background()); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
eips := make([]cloudprovider.ICloudEIP, len(_eips.Values()))
|
||||
for i := 0; i < len(eips); i++ {
|
||||
eip := SEipAddress{region: region}
|
||||
jsonutils.Update(&eip, _eips.Values()[i])
|
||||
eips[i] = &eip
|
||||
}
|
||||
return eips, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (region *SRegion) GetEip(eipId string) (*SEipAddress, error) {
|
||||
eip := SEipAddress{region: region}
|
||||
resourceGroup, eipName := PareResourceGroupWithName(eipId, EIP_RESOURCE)
|
||||
if len(eipName) == 0 {
|
||||
return nil, cloudprovider.ErrNotFound
|
||||
}
|
||||
networkClient := network.NewPublicIPAddressesClientWithBaseURI(region.client.baseUrl, region.SubscriptionID)
|
||||
networkClient.Authorizer = region.client.authorizer
|
||||
if result, err := networkClient.Get(context.Background(), resourceGroup, eipName, ""); err != nil {
|
||||
if result.Response.StatusCode == 404 {
|
||||
return nil, cloudprovider.ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
} else if err := jsonutils.Update(&eip, result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &eip, nil
|
||||
}
|
||||
|
||||
func (self *SEipAddress) Associate(instanceId string) error {
|
||||
if err := self.region.AssociateEip(self.ID, instanceId); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (region *SRegion) AssociateEip(eipId string, instanceId string) error {
|
||||
resourceGroup, instanceName := PareResourceGroupWithName(instanceId, INSTANCE_RESOURCE)
|
||||
if instance, err := region.GetInstance(resourceGroup, instanceName); err != nil {
|
||||
return err
|
||||
} else {
|
||||
nicId := instance.Properties.NetworkProfile.NetworkInterfaces[0].ID
|
||||
resourceGroup, nicName := PareResourceGroupWithName(nicId, NIC_RESOURCE)
|
||||
if nic, err := region.getNetworkInterface(resourceGroup, nicName); err != nil {
|
||||
return err
|
||||
} else {
|
||||
oldIPConf := nic.Properties.IPConfigurations[0]
|
||||
interfaceClinet := network.NewInterfacesClientWithBaseURI(region.client.baseUrl, region.SubscriptionID)
|
||||
interfaceClinet.Authorizer = region.client.authorizer
|
||||
InterfaceIPConfiguration := []network.InterfaceIPConfiguration{
|
||||
network.InterfaceIPConfiguration{
|
||||
Name: &nic.Name,
|
||||
InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
|
||||
Primary: &oldIPConf.Properties.Primary,
|
||||
PrivateIPAddress: &oldIPConf.Properties.PrivateIPAddress,
|
||||
PrivateIPAllocationMethod: network.Static,
|
||||
PublicIPAddress: &network.PublicIPAddress{ID: &eipId},
|
||||
Subnet: &network.Subnet{ID: &oldIPConf.Properties.Subnet.ID},
|
||||
},
|
||||
},
|
||||
}
|
||||
params := network.Interface{
|
||||
InterfacePropertiesFormat: &network.InterfacePropertiesFormat{
|
||||
IPConfigurations: &InterfaceIPConfiguration,
|
||||
},
|
||||
}
|
||||
if result, err := interfaceClinet.CreateOrUpdate(context.Background(), resourceGroup, nicName, params); err != nil {
|
||||
return err
|
||||
} else if err := result.WaitForCompletion(context.Background(), interfaceClinet.Client); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (region *SRegion) GetIEipById(eipId string) (cloudprovider.ICloudEIP, error) {
|
||||
eip := SEipAddress{region: region}
|
||||
resourceGroup, eipName := PareResourceGroupWithName(eipId, EIP_RESOURCE)
|
||||
if len(eipName) == 0 {
|
||||
return nil, cloudprovider.ErrNotFound
|
||||
}
|
||||
networkClient := network.NewPublicIPAddressesClientWithBaseURI(region.client.baseUrl, region.SubscriptionID)
|
||||
networkClient.Authorizer = region.client.authorizer
|
||||
if result, err := networkClient.Get(context.Background(), resourceGroup, eipName, ""); err != nil {
|
||||
if result.Response.StatusCode == 404 {
|
||||
return nil, cloudprovider.ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
} else if err := jsonutils.Update(&eip, result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &eip, nil
|
||||
}
|
||||
|
||||
func (self *SEipAddress) ChangeBandwidth(bw int) error {
|
||||
return cloudprovider.ErrNotImplemented
|
||||
}
|
||||
|
||||
func (self *SEipAddress) Delete() error {
|
||||
return cloudprovider.ErrNotImplemented
|
||||
}
|
||||
|
||||
func (self *SEipAddress) Dissociate() error {
|
||||
// if err := self.region.DissociateEip(self.AllocationId, self.InstanceId); err != nil {
|
||||
// return err
|
||||
// }
|
||||
// return nil
|
||||
return cloudprovider.ErrNotImplemented
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetAssociationExternalId() string {
|
||||
return self.ID
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetAssociationType() string {
|
||||
return ""
|
||||
// switch self.InstanceType {
|
||||
// case EIP_INSTANCE_TYPE_ECS:
|
||||
// return "server"
|
||||
// default:
|
||||
// log.Fatalf("unsupported type: %s", self.InstanceType)
|
||||
// return "unsupported"
|
||||
// }
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetBandwidth() int {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetGlobalId() string {
|
||||
return self.ID
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetId() string {
|
||||
return self.ID
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetInternetChargeType() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetIpAddr() string {
|
||||
return self.Properties.IPAddress
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetManagerId() string {
|
||||
return self.region.client.providerId
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetMetadata() *jsonutils.JSONDict {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetMode() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetName() string {
|
||||
return self.Name
|
||||
}
|
||||
|
||||
func (self *SEipAddress) GetStatus() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (self *SEipAddress) IsEmulated() bool {
|
||||
return false
|
||||
// if self.AllocationId == self.InstanceId {
|
||||
// // fixed Public IP
|
||||
// return true
|
||||
// } else {
|
||||
// return false
|
||||
// }
|
||||
}
|
||||
|
||||
func (self *SEipAddress) Refresh() error {
|
||||
return nil
|
||||
}
|
||||
+125
-4
@@ -1,8 +1,11 @@
|
||||
package azure
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-06-01/compute"
|
||||
"yunion.io/x/jsonutils"
|
||||
"yunion.io/x/log"
|
||||
"yunion.io/x/onecloud/pkg/cloudprovider"
|
||||
@@ -41,8 +44,126 @@ func (self *SHost) Refresh() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SHost) CreateVM(name string, imgId string, sysDiskSize int, cpu int, memMB int, vswitchId string, ipAddr string, desc string, passwd string, storageType string, diskSizes []int, publicKey string) (cloudprovider.ICloudVM, error) {
|
||||
return nil, nil
|
||||
func (self *SHost) CreateVM(name string, imgId string, sysDiskSize int, cpu int, memMB int, networkId string, ipAddr string, desc string, passwd string, storageType string, diskSizes []int, publicKey string) (cloudprovider.ICloudVM, error) {
|
||||
vmId, err := self._createVM(name, imgId, sysDiskSize, cpu, memMB, networkId, ipAddr, desc, passwd, storageType, diskSizes, publicKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resourceGroup, instanceName := PareResourceGroupWithName(vmId, INSTANCE_RESOURCE)
|
||||
if vm, err := self.zone.region.GetInstance(resourceGroup, instanceName); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return vm, err
|
||||
}
|
||||
}
|
||||
|
||||
func (self *SHost) _createVM(name string, imgId string, sysDiskSize int, cpu int, memMB int, networkId string, ipAddr string, desc string, passwd string, storageType string, diskSizes []int, publicKey string) (string, error) {
|
||||
nicId := ""
|
||||
if net := self.zone.getNetworkById(networkId); net == nil {
|
||||
return "", fmt.Errorf("invalid network ID %s", networkId)
|
||||
} else if nic, err := self.zone.region.CreateNetworkInterface(fmt.Sprintf("%s-ipconfig", name), ipAddr, net.GetId()); err != nil {
|
||||
return "", err
|
||||
} else {
|
||||
nicId = nic.ID
|
||||
}
|
||||
computeClient := compute.NewVirtualMachinesClientWithBaseURI(self.zone.region.client.baseUrl, self.zone.region.client.subscriptionId)
|
||||
computeClient.Authorizer = self.zone.region.client.authorizer
|
||||
|
||||
image, err := self.zone.region.GetImage(imgId)
|
||||
if err != nil {
|
||||
log.Errorf("Get Image %s fail %s", imgId, err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
if image.Properties.ProvisioningState != ImageStatusAvailable {
|
||||
log.Errorf("image %s status %s", imgId, image.Properties.ProvisioningState)
|
||||
return "", fmt.Errorf("image not ready")
|
||||
}
|
||||
|
||||
WindowsConfiguration := compute.WindowsConfiguration{}
|
||||
LinuxConfiguration := compute.LinuxConfiguration{}
|
||||
|
||||
storage, err := self.zone.getStorageByType(storageType)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("Storage %s not avaiable: %s", storageType, err)
|
||||
}
|
||||
|
||||
osDiskName := fmt.Sprintf("vdisk_%s_%d", name, time.Now().UnixNano())
|
||||
DataDisks := make([]compute.DataDisk, 0)
|
||||
for i := 0; i < len(diskSizes); i++ {
|
||||
diskName := fmt.Sprintf("vdisk_%s_%d", name, time.Now().UnixNano())
|
||||
size := int32(diskSizes[i] >> 10)
|
||||
index := int32(i)
|
||||
DataDisks = append(DataDisks, compute.DataDisk{
|
||||
Name: &diskName,
|
||||
DiskSizeGB: &size,
|
||||
CreateOption: compute.Empty,
|
||||
Lun: &index,
|
||||
})
|
||||
}
|
||||
|
||||
AdminUsername := "yunion"
|
||||
|
||||
NetworkInterfaceReferences := []compute.NetworkInterfaceReference{
|
||||
compute.NetworkInterfaceReference{ID: &nicId},
|
||||
}
|
||||
|
||||
osType := compute.OperatingSystemTypes(image.GetOsType())
|
||||
DiskSizeGB := int32(sysDiskSize)
|
||||
|
||||
properties := compute.VirtualMachineProperties{
|
||||
HardwareProfile: &compute.HardwareProfile{},
|
||||
StorageProfile: &compute.StorageProfile{
|
||||
ImageReference: &compute.ImageReference{ID: &image.ID},
|
||||
OsDisk: &compute.OSDisk{
|
||||
Caching: compute.ReadWrite,
|
||||
ManagedDisk: &compute.ManagedDiskParameters{
|
||||
StorageAccountType: compute.StorageAccountTypes(storage.storageType),
|
||||
},
|
||||
Name: &osDiskName,
|
||||
CreateOption: compute.FromImage,
|
||||
OsType: osType,
|
||||
DiskSizeGB: &DiskSizeGB,
|
||||
},
|
||||
DataDisks: &DataDisks,
|
||||
},
|
||||
OsProfile: &compute.OSProfile{
|
||||
ComputerName: &name,
|
||||
AdminUsername: &AdminUsername,
|
||||
AdminPassword: &passwd,
|
||||
},
|
||||
NetworkProfile: &compute.NetworkProfile{NetworkInterfaces: &NetworkInterfaceReferences},
|
||||
}
|
||||
|
||||
ProvisionVMAgent := false
|
||||
|
||||
if osType == compute.Linux {
|
||||
LinuxConfiguration.ProvisionVMAgent = &ProvisionVMAgent
|
||||
properties.OsProfile.LinuxConfiguration = &LinuxConfiguration
|
||||
} else if osType == compute.Windows {
|
||||
WindowsConfiguration.ProvisionVMAgent = &ProvisionVMAgent
|
||||
properties.OsProfile.WindowsConfiguration = &WindowsConfiguration
|
||||
}
|
||||
|
||||
params := compute.VirtualMachine{Location: &self.zone.region.Name, Name: &name, VirtualMachineProperties: &properties}
|
||||
log.Debugf("Create instance params: %s", jsonutils.Marshal(params).PrettyString())
|
||||
for _, profile := range self.zone.region.getHardwareProfile(cpu, memMB) {
|
||||
params.HardwareProfile.VMSize = compute.VirtualMachineSizeTypes(profile)
|
||||
log.Debugf("Try HardwareProfile : %s", profile)
|
||||
resourceGroup, instanceName := PareResourceGroupWithName(name, INSTANCE_RESOURCE)
|
||||
result, err := computeClient.CreateOrUpdate(context.Background(), resourceGroup, instanceName, params)
|
||||
if err != nil {
|
||||
log.Errorf("Failed for %s: %s", profile, err)
|
||||
} else if err := result.WaitForCompletion(context.Background(), computeClient.Client); err != nil {
|
||||
return "", err
|
||||
} else if vm, err := result.Result(computeClient); err != nil {
|
||||
return "", err
|
||||
} else {
|
||||
return *vm.ID, nil
|
||||
}
|
||||
}
|
||||
self.zone.region.DeleteNetworkInterface(nicId)
|
||||
return "", fmt.Errorf("Failed to create, specification not supported")
|
||||
}
|
||||
|
||||
func (self *SHost) GetAccessIp() string {
|
||||
@@ -98,8 +219,8 @@ func (self *SHost) GetIStorages() ([]cloudprovider.ICloudStorage, error) {
|
||||
}
|
||||
|
||||
func (self *SHost) GetIVMById(gid string) (cloudprovider.ICloudVM, error) {
|
||||
resourceGroup, name, _ := PareResourceGroupWithName(gid)
|
||||
if instance, err := self.zone.region.GetInstance(resourceGroup, name); err != nil {
|
||||
resourceGroup, instanceName := PareResourceGroupWithName(gid, INSTANCE_RESOURCE)
|
||||
if instance, err := self.zone.region.GetInstance(resourceGroup, instanceName); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
instance.host = self
|
||||
|
||||
+48
-9
@@ -15,7 +15,7 @@ type ImageStatusType string
|
||||
|
||||
const (
|
||||
ImageStatusCreating ImageStatusType = "Creating"
|
||||
ImageStatusAvailable ImageStatusType = "Available"
|
||||
ImageStatusAvailable ImageStatusType = "Succeeded"
|
||||
ImageStatusUnAvailable ImageStatusType = "UnAvailable"
|
||||
ImageStatusCreateFailed ImageStatusType = "CreateFailed"
|
||||
)
|
||||
@@ -81,7 +81,8 @@ func (self *SImage) IsEmulated() bool {
|
||||
}
|
||||
|
||||
func (self *SImage) GetGlobalId() string {
|
||||
return fmt.Sprintf("%s-%s", DefaultResourceGroup["image"], self.Name)
|
||||
resourceGroup, imageName := PareResourceGroupWithName(self.ID, IMAGE_RESOURCE)
|
||||
return fmt.Sprintf("resourceGroups/%s/providers/image/%s", resourceGroup, imageName)
|
||||
}
|
||||
|
||||
func (self *SImage) GetStatus() string {
|
||||
@@ -123,7 +124,11 @@ func (self *SRegion) GetImage(imageId string) (*SImage, error) {
|
||||
image := SImage{}
|
||||
imageClient := compute.NewImagesClientWithBaseURI(self.client.baseUrl, self.SubscriptionID)
|
||||
imageClient.Authorizer = self.client.authorizer
|
||||
if result, err := imageClient.Get(context.Background(), DefaultResourceGroup["image"], imageId, ""); err != nil {
|
||||
resourceGroup, imageName := PareResourceGroupWithName(imageId, IMAGE_RESOURCE)
|
||||
if result, err := imageClient.Get(context.Background(), resourceGroup, imageName, ""); err != nil {
|
||||
if result.Response.StatusCode == 404 {
|
||||
return nil, cloudprovider.ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
} else if jsonutils.Update(&image, result); err != nil {
|
||||
return nil, err
|
||||
@@ -135,15 +140,33 @@ func (self *SRegion) GetImageByName(imageId string) (*SImage, error) {
|
||||
return self.GetImage(imageId)
|
||||
}
|
||||
|
||||
func (self *SRegion) CreateImageByBlob(imageName, osType, blobURI string) (*SImage, error) {
|
||||
func (self *SRegion) CreateImageByBlob(imageName, osType, blobURI string, diskSizeGB int32) (*SImage, error) {
|
||||
if diskSizeGB < 1 || diskSizeGB > 4095 {
|
||||
diskSizeGB = 30
|
||||
}
|
||||
imageClient := compute.NewImagesClientWithBaseURI(self.client.baseUrl, self.SubscriptionID)
|
||||
imageClient.Authorizer = self.client.authorizer
|
||||
storageProfile := compute.ImageStorageProfile{OsDisk: &compute.ImageOSDisk{OsType: compute.OperatingSystemTypes(osType), OsState: compute.OperatingSystemStateTypes("Generalized"), BlobURI: &blobURI}}
|
||||
params := compute.Image{Name: &imageName, Location: &self.Name, ImageProperties: &compute.ImageProperties{StorageProfile: &storageProfile}}
|
||||
if result, err := imageClient.CreateOrUpdate(context.Background(), DefaultResourceGroup["image"], imageName, params); err != nil {
|
||||
storageProfile := compute.ImageStorageProfile{
|
||||
OsDisk: &compute.ImageOSDisk{
|
||||
OsType: compute.OperatingSystemTypes(osType),
|
||||
OsState: compute.Generalized,
|
||||
BlobURI: &blobURI,
|
||||
DiskSizeGB: &diskSizeGB,
|
||||
},
|
||||
}
|
||||
params := compute.Image{
|
||||
Name: &imageName,
|
||||
Location: &self.Name,
|
||||
ImageProperties: &compute.ImageProperties{
|
||||
StorageProfile: &storageProfile,
|
||||
},
|
||||
}
|
||||
resourceGroup, imageName := PareResourceGroupWithName(imageName, IMAGE_RESOURCE)
|
||||
if result, err := imageClient.CreateOrUpdate(context.Background(), resourceGroup, imageName, params); err != nil {
|
||||
log.Errorf("Create image from blob error: %v", err)
|
||||
return nil, err
|
||||
} else if err := result.WaitForCompletion(context.Background(), imageClient.Client); err != nil {
|
||||
log.Errorf("WaitForCreateImageCompletion error: %v", err)
|
||||
return nil, err
|
||||
} else if image, err := self.GetImageByName(imageName); err != nil {
|
||||
return nil, err
|
||||
@@ -164,6 +187,22 @@ func (self *SRegion) GetImages() ([]SImage, error) {
|
||||
return images, nil
|
||||
}
|
||||
|
||||
func (self *SImage) Delete() error {
|
||||
return cloudprovider.ErrNotImplemented
|
||||
func (self *SRegion) DeleteImage(imageId string) error {
|
||||
imageClient := compute.NewImagesClientWithBaseURI(self.client.baseUrl, self.SubscriptionID)
|
||||
imageClient.Authorizer = self.client.authorizer
|
||||
resourceGroup, imageName := PareResourceGroupWithName(imageId, IMAGE_RESOURCE)
|
||||
if result, err := imageClient.Delete(context.Background(), resourceGroup, imageName); err != nil {
|
||||
return err
|
||||
} else if err := result.WaitForCompletion(context.Background(), imageClient.Client); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SImage) Delete() error {
|
||||
return self.storageCache.region.DeleteImage(self.ID)
|
||||
}
|
||||
|
||||
func (self *SImage) GetOsType() string {
|
||||
return string(self.Properties.StorageProfile.OsDisk.OsType)
|
||||
}
|
||||
|
||||
+127
-48
@@ -154,8 +154,7 @@ type SInstance struct {
|
||||
|
||||
idisks []cloudprovider.ICloudDisk
|
||||
|
||||
CreationTime time.Time
|
||||
ResourceGroup string
|
||||
CreationTime time.Time
|
||||
|
||||
Properties VirtualMachineProperties
|
||||
ID string
|
||||
@@ -166,25 +165,30 @@ type SInstance struct {
|
||||
Tags map[string]string
|
||||
}
|
||||
|
||||
func PareResourceGroupWithName(s string) (string, string, error) {
|
||||
func PareResourceGroupWithName(s string, resourceType string) (string, string) {
|
||||
valid := regexp.MustCompile("resourceGroups/(.+)/providers/.+/(.+)$")
|
||||
if resourceGroups := valid.FindStringSubmatch(s); len(resourceGroups) == 3 {
|
||||
return resourceGroups[1], resourceGroups[2], nil
|
||||
return resourceGroups[1], resourceGroups[2]
|
||||
}
|
||||
log.Errorf("PareResourceGroupWithName[%s] error", s)
|
||||
return "", "", cloudprovider.ErrNotFound
|
||||
return DefaultResourceGroups[resourceType], s
|
||||
}
|
||||
|
||||
func (self *SRegion) GetInstance(resourceGroup string, VMName string) (*SInstance, error) {
|
||||
instance := SInstance{}
|
||||
computeClient := compute.NewVirtualMachinesClientWithBaseURI(self.client.baseUrl, self.client.subscriptionId)
|
||||
computeClient.Authorizer = self.client.authorizer
|
||||
if len(VMName) == 0 {
|
||||
return nil, cloudprovider.ErrNotFound
|
||||
}
|
||||
if _instance, err := computeClient.Get(context.Background(), resourceGroup, VMName, "instanceView"); err != nil {
|
||||
if _instance.Response.StatusCode == 404 {
|
||||
return nil, cloudprovider.ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
} else if err := jsonutils.Update(&instance, _instance); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
instance.ResourceGroup = resourceGroup
|
||||
return &instance, nil
|
||||
}
|
||||
}
|
||||
@@ -202,7 +206,6 @@ func (self *SRegion) GetInstances() ([]SInstance, error) {
|
||||
if err := jsonutils.Update(&instance, _instance); err != nil {
|
||||
return instances, err
|
||||
}
|
||||
instance.ResourceGroup, _, _ = PareResourceGroupWithName(instance.ID)
|
||||
instances = append(instances, instance)
|
||||
}
|
||||
}
|
||||
@@ -211,7 +214,14 @@ func (self *SRegion) GetInstances() ([]SInstance, error) {
|
||||
}
|
||||
|
||||
func (self *SRegion) doDeleteVM(instanceId string) error {
|
||||
//return self.instanceOperation(instanceId, "DeleteInstance", nil)
|
||||
resourceGroup, instanceName := PareResourceGroupWithName(instanceId, INSTANCE_RESOURCE)
|
||||
computeClient := compute.NewVirtualMachinesClientWithBaseURI(self.client.baseUrl, self.client.subscriptionId)
|
||||
computeClient.Authorizer = self.client.authorizer
|
||||
if resulte, err := computeClient.Delete(context.Background(), resourceGroup, instanceName); err != nil {
|
||||
return err
|
||||
} else if err := resulte.WaitForCompletion(context.Background(), computeClient.Client); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -226,6 +236,8 @@ func (self *SInstance) GetMetadata() *jsonutils.JSONDict {
|
||||
if loginKey := self.Properties.OsProfile.AdminPassword; len(loginKey) > 0 {
|
||||
data.Add(jsonutils.NewString(loginKey), "login_key")
|
||||
}
|
||||
|
||||
data.Add(jsonutils.NewString(self.Properties.HardwareProfile.VMSize), "price_key")
|
||||
return data
|
||||
}
|
||||
|
||||
@@ -237,12 +249,47 @@ func (self *SInstance) IsEmulated() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (self *SInstance) getDisks() ([]SDisk, error) {
|
||||
disks := make([]SDisk, 0)
|
||||
resourceGroup, diskName := PareResourceGroupWithName(self.Properties.StorageProfile.OsDisk.ManagedDisk.ID, DISK_RESOURCE)
|
||||
if osdisk, err := self.getDiskWithStore(resourceGroup, diskName); err != nil {
|
||||
log.Errorf("Failed to find instance %s os disk: %s", self.Name, diskName)
|
||||
|
||||
} else {
|
||||
disks = append(disks, *osdisk)
|
||||
}
|
||||
for _, _disk := range self.Properties.StorageProfile.DataDisks {
|
||||
resourceGroup, diskName := PareResourceGroupWithName(_disk.ManagedDisk.ID, DISK_RESOURCE)
|
||||
if disk, err := self.getDiskWithStore(resourceGroup, diskName); err != nil {
|
||||
log.Errorf("Failed to find instance %s data disk: %s", self.Name, diskName)
|
||||
return nil, err
|
||||
} else {
|
||||
disks = append(disks, *disk)
|
||||
}
|
||||
}
|
||||
return disks, nil
|
||||
}
|
||||
|
||||
func (self *SInstance) getNics() ([]SInstanceNic, error) {
|
||||
nics := make([]SInstanceNic, 0)
|
||||
for _, _nic := range self.Properties.NetworkProfile.NetworkInterfaces {
|
||||
resourceGroup, nicName := PareResourceGroupWithName(_nic.ID, NIC_RESOURCE)
|
||||
if nic, err := self.host.zone.region.getNetworkInterface(resourceGroup, nicName); err != nil {
|
||||
log.Errorf("Failed to find instance %s nic: %s", self.Name, nicName)
|
||||
return nil, err
|
||||
} else {
|
||||
nic.instance = self
|
||||
nics = append(nics, *nic)
|
||||
}
|
||||
}
|
||||
return nics, nil
|
||||
}
|
||||
|
||||
func (self *SInstance) Refresh() error {
|
||||
if instance, err := self.host.zone.region.GetInstance(self.ResourceGroup, self.Name); err != nil {
|
||||
log.Errorf("Refresh Instance error: %v", err)
|
||||
return cloudprovider.ErrNotFound
|
||||
resourceGroup, instanceName := PareResourceGroupWithName(self.ID, INSTANCE_RESOURCE)
|
||||
if instance, err := self.host.zone.region.GetInstance(resourceGroup, instanceName); err != nil {
|
||||
return err
|
||||
} else if err := jsonutils.Update(self, instance); err != nil {
|
||||
log.Errorf("Refresh Instance error: %v", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
@@ -256,7 +303,7 @@ func (self *SInstance) GetStatus() string {
|
||||
if code := strings.Split(statuses.Code, "/"); len(code) == 2 {
|
||||
if code[0] == "PowerState" {
|
||||
switch code[1] {
|
||||
case "stopped":
|
||||
case "stopped", "deallocated":
|
||||
return models.VM_READY
|
||||
case "running":
|
||||
return models.VM_RUNNING
|
||||
@@ -309,30 +356,57 @@ func (self *SInstance) GetName() string {
|
||||
}
|
||||
|
||||
func (self *SInstance) GetGlobalId() string {
|
||||
resourceGroup, _, _ := PareResourceGroupWithName(self.ID)
|
||||
return fmt.Sprintf("resourceGroups/%s/providers/server/%s", resourceGroup, self.Name)
|
||||
resourceGroup, instanceName := PareResourceGroupWithName(self.ID, INSTANCE_RESOURCE)
|
||||
return fmt.Sprintf("resourceGroups/%s/providers/server/%s", resourceGroup, instanceName)
|
||||
}
|
||||
|
||||
func (self *SRegion) GetInstanceStatus(instanceId string) (string, error) {
|
||||
resourceGroup, instanceName := PareResourceGroupWithName(instanceId, INSTANCE_RESOURCE)
|
||||
instance, err := self.GetInstance(resourceGroup, instanceName)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return instance.GetStatus(), nil
|
||||
}
|
||||
|
||||
func (self *SRegion) DeleteVM(instanceId string) error {
|
||||
// status, err := self.GetInstanceStatus(instanceId)
|
||||
// if status == InstanceStatusRunning {
|
||||
// err = self.StopVM(instanceId, true)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// } else if status != InstanceStatusStopped {
|
||||
// return cloudprovider.ErrInvalidStatus
|
||||
// }
|
||||
if status, err := self.GetInstanceStatus(instanceId); err != nil {
|
||||
return err
|
||||
} else if status == models.VM_RUNNING {
|
||||
if err := self.StopVM(instanceId, true); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if status != models.VM_READY {
|
||||
log.Debugf("instance %s status: %s", instanceId, status)
|
||||
return cloudprovider.ErrInvalidStatus
|
||||
}
|
||||
return self.doDeleteVM(instanceId)
|
||||
}
|
||||
|
||||
func (self *SInstance) DeleteVM() error {
|
||||
log.Debugf("delete: %s %s", self.ID, self.Name)
|
||||
if err := self.host.zone.region.DeleteVM(self.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if disks, err := self.getDisks(); err != nil {
|
||||
return err
|
||||
} else {
|
||||
for _, disk := range disks {
|
||||
if err := disk.Delete(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if nics, err := self.getNics(); err != nil {
|
||||
return err
|
||||
} else {
|
||||
for _, nic := range nics {
|
||||
if err := nic.Delete(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
// err := self.host.zone.region.DeleteVM(self.InstanceId)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// return cloudprovider.WaitDeleted(self, 10*time.Second, 300*time.Second) // 5minutes
|
||||
}
|
||||
|
||||
func (self *SInstance) getDiskWithStore(resourceGroup string, diskName string) (*SDisk, error) {
|
||||
@@ -348,21 +422,12 @@ func (self *SInstance) getDiskWithStore(resourceGroup string, diskName string) (
|
||||
}
|
||||
|
||||
func (self *SInstance) fetchDisks() error {
|
||||
self.Refresh()
|
||||
self.idisks = make([]cloudprovider.ICloudDisk, len(self.Properties.StorageProfile.DataDisks)+1)
|
||||
if disk, err := self.getDiskWithStore(self.ResourceGroup, self.Properties.StorageProfile.OsDisk.Name); err != nil {
|
||||
if disks, err := self.getDisks(); err != nil {
|
||||
return err
|
||||
} else {
|
||||
self.idisks[0] = disk
|
||||
}
|
||||
for i, dataDisk := range self.Properties.StorageProfile.DataDisks {
|
||||
if resourceGroup, diskName, err := PareResourceGroupWithName(dataDisk.ManagedDisk.ID); err != nil {
|
||||
return err
|
||||
} else if disk, err := self.getDiskWithStore(resourceGroup, diskName); err != nil {
|
||||
return err
|
||||
} else {
|
||||
self.idisks[i+1] = disk
|
||||
log.Debugf("find disk %s for instance %s", disk.GetName(), self.GetName())
|
||||
for i := 0; i < len(disks); i++ {
|
||||
self.idisks[i] = &disks[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -384,9 +449,8 @@ func (self *SInstance) GetOSType() string {
|
||||
func (self *SInstance) GetINics() ([]cloudprovider.ICloudNic, error) {
|
||||
nics := make([]cloudprovider.ICloudNic, 0)
|
||||
for _, _nic := range self.Properties.NetworkProfile.NetworkInterfaces {
|
||||
if resourceGroup, nicName, err := PareResourceGroupWithName(_nic.ID); err != nil {
|
||||
return nics, err
|
||||
} else if nic, err := self.host.zone.region.getNetworkInterface(resourceGroup, nicName); err != nil {
|
||||
resourceGroup, nicName := PareResourceGroupWithName(_nic.ID, NIC_RESOURCE)
|
||||
if nic, err := self.host.zone.region.getNetworkInterface(resourceGroup, nicName); err != nil {
|
||||
return nics, err
|
||||
} else {
|
||||
nic.instance = self
|
||||
@@ -467,10 +531,10 @@ func (self *SInstance) GetVNCInfo() (jsonutils.JSONObject, error) {
|
||||
}
|
||||
|
||||
func (self *SRegion) StartVM(instanceId string) error {
|
||||
resourceGroup, name, _ := PareResourceGroupWithName(instanceId)
|
||||
resourceGroup, instanceName := PareResourceGroupWithName(instanceId, INSTANCE_RESOURCE)
|
||||
computeClient := compute.NewVirtualMachinesClientWithBaseURI(self.client.baseUrl, self.client.subscriptionId)
|
||||
computeClient.Authorizer = self.client.authorizer
|
||||
if result, err := computeClient.Start(context.Background(), resourceGroup, name); err != nil {
|
||||
if result, err := computeClient.Start(context.Background(), resourceGroup, instanceName); err != nil {
|
||||
return err
|
||||
} else if err := result.WaitForCompletion(context.Background(), computeClient.Client); err != nil {
|
||||
return err
|
||||
@@ -497,10 +561,10 @@ func (self *SRegion) StopVM(instanceId string, isForce bool) error {
|
||||
}
|
||||
|
||||
func (self *SRegion) doStopVM(instanceId string, isForce bool) error {
|
||||
resourceGroup, name, _ := PareResourceGroupWithName(instanceId)
|
||||
resourceGroup, instanceName := PareResourceGroupWithName(instanceId, INSTANCE_RESOURCE)
|
||||
computeClient := compute.NewVirtualMachinesClientWithBaseURI(self.client.baseUrl, self.client.subscriptionId)
|
||||
computeClient.Authorizer = self.client.authorizer
|
||||
if result, err := computeClient.PowerOff(context.Background(), resourceGroup, name); err != nil {
|
||||
if result, err := computeClient.PowerOff(context.Background(), resourceGroup, instanceName); err != nil {
|
||||
return err
|
||||
} else if err := result.WaitForCompletion(context.Background(), computeClient.Client); err != nil {
|
||||
return err
|
||||
@@ -511,3 +575,18 @@ func (self *SRegion) doStopVM(instanceId string, isForce bool) error {
|
||||
func (self *SInstance) SyncSecurityGroup(secgroupId string, name string, rules []secrules.SecurityRule) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SInstance) GetIEIP() (cloudprovider.ICloudEIP, error) {
|
||||
if nics, err := self.getNics(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
for _, nic := range nics {
|
||||
for _, ip := range nic.Properties.IPConfigurations {
|
||||
if len(ip.Properties.PublicIPAddress.ID) > 0 {
|
||||
return self.host.zone.region.GetEip(ip.Properties.PublicIPAddress.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -4,19 +4,12 @@ import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"yunion.io/x/jsonutils"
|
||||
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-06-01/network"
|
||||
"yunion.io/x/log"
|
||||
"yunion.io/x/onecloud/pkg/cloudprovider"
|
||||
"yunion.io/x/pkg/util/netutils"
|
||||
|
||||
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-04-01/network"
|
||||
)
|
||||
|
||||
type PublicIPAddressPropertiesFormat struct {
|
||||
PublicIPAddressVersion string
|
||||
IPAddress string
|
||||
}
|
||||
|
||||
type PublicIPAddress struct {
|
||||
ID string
|
||||
Name string
|
||||
@@ -25,11 +18,12 @@ type PublicIPAddress struct {
|
||||
}
|
||||
|
||||
type InterfaceIPConfigurationPropertiesFormat struct {
|
||||
PrivateIPAddress string
|
||||
PrivateIPAddressVersion string
|
||||
Subnet Subnet
|
||||
Primary bool
|
||||
PublicIPAddress PublicIPAddress
|
||||
PrivateIPAddress string
|
||||
PrivateIPAddressVersion string
|
||||
PrivateIPAllocationMethod string
|
||||
Subnet Subnet
|
||||
Primary bool
|
||||
PublicIPAddress PublicIPAddress
|
||||
}
|
||||
|
||||
type InterfaceIPConfiguration struct {
|
||||
@@ -53,22 +47,26 @@ type SInstanceNic struct {
|
||||
Properties InterfacePropertiesFormat
|
||||
}
|
||||
|
||||
func (self *SRegion) getNetworkInterface(resourceGroup string, nicName string) (*SInstanceNic, error) {
|
||||
nic := SInstanceNic{}
|
||||
networkClient := network.NewInterfacesClientWithBaseURI(self.client.baseUrl, self.SubscriptionID)
|
||||
networkClient.Authorizer = self.client.authorizer
|
||||
if _nic, err := networkClient.Get(context.Background(), resourceGroup, nicName, ""); err != nil {
|
||||
return nil, err
|
||||
} else if err := jsonutils.Update(&nic, _nic); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &nic, nil
|
||||
}
|
||||
|
||||
func (self *SInstanceNic) GetIP() string {
|
||||
return self.Properties.IPConfigurations[0].Properties.PrivateIPAddress
|
||||
}
|
||||
|
||||
func (region *SRegion) DeleteNetworkInterface(interfaceId string) error {
|
||||
resourceGroup, nicName := PareResourceGroupWithName(interfaceId, NIC_RESOURCE)
|
||||
networkClient := network.NewInterfacesClientWithBaseURI(region.client.baseUrl, region.SubscriptionID)
|
||||
networkClient.Authorizer = region.client.authorizer
|
||||
if result, err := networkClient.Delete(context.Background(), resourceGroup, nicName); err != nil {
|
||||
return err
|
||||
} else if err := result.WaitForCompletion(context.Background(), networkClient.Client); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SInstanceNic) Delete() error {
|
||||
return self.instance.host.zone.region.DeleteNetworkInterface(self.ID)
|
||||
}
|
||||
|
||||
func (self *SInstanceNic) GetMAC() string {
|
||||
mac := self.Properties.MacAddress
|
||||
if len(mac) == 0 {
|
||||
|
||||
@@ -28,8 +28,7 @@ func (self *SNetwork) GetMetadata() *jsonutils.JSONDict {
|
||||
}
|
||||
|
||||
func (self *SNetwork) GetId() string {
|
||||
vpcName := self.wire.vpc.GetName()
|
||||
return fmt.Sprintf("%s/%s/%s/%s", self.wire.zone.region.GetGlobalId(), self.wire.zone.region.SubscriptionID, vpcName, self.Name)
|
||||
return self.ID
|
||||
}
|
||||
|
||||
func (self *SNetwork) GetName() string {
|
||||
@@ -37,7 +36,8 @@ func (self *SNetwork) GetName() string {
|
||||
}
|
||||
|
||||
func (self *SNetwork) GetGlobalId() string {
|
||||
return self.GetId()
|
||||
resourceGroup, networkName := PareResourceGroupWithName(self.ID, NETWORK_RESOURCE)
|
||||
return fmt.Sprintf("resourceGroups/%s/providers/network/%s", resourceGroup, networkName)
|
||||
}
|
||||
|
||||
func (self *SNetwork) IsEmulated() bool {
|
||||
@@ -71,8 +71,8 @@ func (self *SNetwork) Delete() error {
|
||||
region := self.wire.vpc.region
|
||||
networkClient := network.NewVirtualNetworksClientWithBaseURI(region.client.baseUrl, region.SubscriptionID)
|
||||
networkClient.Authorizer = region.client.authorizer
|
||||
resourceGroup, _, _ := PareResourceGroupWithName(vpc.ID)
|
||||
if result, err := networkClient.CreateOrUpdate(context.Background(), resourceGroup, vpc.Name, params); err != nil {
|
||||
resourceGroup, vpcName := PareResourceGroupWithName(vpc.ID, VPC_RESOURCE)
|
||||
if result, err := networkClient.CreateOrUpdate(context.Background(), resourceGroup, vpcName, params); err != nil {
|
||||
return err
|
||||
} else if err := result.WaitForCompletion(context.Background(), networkClient.Client); err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package azure
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-06-01/network"
|
||||
"yunion.io/x/jsonutils"
|
||||
)
|
||||
|
||||
func (self *SRegion) getNetworkInterface(resourceGroup string, nicName string) (*SInstanceNic, error) {
|
||||
nic := SInstanceNic{}
|
||||
networkClient := network.NewInterfacesClientWithBaseURI(self.client.baseUrl, self.SubscriptionID)
|
||||
networkClient.Authorizer = self.client.authorizer
|
||||
if _nic, err := networkClient.Get(context.Background(), resourceGroup, nicName, ""); err != nil {
|
||||
return nil, err
|
||||
} else if err := jsonutils.Update(&nic, _nic); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &nic, nil
|
||||
}
|
||||
|
||||
func (self *SRegion) GetNetworkInterfaces() ([]SInstanceNic, error) {
|
||||
networkClinet := network.NewInterfacesClientWithBaseURI(self.client.baseUrl, self.SubscriptionID)
|
||||
networkClinet.Authorizer = self.client.authorizer
|
||||
nics := make([]SInstanceNic, 0)
|
||||
if _nics, err := networkClinet.ListAll(context.Background()); err != nil {
|
||||
return nil, err
|
||||
} else if err := jsonutils.Update(&nics, _nics.Values()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nics, nil
|
||||
}
|
||||
|
||||
func (self *SRegion) isNetworkInstanceNameAvaliable(nicName string) bool {
|
||||
networkClinet := network.NewInterfacesClientWithBaseURI(self.client.baseUrl, self.SubscriptionID)
|
||||
networkClinet.Authorizer = self.client.authorizer
|
||||
resourceGroup, nicName := PareResourceGroupWithName(nicName, NIC_RESOURCE)
|
||||
if _, err := networkClinet.Get(context.Background(), resourceGroup, nicName, ""); err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (self *SRegion) CreateNetworkInterface(nicName string, ipAddr string, subnetId string) (*SInstanceNic, error) {
|
||||
networkClinet := network.NewInterfacesClientWithBaseURI(self.client.baseUrl, self.SubscriptionID)
|
||||
networkClinet.Authorizer = self.client.authorizer
|
||||
nic := SInstanceNic{}
|
||||
PrivateIPAllocationMethod := network.Static
|
||||
if len(ipAddr) == 0 {
|
||||
PrivateIPAllocationMethod = network.Dynamic
|
||||
}
|
||||
_nicName := nicName
|
||||
for i := 0; i < 10; i++ {
|
||||
nicName = fmt.Sprintf("%s-%d", _nicName, i)
|
||||
if self.isNetworkInstanceNameAvaliable(nicName) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if nicName == fmt.Sprintf("%s-10", _nicName) {
|
||||
return nil, fmt.Errorf("Can not find avaliable nic name")
|
||||
}
|
||||
|
||||
IPConfigurations := []network.InterfaceIPConfiguration{
|
||||
network.InterfaceIPConfiguration{
|
||||
Name: &nicName,
|
||||
InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
|
||||
PrivateIPAddress: &ipAddr,
|
||||
PrivateIPAddressVersion: network.IPv4,
|
||||
PrivateIPAllocationMethod: PrivateIPAllocationMethod,
|
||||
Subnet: &network.Subnet{ID: &subnetId},
|
||||
},
|
||||
},
|
||||
}
|
||||
params := network.Interface{
|
||||
Name: &nicName,
|
||||
Location: &self.Name,
|
||||
InterfacePropertiesFormat: &network.InterfacePropertiesFormat{
|
||||
IPConfigurations: &IPConfigurations,
|
||||
},
|
||||
}
|
||||
//log.Debugf("create params: %", jsonutils.Marshal(params).PrettyString())
|
||||
resourceGroup, nicName := PareResourceGroupWithName(nicName, NIC_RESOURCE)
|
||||
if result, err := networkClinet.CreateOrUpdate(context.Background(), resourceGroup, nicName, params); err != nil {
|
||||
return nil, err
|
||||
} else if err := result.WaitForCompletion(context.Background(), networkClinet.Client); err != nil {
|
||||
return nil, err
|
||||
} else if _nic, err := result.Result(networkClinet); err != nil {
|
||||
return nil, err
|
||||
} else if err := jsonutils.Update(&nic, _nic); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &nic, nil
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package progress
|
||||
|
||||
// ComputeStats type supports computing running average with a given window size.
|
||||
//
|
||||
type ComputeStats struct {
|
||||
history []float64
|
||||
size int
|
||||
p int
|
||||
}
|
||||
|
||||
// NewComputeStats returns a new instance of ComputeStats. The parameter size is the
|
||||
// maximum number of values that ComputeStats track at any given point of time.
|
||||
//
|
||||
func NewComputeStats(size int) *ComputeStats {
|
||||
return &ComputeStats{
|
||||
history: make([]float64, size),
|
||||
size: size,
|
||||
p: 0,
|
||||
}
|
||||
}
|
||||
|
||||
// NewComputestateDefaultSize returns a new instance of ComputeStats that can tracks
|
||||
// maximum of 60 values.
|
||||
//
|
||||
func NewComputestateDefaultSize() *ComputeStats {
|
||||
return NewComputeStats(60)
|
||||
}
|
||||
|
||||
// ComputeAvg adds the given value to a list containing set of previous values added
|
||||
// and returns the average of the values in the list. If the values list reached the
|
||||
// maximum size then oldest value will be removed
|
||||
//
|
||||
func (s *ComputeStats) ComputeAvg(current float64) float64 {
|
||||
s.history[s.p] = current
|
||||
s.p++
|
||||
if s.p == s.size {
|
||||
s.p = 0
|
||||
}
|
||||
|
||||
sum := float64(0)
|
||||
for i := 0; i < s.size; i++ {
|
||||
sum += s.history[i]
|
||||
}
|
||||
|
||||
return sum / float64(s.size)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package progress
|
||||
|
||||
import (
|
||||
"io"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ReaderWithProgress wraps an io.ReadCloser, it track and report the read progress.
|
||||
//
|
||||
type ReaderWithProgress struct {
|
||||
ProgressChan <-chan *Record
|
||||
innerReadCloser io.ReadCloser
|
||||
progressStatus *Status
|
||||
}
|
||||
|
||||
// NewReaderWithProgress creates a new instance of ReaderWithProgress. The parameter inner is the inner stream whose
|
||||
// read progress needs to be tracked, sizeInBytes is the total size of the inner stream in bytes,
|
||||
// progressIntervalInSeconds is the interval at which the read progress needs to be send to ProgressChan channel.
|
||||
// After using the this reader, it must be closed by calling Close method to avoid goroutine leak.
|
||||
//
|
||||
func NewReaderWithProgress(inner io.ReadCloser, sizeInBytes int64, progressIntervalInSeconds time.Duration) *ReaderWithProgress {
|
||||
r := &ReaderWithProgress{}
|
||||
r.innerReadCloser = inner
|
||||
r.progressStatus = NewStatus(0, 0, sizeInBytes, NewComputestateDefaultSize())
|
||||
r.ProgressChan = r.progressStatus.Run()
|
||||
return r
|
||||
}
|
||||
|
||||
// Read reads up to len(b) bytes from the inner stream. It returns the number of bytes read and an error, if any.
|
||||
// EOF is signaled when no more data to read and n will set to 0.
|
||||
//
|
||||
func (r *ReaderWithProgress) Read(p []byte) (n int, err error) {
|
||||
n, err = r.innerReadCloser.Read(p)
|
||||
if err == nil {
|
||||
r.progressStatus.ReportBytesProcessedCount(int64(n))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Close closes the inner stream and stop reporting read progress in the ProgressChan chan.
|
||||
//
|
||||
func (r *ReaderWithProgress) Close() error {
|
||||
err := r.innerReadCloser.Close()
|
||||
r.progressStatus.Close()
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package progress
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Status can be used by a collection of workers (reporters) to report the amount of work done when they need,
|
||||
// Status compute the overall progress at regular interval and report it.
|
||||
//
|
||||
type Status struct {
|
||||
bytesProcessedCountChan chan int64
|
||||
doneChan chan bool
|
||||
bytesProcessed int64
|
||||
totalBytes int64
|
||||
alreadyProcessedBytes int64
|
||||
startTime time.Time
|
||||
throughputStats *ComputeStats
|
||||
}
|
||||
|
||||
// Record type is used by the ProgressStatus to report the progress at regular interval.
|
||||
//
|
||||
type Record struct {
|
||||
PercentComplete float64
|
||||
AverageThroughputMbPerSecond float64
|
||||
RemainingDuration time.Duration
|
||||
BytesProcessed int64
|
||||
}
|
||||
|
||||
// oneMB is one MegaByte
|
||||
//
|
||||
const oneMB = float64(1048576)
|
||||
|
||||
// nanosecondsInOneSecond is 1 second expressed as nano-second unit
|
||||
//
|
||||
const nanosecondsInOneSecond = 1000 * 1000 * 1000
|
||||
|
||||
// NewStatus creates a new instance of Status. reporterCount is the number of concurrent goroutines that want to
|
||||
// report processed bytes count, alreadyProcessedBytes is the bytes already processed if any, the parameter
|
||||
// totalBytes is the total number of bytes that the reports will be process eventually, the parameter computeStats
|
||||
// is used to calculate the running average.
|
||||
//
|
||||
func NewStatus(reportersCount int, alreadyProcessedBytes, totalBytes int64, computeStats *ComputeStats) *Status {
|
||||
return &Status{
|
||||
bytesProcessedCountChan: make(chan int64, reportersCount),
|
||||
doneChan: make(chan bool, 0),
|
||||
totalBytes: totalBytes,
|
||||
alreadyProcessedBytes: alreadyProcessedBytes,
|
||||
startTime: time.Now(),
|
||||
throughputStats: computeStats,
|
||||
}
|
||||
}
|
||||
|
||||
// ReportBytesProcessedCount method is used to report the number of bytes processed.
|
||||
//
|
||||
func (s *Status) ReportBytesProcessedCount(count int64) {
|
||||
s.bytesProcessedCountChan <- count
|
||||
}
|
||||
|
||||
// Run starts counting the reported processed bytes count and compute the progress, this method returns a channel,
|
||||
// the computed progress will be send to this channel in regular interval. Once done with using ProgressStatus
|
||||
// instance, you must call Dispose method otherwise there will be go routine leak.
|
||||
//
|
||||
func (s *Status) Run() <-chan *Record {
|
||||
go s.bytesProcessedCountReceiver()
|
||||
var outChan = make(chan *Record, 0)
|
||||
go s.progressRecordSender(outChan)
|
||||
return outChan
|
||||
}
|
||||
|
||||
// Close disposes this ProgressStatus instance, an attempt to invoke ReportBytesProcessedCount method on a closed
|
||||
// instance will be panic. Close also stops sending progress to the channel returned by Run method. Not calling
|
||||
// Close will cause goroutine leak.
|
||||
//
|
||||
func (s *Status) Close() {
|
||||
close(s.bytesProcessedCountChan)
|
||||
}
|
||||
|
||||
// bytesProcessedCountReceiver read the channel containing the collection of reported bytes count and update the total
|
||||
// bytes processed. This method signal doneChan when there is no more data to read.
|
||||
//
|
||||
func (s *Status) bytesProcessedCountReceiver() {
|
||||
for c := range s.bytesProcessedCountChan {
|
||||
s.bytesProcessed += c
|
||||
}
|
||||
s.doneChan <- true
|
||||
}
|
||||
|
||||
// progressRecordSender compute the progress information at regular interval and send it to channel outChan which is
|
||||
// returned by the Run method
|
||||
//
|
||||
func (s *Status) progressRecordSender(outChan chan<- *Record) {
|
||||
progressRecord := &Record{}
|
||||
tickerChan := time.NewTicker(500 * time.Millisecond)
|
||||
Loop:
|
||||
for {
|
||||
select {
|
||||
case <-tickerChan.C:
|
||||
computeAvg := s.throughputStats.ComputeAvg(s.throughputMBs())
|
||||
avtThroughputMbps := 8.0 * computeAvg
|
||||
remainingSeconds := (s.remainingMB() / computeAvg)
|
||||
|
||||
progressRecord.PercentComplete = s.percentComplete()
|
||||
progressRecord.RemainingDuration = time.Duration(nanosecondsInOneSecond * remainingSeconds)
|
||||
progressRecord.AverageThroughputMbPerSecond = avtThroughputMbps
|
||||
progressRecord.BytesProcessed = s.bytesProcessed
|
||||
|
||||
outChan <- progressRecord
|
||||
case <-s.doneChan:
|
||||
tickerChan.Stop()
|
||||
break Loop
|
||||
}
|
||||
}
|
||||
close(outChan)
|
||||
}
|
||||
|
||||
// remainingMB returns remaining bytes to be processed as MB.
|
||||
//
|
||||
func (s *Status) remainingMB() float64 {
|
||||
return float64(s.totalBytes-s.bytesProcessed) / oneMB
|
||||
}
|
||||
|
||||
// percentComplete returns the percentage of bytes processed out of total bytes.
|
||||
//
|
||||
func (s *Status) percentComplete() float64 {
|
||||
return float64(100.0) * (float64(s.bytesProcessed) / float64(s.totalBytes))
|
||||
}
|
||||
|
||||
// processTime returns the Duration representing the time taken to process the bytes so far.
|
||||
//
|
||||
func (s *Status) processTime() time.Duration {
|
||||
return time.Since(s.startTime)
|
||||
}
|
||||
|
||||
// throughputMBs returns the throughput in MB
|
||||
//
|
||||
func (s *Status) throughputMBs() float64 {
|
||||
return float64(s.bytesProcessed) / oneMB / s.processTime().Seconds()
|
||||
}
|
||||
+46
-11
@@ -8,6 +8,7 @@ import (
|
||||
"yunion.io/x/log"
|
||||
"yunion.io/x/onecloud/pkg/cloudprovider"
|
||||
"yunion.io/x/onecloud/pkg/compute/models"
|
||||
"yunion.io/x/onecloud/pkg/util/seclib2"
|
||||
|
||||
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-06-01/compute"
|
||||
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-06-01/network"
|
||||
@@ -66,6 +67,21 @@ func (self *SRegion) fetchVMSize() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SRegion) getHardwareProfile(cpu, memMB int) []string {
|
||||
if self.vmSize == nil || len(self.vmSize) == 0 {
|
||||
if err := self.fetchVMSize(); err != nil {
|
||||
return []string{}
|
||||
}
|
||||
}
|
||||
profiles := make([]string, 0)
|
||||
for vmSize, info := range self.vmSize {
|
||||
if info.MemoryInMB == int32(memMB) && info.NumberOfCores == int32(cpu) {
|
||||
profiles = append(profiles, vmSize)
|
||||
}
|
||||
}
|
||||
return profiles
|
||||
}
|
||||
|
||||
func (self *SRegion) getVMSize(size string) (*SVMSize, error) {
|
||||
if self.vmSize == nil || len(self.vmSize) == 0 {
|
||||
if err := self.fetchVMSize(); err != nil {
|
||||
@@ -122,8 +138,9 @@ func (self *SRegion) CreateIVpc(name string, desc string, cidr string) (cloudpro
|
||||
addressSpace := network.AddressSpace{AddressPrefixes: &addressPrefixes}
|
||||
properties := network.VirtualNetworkPropertiesFormat{AddressSpace: &addressSpace}
|
||||
parameters := network.VirtualNetwork{Name: &name, Location: &self.Name, VirtualNetworkPropertiesFormat: &properties}
|
||||
vpcId := fmt.Sprintf("resourceGroups/%s/providers/%s/%s", DefaultResourceGroup["vpc"], self.SubscriptionID, name)
|
||||
if result, err := vpcClient.CreateOrUpdate(context.Background(), DefaultResourceGroup["vpc"], name, parameters); err != nil {
|
||||
resourceGroup, vpcName := PareResourceGroupWithName(name, VPC_RESOURCE)
|
||||
vpcId := fmt.Sprintf("resourceGroups/%s/providers/vpc/%s", resourceGroup, vpcName)
|
||||
if result, err := vpcClient.CreateOrUpdate(context.Background(), resourceGroup, vpcName, parameters); err != nil {
|
||||
return nil, err
|
||||
} else if err := result.WaitForCompletion(context.Background(), vpcClient.Client); err != nil {
|
||||
return nil, err
|
||||
@@ -180,15 +197,12 @@ func (self *SRegion) GetIVpcById(id string) (cloudprovider.ICloudVpc, error) {
|
||||
if ivpcs, err := self.GetIVpcs(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
if resourceGroup, vpcName, err := PareResourceGroupWithName(id); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
for i := 0; i < len(ivpcs); i++ {
|
||||
vpcId := ivpcs[i].GetId()
|
||||
_resourceGroup, _vpcName, _ := PareResourceGroupWithName(vpcId)
|
||||
if _resourceGroup == resourceGroup && _vpcName == vpcName {
|
||||
return ivpcs[i], nil
|
||||
}
|
||||
resourceGroup, vpcName := PareResourceGroupWithName(id, VPC_RESOURCE)
|
||||
for i := 0; i < len(ivpcs); i++ {
|
||||
vpcId := ivpcs[i].GetId()
|
||||
_resourceGroup, _vpcName := PareResourceGroupWithName(vpcId, VPC_RESOURCE)
|
||||
if _resourceGroup == resourceGroup && _vpcName == vpcName {
|
||||
return ivpcs[i], nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -316,3 +330,24 @@ func (self *SRegion) fetchInfrastructure() error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SRegion) CreateInstanceSimple(name string, imgId string, cpu int, memGB int, storageType string, dataDiskSizesGB []int, networkId string, passwd string, publicKey string) (*SInstance, error) {
|
||||
izones, err := self.GetIZones()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := 0; i < len(izones); i += 1 {
|
||||
z := izones[i].(*SZone)
|
||||
log.Debugf("Search in zone %s", z.Name)
|
||||
net := z.getNetworkById(networkId)
|
||||
if net != nil {
|
||||
passwd := seclib2.RandomPassword2(12)
|
||||
inst, err := z.getHost().CreateVM(name, imgId, 30, cpu, memGB*1024, networkId, "", "", passwd, storageType, dataDiskSizesGB, publicKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return inst.(*SInstance), nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("cannot find network %s", networkId)
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"strings"
|
||||
|
||||
"yunion.io/x/jsonutils"
|
||||
"yunion.io/x/log"
|
||||
"yunion.io/x/pkg/util/secrules"
|
||||
|
||||
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-06-01/network"
|
||||
@@ -170,17 +169,13 @@ func (self *SSecurityGroup) IsEmulated() bool {
|
||||
}
|
||||
|
||||
func (self *SSecurityGroup) Refresh() error {
|
||||
if resourceGroup, _, err := PareResourceGroupWithName(self.ID); err != nil {
|
||||
log.Errorf("Refresh SecurityGroup error %v", err)
|
||||
resourceGroup, secgrpName := PareResourceGroupWithName(self.ID, SECGRP_RESOURCE)
|
||||
networkClient := network.NewSecurityGroupsClientWithBaseURI(self.vpc.region.client.baseUrl, self.vpc.region.SubscriptionID)
|
||||
networkClient.Authorizer = self.vpc.region.client.authorizer
|
||||
if secgrp, err := networkClient.Get(context.Background(), resourceGroup, secgrpName, ""); err != nil {
|
||||
return err
|
||||
} else if err := jsonutils.Update(self, secgrp); err != nil {
|
||||
return err
|
||||
} else {
|
||||
networkClient := network.NewSecurityGroupsClientWithBaseURI(self.vpc.region.client.baseUrl, self.vpc.region.SubscriptionID)
|
||||
networkClient.Authorizer = self.vpc.region.client.authorizer
|
||||
if secgrp, err := networkClient.Get(context.Background(), resourceGroup, self.Name, ""); err != nil {
|
||||
return err
|
||||
} else if err := jsonutils.Update(self, secgrp); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -31,9 +31,10 @@ func init() {
|
||||
}
|
||||
|
||||
shellutils.R(&DiskCreateOptions{}, "disk-create", "Create disk", func(cli *azure.SRegion, args *DiskCreateOptions) error {
|
||||
resourceGroup, diskName := azure.PareResourceGroupWithName(args.NAME, azure.DISK_RESOURCE)
|
||||
if err := cli.CreateDisk(args.StorageType, args.NAME, args.SizeGb, args.Desc); err != nil {
|
||||
return err
|
||||
} else if disk, err := cli.GetDisk(azure.DefaultResourceGroup["disk"], args.NAME); err != nil {
|
||||
} else if disk, err := cli.GetDisk(resourceGroup, diskName); err != nil {
|
||||
return err
|
||||
} else {
|
||||
printObject(disk)
|
||||
@@ -49,7 +50,7 @@ func init() {
|
||||
shellutils.R(&DiskDeleteOptions{}, "disk-delete", "Delete disks", func(cli *azure.SRegion, args *DiskDeleteOptions) error {
|
||||
resourceGroup := args.ResourceGroup
|
||||
if len(resourceGroup) == 0 {
|
||||
resourceGroup = azure.DefaultResourceGroup["disk"]
|
||||
resourceGroup, _ = azure.PareResourceGroupWithName(args.NAME, azure.DISK_RESOURCE)
|
||||
}
|
||||
if disk, err := cli.GetDisk(resourceGroup, args.NAME); err != nil {
|
||||
return err
|
||||
|
||||
@@ -20,17 +20,27 @@ func init() {
|
||||
})
|
||||
|
||||
type ImageCreateOptions struct {
|
||||
Name string `helo:"Image name"`
|
||||
OsType string `helo:"Operation system" choices:"Linux|Windows"`
|
||||
BlobURI string `helo:"page blob uri"`
|
||||
NAME string `helo:"Image name"`
|
||||
OSTYPE string `helo:"Operation system" choices:"Linux|Windows"`
|
||||
BLOBURI string `helo:"page blob uri"`
|
||||
DISKSIZEGB int32 `helo:"Image size"`
|
||||
}
|
||||
|
||||
shellutils.R(&ImageCreateOptions{}, "image-create", "Create image", func(cli *azure.SRegion, args *ImageCreateOptions) error {
|
||||
if image, err := cli.CreateImageByBlob(args.Name, args.OsType, args.BlobURI); err != nil {
|
||||
if image, err := cli.CreateImageByBlob(args.NAME, args.OSTYPE, args.BLOBURI, args.DISKSIZEGB); err != nil {
|
||||
return err
|
||||
} else {
|
||||
printObject(image)
|
||||
return nil
|
||||
}
|
||||
})
|
||||
|
||||
type ImageDeleteOptions struct {
|
||||
ID string `helo:"Image ID"`
|
||||
}
|
||||
|
||||
shellutils.R(&ImageDeleteOptions{}, "image-delete", "Delete image", func(cli *azure.SRegion, args *ImageDeleteOptions) error {
|
||||
return cli.DeleteImage(args.ID)
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
@@ -18,4 +18,38 @@ func init() {
|
||||
return nil
|
||||
}
|
||||
})
|
||||
|
||||
type InstanceCrateOptions struct {
|
||||
NAME string `help:"name of instance"`
|
||||
IMAGE string `help:"image ID"`
|
||||
CPU int `help:"CPU count"`
|
||||
MEMORYGB int `help:"MemoryGB"`
|
||||
Disk []int `help:"Data disk sizes int GB"`
|
||||
STORAGE string `help:"Storage type"`
|
||||
NETWORK string `help:"Network ID"`
|
||||
PASSWD string `help:"password"`
|
||||
PublicKey string `help:"PublicKey"`
|
||||
}
|
||||
shellutils.R(&InstanceCrateOptions{}, "instance-create", "Create a instance", func(cli *azure.SRegion, args *InstanceCrateOptions) error {
|
||||
instance, e := cli.CreateInstanceSimple(args.NAME, args.IMAGE, args.CPU, args.MEMORYGB, args.STORAGE, args.Disk, args.NETWORK, args.PASSWD, args.PublicKey)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
printObject(instance)
|
||||
return nil
|
||||
})
|
||||
|
||||
type InstanceShowOptions struct {
|
||||
ID string `help:"Instance ID"`
|
||||
}
|
||||
shellutils.R(&InstanceShowOptions{}, "instance-show", "Show intance detail", func(cli *azure.SRegion, args *InstanceShowOptions) error {
|
||||
resourceGroup, instanceName := azure.PareResourceGroupWithName(args.ID, azure.INSTANCE_RESOURCE)
|
||||
if instance, err := cli.GetInstance(resourceGroup, instanceName); err != nil {
|
||||
return err
|
||||
} else {
|
||||
printObject(instance)
|
||||
return nil
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package shell
|
||||
|
||||
import (
|
||||
"yunion.io/x/onecloud/pkg/util/azure"
|
||||
"yunion.io/x/onecloud/pkg/util/shellutils"
|
||||
)
|
||||
|
||||
func init() {
|
||||
type NetworkListOptions struct {
|
||||
Limit int `help:"page size"`
|
||||
Offset int `help:"page offset"`
|
||||
}
|
||||
shellutils.R(&NetworkListOptions{}, "network-list", "List networks", func(cli *azure.SRegion, args *NetworkListOptions) error {
|
||||
if vpcs, err := cli.GetIVpcs(); err != nil {
|
||||
return nil
|
||||
} else {
|
||||
networks := make([]azure.Subnet, 0)
|
||||
for _, _vpc := range vpcs {
|
||||
vpc := _vpc.(*azure.SVpc)
|
||||
if _networks := vpc.GetNetworks(); len(_networks) > 0 {
|
||||
networks = append(networks, _networks...)
|
||||
}
|
||||
|
||||
}
|
||||
printList(networks, len(networks), args.Offset, args.Limit, []string{})
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
type NetworkInterfaceListOptions struct {
|
||||
Limit int `help:"page size"`
|
||||
Offset int `help:"page offset"`
|
||||
}
|
||||
|
||||
shellutils.R(&NetworkInterfaceListOptions{}, "network-interface-list", "List network interface", func(cli *azure.SRegion, args *NetworkInterfaceListOptions) error {
|
||||
if interfaces, err := cli.GetNetworkInterfaces(); err != nil {
|
||||
return err
|
||||
} else {
|
||||
printList(interfaces, len(interfaces), args.Offset, args.Limit, []string{})
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
type NetworkInterfaceCreateOptions struct {
|
||||
NAME string `help:"Nic interface name"`
|
||||
IP string `help:"Nic private ip address"`
|
||||
SUBNET string `help:"Subnet ID"`
|
||||
}
|
||||
|
||||
shellutils.R(&NetworkInterfaceCreateOptions{}, "network-interface-create", "Create network interface", func(cli *azure.SRegion, args *NetworkInterfaceCreateOptions) error {
|
||||
if nic, err := cli.CreateNetworkInterface(args.NAME, args.IP, args.SUBNET); err != nil {
|
||||
return err
|
||||
} else {
|
||||
printObject(nic)
|
||||
return nil
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package shell
|
||||
|
||||
import (
|
||||
"yunion.io/x/onecloud/pkg/util/azure"
|
||||
"yunion.io/x/onecloud/pkg/util/shellutils"
|
||||
)
|
||||
|
||||
func init() {
|
||||
type VpcListOptions struct {
|
||||
Limit int `help:"page size"`
|
||||
Offset int `help:"page offset"`
|
||||
}
|
||||
shellutils.R(&VpcListOptions{}, "vpc-list", "List vpcs", func(cli *azure.SRegion, args *VpcListOptions) error {
|
||||
if vpcs, err := cli.GetIVpcs(); err != nil {
|
||||
return err
|
||||
} else {
|
||||
printList(vpcs, len(vpcs), args.Offset, args.Limit, []string{})
|
||||
return nil
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -49,9 +49,10 @@ func (self *SStorage) GetCapacityMB() int {
|
||||
}
|
||||
|
||||
func (self *SStorage) CreateIDisk(name string, sizeGb int, desc string) (cloudprovider.ICloudDisk, error) {
|
||||
if err := self.zone.region.createDisk(self.storageType, name, int32(sizeGb), desc); err != nil {
|
||||
resourceGroup, diskName := PareResourceGroupWithName(name, DISK_RESOURCE)
|
||||
if err := self.zone.region.createDisk(self.storageType, diskName, int32(sizeGb), desc); err != nil {
|
||||
return nil, err
|
||||
} else if disk, err := self.zone.region.GetDisk(DefaultResourceGroup["disk"], name); err != nil {
|
||||
} else if disk, err := self.zone.region.GetDisk(resourceGroup, diskName); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
disk.storage = self
|
||||
@@ -60,15 +61,12 @@ func (self *SStorage) CreateIDisk(name string, sizeGb int, desc string) (cloudpr
|
||||
}
|
||||
|
||||
func (self *SStorage) GetIDisk(idStr string) (cloudprovider.ICloudDisk, error) {
|
||||
if resourceGroup, diskName, err := PareResourceGroupWithName(idStr); err != nil {
|
||||
resourceGroup, diskName := PareResourceGroupWithName(idStr, DISK_RESOURCE)
|
||||
if disk, err := self.zone.region.GetDisk(resourceGroup, diskName); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
if disk, err := self.zone.region.GetDisk(resourceGroup, diskName); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
disk.storage = self
|
||||
return disk, nil
|
||||
}
|
||||
disk.storage = self
|
||||
return disk, nil
|
||||
}
|
||||
return nil, cloudprovider.ErrNotImplemented
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -18,13 +19,16 @@ import (
|
||||
|
||||
storageaccount "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2018-02-01/storage"
|
||||
"github.com/Azure/azure-sdk-for-go/storage"
|
||||
|
||||
"github.com/Microsoft/azure-vhd-utils/vhdcore/common"
|
||||
"github.com/Microsoft/azure-vhd-utils/vhdcore/diskstream"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultStorageAccount string = "storage"
|
||||
DefaultBlobContainer string = "image-cache"
|
||||
|
||||
DefaultReadBlockSize uint64 = 4 * 1024 * 1024
|
||||
DefaultReadBlockSize int64 = 4 * 1024 * 1024
|
||||
)
|
||||
|
||||
type SStoragecache struct {
|
||||
@@ -103,7 +107,7 @@ func (self *SRegion) CreateStorageAccount(resourceGroup, storageAccount string)
|
||||
sku := storageaccount.Sku{Name: storageaccount.SkuName("Standard_GRS")}
|
||||
params := storageaccount.AccountCreateParameters{Sku: &sku, Location: &self.Name, Kind: storageaccount.Kind("Storage")}
|
||||
if len(resourceGroup) == 0 {
|
||||
resourceGroup = DefaultResourceGroup["storage"]
|
||||
resourceGroup = DefaultResourceGroups[STORAGE_RESOURCE]
|
||||
}
|
||||
if len(storageAccount) == 0 {
|
||||
storageAccount = fmt.Sprintf("%s%s", self.Name, DefaultStorageAccount)
|
||||
@@ -156,7 +160,7 @@ func (self *SRegion) getStorageAccountKey(resourceGroup, storageAccount string)
|
||||
|
||||
func (self *SRegion) CheckBlobContainer(resourceGroup, storageAccount, blobName string) error {
|
||||
if len(resourceGroup) == 0 {
|
||||
resourceGroup = DefaultResourceGroup["storage"]
|
||||
resourceGroup = DefaultResourceGroups[STORAGE_RESOURCE]
|
||||
}
|
||||
if len(storageAccount) == 0 {
|
||||
storageAccount = fmt.Sprintf("%s%s", self.Name, DefaultStorageAccount)
|
||||
@@ -247,7 +251,7 @@ func (self *SRegion) getContainerFiles(storageAccount, accessKey, containerName
|
||||
|
||||
func (self *SRegion) ListContainerFiles(resourceGroup, storageAccount, blobName string) ([]Blob, error) {
|
||||
if len(resourceGroup) == 0 {
|
||||
resourceGroup = DefaultResourceGroup["storage"]
|
||||
resourceGroup = DefaultResourceGroups[STORAGE_RESOURCE]
|
||||
}
|
||||
if len(storageAccount) == 0 {
|
||||
storageAccount = fmt.Sprintf("%s%s", self.Name, DefaultStorageAccount)
|
||||
@@ -276,17 +280,17 @@ func (self *SRegion) uploadContainerFileByReader(storageAccount, accessKey, cont
|
||||
if err := blobClient.PutPageBlob(&storage.PutBlobOptions{}); err != nil {
|
||||
return "", err
|
||||
}
|
||||
var readed uint64 = 0
|
||||
for i := 0; i < int(uint64(size)/DefaultReadBlockSize); i++ {
|
||||
if err := blobClient.WriteRange(storage.BlobRange{Start: readed, End: readed + DefaultReadBlockSize - 1}, content, &storage.PutPageOptions{}); err != nil {
|
||||
var readed int64 = 0
|
||||
for i := 0; i < int(size/DefaultReadBlockSize); i++ {
|
||||
if err := blobClient.WriteRange(storage.BlobRange{Start: uint64(readed), End: uint64(readed + DefaultReadBlockSize - 1)}, content, &storage.PutPageOptions{}); err != nil {
|
||||
return "", err
|
||||
}
|
||||
readed += DefaultReadBlockSize
|
||||
log.Debugf("Upload %s %f%% to %s", fileName, float64(readed)/float64(size)*100, storageAccount)
|
||||
}
|
||||
if extraSize := uint64(size) % DefaultReadBlockSize; extraSize > 0 {
|
||||
if extraSize := size % DefaultReadBlockSize; extraSize > 0 {
|
||||
log.Debugf("Upload %s extra size: %d to %s", fileName, extraSize, storageAccount)
|
||||
if err := blobClient.WriteRange(storage.BlobRange{Start: readed, End: readed + extraSize - 1}, content, &storage.PutPageOptions{}); err != nil {
|
||||
if err := blobClient.WriteRange(storage.BlobRange{Start: uint64(readed), End: uint64(readed + extraSize - 1)}, content, &storage.PutPageOptions{}); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
@@ -295,22 +299,62 @@ func (self *SRegion) uploadContainerFileByReader(storageAccount, accessKey, cont
|
||||
}
|
||||
}
|
||||
|
||||
func (self *SRegion) uploadContainerFileByPath(storageAccount, accessKey, containerName, filePath string) (string, error) {
|
||||
if f, err := os.Open(filePath); err != nil {
|
||||
func (self *SRegion) uploadContainerFileByPath(storageAccount, accessKey, containerName, localVHDPath string) (string, error) {
|
||||
if err := ensureVHDSanity(localVHDPath); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if diskStream, err := diskstream.CreateNewDiskStream(localVHDPath); err != nil {
|
||||
return "", err
|
||||
} else {
|
||||
defer f.Close()
|
||||
if finfo, err := f.Stat(); err != nil {
|
||||
defer diskStream.Close()
|
||||
storageClient, err := storage.NewBasicClientOnSovereignCloud(storageAccount, accessKey, self.client.env)
|
||||
if err != nil {
|
||||
return "", err
|
||||
} else {
|
||||
return self.uploadContainerFileByReader(storageAccount, accessKey, containerName, finfo.Name(), f, finfo.Size())
|
||||
}
|
||||
blobServiceClient := storageClient.GetBlobService()
|
||||
containerClinet := blobServiceClient.GetContainerReference(containerName)
|
||||
blobName := path.Base(localVHDPath)
|
||||
blobClient := containerClinet.GetBlobReference(blobName)
|
||||
if _, err := blobClient.DeleteIfExists(&storage.DeleteBlobOptions{}); err != nil {
|
||||
return "", err
|
||||
}
|
||||
blobClient.Properties.ContentLength = diskStream.GetSize()
|
||||
if err := blobClient.PutPageBlob(&storage.PutBlobOptions{}); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var rangesToSkip []*common.IndexRange
|
||||
uploadableRanges, err := LocateUploadableRanges(diskStream, rangesToSkip, DefaultReadBlockSize)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if uploadableRanges, err = DetectEmptyRanges(diskStream, uploadableRanges); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
cxt := &DiskUploadContext{
|
||||
VhdStream: diskStream,
|
||||
UploadableRanges: uploadableRanges,
|
||||
AlreadyProcessedBytes: common.TotalRangeLength(rangesToSkip),
|
||||
BlobServiceClient: blobServiceClient,
|
||||
ContainerName: containerName,
|
||||
BlobName: blobName,
|
||||
Parallelism: 3,
|
||||
Resume: false,
|
||||
MD5Hash: []byte(""), //localMetaData.FileMetaData.MD5Hash,
|
||||
}
|
||||
|
||||
if err := Upload(cxt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return blobClient.GetURL(), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (self *SRegion) UploadContainerFiles(resourceGroup, storageAccount, containerName, filePath string) (string, error) {
|
||||
if len(resourceGroup) == 0 {
|
||||
resourceGroup = DefaultResourceGroup["storage"]
|
||||
resourceGroup = DefaultResourceGroups[STORAGE_RESOURCE]
|
||||
}
|
||||
if len(storageAccount) == 0 {
|
||||
storageAccount = fmt.Sprintf("%s%s", self.Name, DefaultStorageAccount)
|
||||
@@ -339,22 +383,34 @@ func (self *SStoragecache) uploadImage(userCred mcclient.TokenCredential, imageI
|
||||
if !strings.HasSuffix(imageNameOnBlob, ".vhd") {
|
||||
imageNameOnBlob = fmt.Sprintf("%s.vhd", imageNameOnBlob)
|
||||
}
|
||||
tmpFile := fmt.Sprintf("/tmp/%s", imageNameOnBlob)
|
||||
|
||||
f, err := os.Create(tmpFile)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
if _, err := io.Copy(f, reader); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
storageAccount := fmt.Sprintf("%s%s", self.region.Name, DefaultStorageAccount)
|
||||
|
||||
if err := self.region.CheckBlobContainer(DefaultResourceGroup["storage"], storageAccount, DefaultBlobContainer); err != nil {
|
||||
if err := self.region.CheckBlobContainer(DefaultResourceGroups[STORAGE_RESOURCE], storageAccount, DefaultBlobContainer); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
size, _ := meta.Int("size")
|
||||
accessKey, err := self.region.getStorageAccountKey(DefaultResourceGroup["storage"], storageAccount)
|
||||
accessKey, err := self.region.getStorageAccountKey(DefaultResourceGroups[STORAGE_RESOURCE], storageAccount)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
blobURI, err := self.region.uploadContainerFileByReader(storageAccount, accessKey, DefaultBlobContainer, imageNameOnBlob, reader, size)
|
||||
blobURI, err := self.region.uploadContainerFileByPath(storageAccount, accessKey, DefaultBlobContainer, tmpFile)
|
||||
os.Remove(tmpFile)
|
||||
//blobURI, err := self.region.uploadContainerFileByReader(storageAccount, accessKey, DefaultBlobContainer, imageNameOnBlob, reader, size)
|
||||
if err != nil {
|
||||
log.Errorf("uploadContainerFileByReader error: %v", err)
|
||||
log.Errorf("uploadContainerFileByPath error: %v", err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
@@ -378,10 +434,10 @@ func (self *SStoragecache) uploadImage(userCred mcclient.TokenCredential, imageI
|
||||
nameIdx += 1
|
||||
}
|
||||
|
||||
if image, err := self.region.CreateImageByBlob(imageName, osType, blobURI); err != nil {
|
||||
if image, err := self.region.CreateImageByBlob(imageName, osType, blobURI, int32(size>>30)); err != nil {
|
||||
return "", err
|
||||
} else {
|
||||
return image.GetId(), nil
|
||||
return image.GetGlobalId(), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
package azure
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/Azure/azure-sdk-for-go/storage"
|
||||
"yunion.io/x/onecloud/pkg/util/azure/concurrent"
|
||||
"yunion.io/x/onecloud/pkg/util/azure/progress"
|
||||
|
||||
"github.com/Microsoft/azure-vhd-utils/vhdcore/block/bitmap"
|
||||
"github.com/Microsoft/azure-vhd-utils/vhdcore/common"
|
||||
"github.com/Microsoft/azure-vhd-utils/vhdcore/diskstream"
|
||||
"github.com/Microsoft/azure-vhd-utils/vhdcore/footer"
|
||||
"github.com/Microsoft/azure-vhd-utils/vhdcore/validator"
|
||||
)
|
||||
|
||||
// DiskUploadContext type describes VHD upload context, this includes the disk stream to read from, the ranges of
|
||||
// the stream to read, the destination blob and it's container, the client to communicate with Azure storage and
|
||||
// the number of parallel go-routines to use for upload.
|
||||
//
|
||||
|
||||
type DataWithRange struct {
|
||||
Range *common.IndexRange
|
||||
Data []byte
|
||||
}
|
||||
|
||||
type DiskUploadContext struct {
|
||||
VhdStream *diskstream.DiskStream // The stream whose ranges needs to be uploaded
|
||||
AlreadyProcessedBytes int64 // The size in bytes already uploaded
|
||||
UploadableRanges []*common.IndexRange // The subset of stream ranges to be uploaded
|
||||
BlobServiceClient storage.BlobStorageClient // The client to make Azure blob service API calls
|
||||
ContainerName string // The container in which page blob resides
|
||||
BlobName string // The destination page blob name
|
||||
Parallelism int // The number of concurrent goroutines to be used for upload
|
||||
Resume bool // Indicate whether this is a new or resuming upload
|
||||
MD5Hash []byte // MD5Hash to be set in the page blob properties once upload finishes
|
||||
}
|
||||
|
||||
// oneMB is one MegaByte
|
||||
//
|
||||
const oneMB = float64(1048576)
|
||||
|
||||
// Upload uploads the disk ranges described by the parameter cxt, this parameter describes the disk stream to
|
||||
// read from, the ranges of the stream to read, the destination blob and it's container, the client to communicate
|
||||
// with Azure storage and the number of parallel go-routines to use for upload.
|
||||
//
|
||||
func Upload(cxt *DiskUploadContext) error {
|
||||
// Get the channel that contains stream of disk data to upload
|
||||
dataWithRangeChan, streamReadErrChan := GetDataWithRanges(cxt.VhdStream, cxt.UploadableRanges)
|
||||
|
||||
// The channel to send upload request to load-balancer
|
||||
requtestChan := make(chan *concurrent.Request, 0)
|
||||
|
||||
// Prepare and start the load-balancer that load request across 'cxt.Parallelism' workers
|
||||
loadBalancer := concurrent.NewBalancer(cxt.Parallelism)
|
||||
loadBalancer.Init()
|
||||
workerErrorChan, allWorkersFinishedChan := loadBalancer.Run(requtestChan)
|
||||
|
||||
// Calculate the actual size of the data to upload
|
||||
uploadSizeInBytes := int64(0)
|
||||
for _, r := range cxt.UploadableRanges {
|
||||
uploadSizeInBytes += r.Length()
|
||||
}
|
||||
fmt.Printf("\nEffective upload size: %.2f MB (from %.2f MB originally)", float64(uploadSizeInBytes)/oneMB, float64(cxt.VhdStream.GetSize())/oneMB)
|
||||
|
||||
// Prepare and start the upload progress tracker
|
||||
uploadProgress := progress.NewStatus(cxt.Parallelism, cxt.AlreadyProcessedBytes, uploadSizeInBytes, progress.NewComputestateDefaultSize())
|
||||
progressChan := uploadProgress.Run()
|
||||
|
||||
// read progress status from progress tracker and print it
|
||||
go readAndPrintProgress(progressChan, cxt.Resume)
|
||||
|
||||
// listen for errors reported by workers and print it
|
||||
var allWorkSucceeded = true
|
||||
go func() {
|
||||
for {
|
||||
fmt.Println(<-workerErrorChan)
|
||||
allWorkSucceeded = false
|
||||
}
|
||||
}()
|
||||
|
||||
var err error
|
||||
L:
|
||||
for {
|
||||
select {
|
||||
case dataWithRange, ok := <-dataWithRangeChan:
|
||||
if !ok {
|
||||
close(requtestChan)
|
||||
break L
|
||||
}
|
||||
|
||||
// Create work request
|
||||
//
|
||||
containerClinet := cxt.BlobServiceClient.GetContainerReference(cxt.ContainerName)
|
||||
blobClient := containerClinet.GetBlobReference(cxt.BlobName)
|
||||
req := &concurrent.Request{
|
||||
Work: func() error {
|
||||
err := blobClient.WriteRange(
|
||||
storage.BlobRange{Start: uint64(dataWithRange.Range.Start), End: uint64(dataWithRange.Range.End)},
|
||||
bytes.NewReader(dataWithRange.Data),
|
||||
&storage.PutPageOptions{},
|
||||
)
|
||||
if err == nil {
|
||||
uploadProgress.ReportBytesProcessedCount(dataWithRange.Range.Length())
|
||||
}
|
||||
return err
|
||||
},
|
||||
ShouldRetry: func(e error) bool {
|
||||
return true
|
||||
},
|
||||
ID: dataWithRange.Range.String(),
|
||||
}
|
||||
|
||||
// Send work request to load balancer for processing
|
||||
//
|
||||
requtestChan <- req
|
||||
case err = <-streamReadErrChan:
|
||||
close(requtestChan)
|
||||
loadBalancer.TearDownWorkers()
|
||||
break L
|
||||
}
|
||||
}
|
||||
|
||||
<-allWorkersFinishedChan
|
||||
uploadProgress.Close()
|
||||
|
||||
if !allWorkSucceeded {
|
||||
err = errors.New("\nUpload Incomplete: Some blocks of the VHD failed to upload, rerun the command to upload those blocks")
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
fmt.Printf("\r Completed: %3d%% [%10.2f MB] RemainingTime: %02dh:%02dm:%02ds Throughput: %d Mb/sec %2c ",
|
||||
100,
|
||||
float64(uploadSizeInBytes)/oneMB,
|
||||
0, 0, 0,
|
||||
0, ' ')
|
||||
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// GetDataWithRanges with start reading and streaming the ranges from the disk identified by the parameter ranges.
|
||||
// It returns two channels, a data channel to stream the disk ranges and a channel to send any error while reading
|
||||
// the disk. On successful completion the data channel will be closed. the caller must not expect any more value in
|
||||
// the data channel if the error channel is signaled.
|
||||
//
|
||||
func GetDataWithRanges(stream *diskstream.DiskStream, ranges []*common.IndexRange) (<-chan *DataWithRange, <-chan error) {
|
||||
dataWithRangeChan := make(chan *DataWithRange, 0)
|
||||
errorChan := make(chan error, 0)
|
||||
go func() {
|
||||
for _, r := range ranges {
|
||||
dataWithRange := &DataWithRange{
|
||||
Range: r,
|
||||
Data: make([]byte, r.Length()),
|
||||
}
|
||||
_, err := stream.Seek(r.Start, 0)
|
||||
if err != nil {
|
||||
errorChan <- err
|
||||
return
|
||||
}
|
||||
_, err = io.ReadFull(stream, dataWithRange.Data)
|
||||
if err != nil {
|
||||
errorChan <- err
|
||||
return
|
||||
}
|
||||
dataWithRangeChan <- dataWithRange
|
||||
}
|
||||
close(dataWithRangeChan)
|
||||
}()
|
||||
return dataWithRangeChan, errorChan
|
||||
}
|
||||
|
||||
// readAndPrintProgress reads the progress records from the given progress channel and output it. It reads the
|
||||
// progress record until the channel is closed.
|
||||
//
|
||||
func readAndPrintProgress(progressChan <-chan *progress.Record, resume bool) {
|
||||
var spinChars = [4]rune{'\\', '|', '/', '-'}
|
||||
s := time.Time{}
|
||||
if resume {
|
||||
fmt.Println("\nResuming VHD upload..")
|
||||
} else {
|
||||
fmt.Println("\nUploading the VHD..")
|
||||
}
|
||||
|
||||
i := 0
|
||||
for progressRecord := range progressChan {
|
||||
if i == 4 {
|
||||
i = 0
|
||||
}
|
||||
t := s.Add(progressRecord.RemainingDuration)
|
||||
fmt.Printf("\r Completed: %3d%% [%10.2f MB] RemainingTime: %02dh:%02dm:%02ds Throughput: %d Mb/sec %2c ",
|
||||
int(progressRecord.PercentComplete),
|
||||
float64(progressRecord.BytesProcessed)/oneMB,
|
||||
t.Hour(), t.Minute(), t.Second(),
|
||||
int(progressRecord.AverageThroughputMbPerSecond),
|
||||
spinChars[i],
|
||||
)
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
func ensureVHDSanity(localVHDPath string) error {
|
||||
if err := validator.ValidateVhd(localVHDPath); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := validator.ValidateVhdSize(localVHDPath); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func LocateUploadableRanges(stream *diskstream.DiskStream, rangesToSkip []*common.IndexRange, pageSizeInBytes int64) ([]*common.IndexRange, error) {
|
||||
var err error
|
||||
var diskRanges = make([]*common.IndexRange, 0)
|
||||
stream.EnumerateExtents(func(ext *diskstream.StreamExtent, extErr error) bool {
|
||||
if extErr != nil {
|
||||
err = extErr
|
||||
return false
|
||||
}
|
||||
|
||||
diskRanges = append(diskRanges, ext.Range)
|
||||
return true
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
diskRanges = common.SubtractRanges(diskRanges, rangesToSkip)
|
||||
diskRanges = common.ChunkRangesBySize(diskRanges, pageSizeInBytes)
|
||||
return diskRanges, nil
|
||||
}
|
||||
|
||||
func DetectEmptyRanges(diskStream *diskstream.DiskStream, uploadableRanges []*common.IndexRange) ([]*common.IndexRange, error) {
|
||||
if diskStream.GetDiskType() != footer.DiskTypeFixed {
|
||||
return uploadableRanges, nil
|
||||
}
|
||||
|
||||
fmt.Println("\nDetecting empty ranges..")
|
||||
totalRangesCount := len(uploadableRanges)
|
||||
lastIndex := int32(-1)
|
||||
emptyRangesCount := int32(0)
|
||||
bits := make([]byte, int32(math.Ceil(float64(totalRangesCount)/float64(8))))
|
||||
bmap := bitmap.NewBitMapFromByteSliceCopy(bits)
|
||||
indexChan, errChan := LocateNonEmptyRangeIndices(diskStream, uploadableRanges)
|
||||
L:
|
||||
for {
|
||||
select {
|
||||
case index, ok := <-indexChan:
|
||||
if !ok {
|
||||
break L
|
||||
}
|
||||
bmap.Set(index, true)
|
||||
emptyRangesCount += index - lastIndex - 1
|
||||
lastIndex = index
|
||||
fmt.Printf("\r Empty ranges : %d/%d", emptyRangesCount, totalRangesCount)
|
||||
case err := <-errChan:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// Remove empty ranges from the uploadable ranges slice.
|
||||
i := int32(0)
|
||||
for j := 0; j < totalRangesCount; j++ {
|
||||
if set, _ := bmap.Get(int32(j)); set {
|
||||
uploadableRanges[i] = uploadableRanges[j]
|
||||
i++
|
||||
}
|
||||
}
|
||||
uploadableRanges = uploadableRanges[:i]
|
||||
return uploadableRanges, nil
|
||||
}
|
||||
|
||||
func LocateNonEmptyRangeIndices(stream *diskstream.DiskStream, ranges []*common.IndexRange) (<-chan int32, <-chan error) {
|
||||
indexChan := make(chan int32, 0)
|
||||
errorChan := make(chan error, 0)
|
||||
go func() {
|
||||
count := int64(-1)
|
||||
var buf []byte
|
||||
for index, r := range ranges {
|
||||
if count != r.Length() {
|
||||
count = r.Length()
|
||||
buf = make([]byte, count)
|
||||
}
|
||||
|
||||
_, err := stream.Seek(r.Start, 0)
|
||||
if err != nil {
|
||||
errorChan <- err
|
||||
return
|
||||
}
|
||||
_, err = io.ReadFull(stream, buf)
|
||||
if err != nil {
|
||||
errorChan <- err
|
||||
return
|
||||
}
|
||||
if !isAllZero(buf) {
|
||||
indexChan <- int32(index)
|
||||
}
|
||||
}
|
||||
close(indexChan)
|
||||
}()
|
||||
return indexChan, errorChan
|
||||
}
|
||||
|
||||
// isAllZero returns true if the given byte slice contain all zeros
|
||||
//
|
||||
func isAllZero(buf []byte) bool {
|
||||
l := len(buf)
|
||||
j := 0
|
||||
for ; j < l; j++ {
|
||||
if buf[j] != byte(0) {
|
||||
break
|
||||
}
|
||||
}
|
||||
return j == l
|
||||
}
|
||||
+10
-7
@@ -64,8 +64,8 @@ func (self *SVpc) GetName() string {
|
||||
}
|
||||
|
||||
func (self *SVpc) GetGlobalId() string {
|
||||
resourceGroup, _, _ := PareResourceGroupWithName(self.ID)
|
||||
return fmt.Sprintf("resourceGroups/%s/providers/vpc/%s", resourceGroup, self.Name)
|
||||
resourceGroup, vpcName := PareResourceGroupWithName(self.ID, VPC_RESOURCE)
|
||||
return fmt.Sprintf("resourceGroups/%s/providers/vpc/%s", resourceGroup, vpcName)
|
||||
}
|
||||
|
||||
func (self *SVpc) IsEmulated() bool {
|
||||
@@ -83,9 +83,8 @@ func (self *SVpc) GetCidrBlock() string {
|
||||
func (self *SVpc) Delete() error {
|
||||
vpcClient := network.NewVirtualNetworksClientWithBaseURI(self.region.client.baseUrl, self.region.client.subscriptionId)
|
||||
vpcClient.Authorizer = self.region.client.authorizer
|
||||
if resourceGroup, vpcName, err := PareResourceGroupWithName(self.ID); err != nil {
|
||||
return cloudprovider.ErrNotFound
|
||||
} else if result, err := vpcClient.Delete(context.Background(), resourceGroup, vpcName); err != nil {
|
||||
resourceGroup, vpcName := PareResourceGroupWithName(self.ID, VPC_RESOURCE)
|
||||
if result, err := vpcClient.Delete(context.Background(), resourceGroup, vpcName); err != nil {
|
||||
return err
|
||||
} else if err := result.WaitForCompletion(context.Background(), vpcClient.Client); err != nil {
|
||||
return err
|
||||
@@ -197,10 +196,10 @@ func (self *SVpc) GetStatus() string {
|
||||
}
|
||||
|
||||
func (self *SVpc) Refresh() error {
|
||||
resourceGroup, _, _ := PareResourceGroupWithName(self.ID)
|
||||
resourceGroup, vpcName := PareResourceGroupWithName(self.ID, VPC_RESOURCE)
|
||||
vpcClient := network.NewVirtualNetworksClientWithBaseURI(self.region.client.baseUrl, self.region.SubscriptionID)
|
||||
vpcClient.Authorizer = self.region.client.authorizer
|
||||
if result, err := vpcClient.Get(context.Background(), resourceGroup, self.Name, ""); err != nil {
|
||||
if result, err := vpcClient.Get(context.Background(), resourceGroup, vpcName, ""); err != nil {
|
||||
return cloudprovider.ErrNotFound
|
||||
} else if err := jsonutils.Update(self, result); err != nil {
|
||||
return err
|
||||
@@ -214,3 +213,7 @@ func (self *SVpc) addWire(wire *SWire) {
|
||||
}
|
||||
self.iwires = append(self.iwires, wire)
|
||||
}
|
||||
|
||||
func (self *SVpc) GetNetworks() []Subnet {
|
||||
return self.Properties.Subnets
|
||||
}
|
||||
|
||||
@@ -78,8 +78,8 @@ func (self *SRegion) createNetwork(vpc *SVpc, subnetName string, cidr string, de
|
||||
|
||||
networkClient := network.NewVirtualNetworksClientWithBaseURI(self.client.baseUrl, self.SubscriptionID)
|
||||
networkClient.Authorizer = self.client.authorizer
|
||||
resourceGroup, _, _ := PareResourceGroupWithName(vpc.ID)
|
||||
if result, err := networkClient.CreateOrUpdate(context.Background(), resourceGroup, vpc.Name, params); err != nil {
|
||||
resourceGroup, vpcName := PareResourceGroupWithName(vpc.ID, VPC_RESOURCE)
|
||||
if result, err := networkClient.CreateOrUpdate(context.Background(), resourceGroup, vpcName, params); err != nil {
|
||||
return "", err
|
||||
} else if err := result.WaitForCompletion(context.Background(), networkClient.Client); err != nil {
|
||||
return "", err
|
||||
@@ -141,10 +141,12 @@ func (self *SWire) getNetworkById(networkId string) *SNetwork {
|
||||
log.Errorf("getNetworkById error: %v", err)
|
||||
return nil
|
||||
} else {
|
||||
resourceGroup, networkName := PareResourceGroupWithName(networkId, NETWORK_RESOURCE)
|
||||
log.Debugf("search for networks %d", len(networks))
|
||||
for i := 0; i < len(networks); i++ {
|
||||
network := networks[i].(*SNetwork)
|
||||
if network.ID == networkId {
|
||||
_resourceGroup, _networkName := PareResourceGroupWithName(network.ID, NETWORK_RESOURCE)
|
||||
if resourceGroup == _resourceGroup && networkName == _networkName {
|
||||
return network
|
||||
}
|
||||
}
|
||||
|
||||
+18
-3
@@ -3,8 +3,10 @@ package azure
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"yunion.io/x/jsonutils"
|
||||
"yunion.io/x/log"
|
||||
"yunion.io/x/onecloud/pkg/cloudprovider"
|
||||
"yunion.io/x/pkg/utils"
|
||||
|
||||
@@ -118,9 +120,9 @@ func (self *SZone) getStorageByType(storageType string) (*SStorage, error) {
|
||||
return nil, err
|
||||
} else {
|
||||
for i := 0; i < len(storages); i += 1 {
|
||||
storage := storages[i].(*SStorage)
|
||||
if storage.storageType == storageType {
|
||||
return storage, nil
|
||||
_storage := storages[i].(*SStorage)
|
||||
if strings.ToLower(_storage.storageType) == strings.ToLower(storageType) {
|
||||
return _storage, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -149,3 +151,16 @@ func (self *SZone) addWire(wire *SWire) {
|
||||
func (self *SZone) GetIWires() ([]cloudprovider.ICloudWire, error) {
|
||||
return self.iwires, nil
|
||||
}
|
||||
|
||||
func (self *SZone) getNetworkById(networId string) *SNetwork {
|
||||
log.Debugf("Search in wires %d", len(self.iwires))
|
||||
for i := 0; i < len(self.iwires); i += 1 {
|
||||
log.Debugf("Search in wire %s", self.iwires[i].GetName())
|
||||
wire := self.iwires[i].(*SWire)
|
||||
net := wire.getNetworkById(networId)
|
||||
if net != nil {
|
||||
return net
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -109,8 +109,8 @@ func (self *SVirtualMachine) GetINics() ([]cloudprovider.ICloudNic, error) {
|
||||
return nil, cloudprovider.ErrNotImplemented
|
||||
}
|
||||
|
||||
func (self *SVirtualMachine) GetEIP() cloudprovider.ICloudEIP {
|
||||
return nil
|
||||
func (self *SVirtualMachine) GetIEIP() (cloudprovider.ICloudEIP, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (self *SVirtualMachine) GetVcpuCount() int8 {
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
|
||||
"yunion.io/x/log"
|
||||
)
|
||||
|
||||
const (
|
||||
PROTOCOL_TTY string = "tty"
|
||||
//PROTOCOL_VNC string = "vnc"
|
||||
)
|
||||
|
||||
type ICommand interface {
|
||||
GetProtocol() string
|
||||
GetCommand() *exec.Cmd
|
||||
Cleanup() error
|
||||
}
|
||||
|
||||
type BaseCommand struct {
|
||||
name string
|
||||
args []string
|
||||
}
|
||||
|
||||
func NewBaseCommand(name string, args ...string) *BaseCommand {
|
||||
return &BaseCommand{
|
||||
name: name,
|
||||
args: args,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *BaseCommand) AppendArgs(args ...string) *BaseCommand {
|
||||
for _, arg := range args {
|
||||
c.args = append(c.args, arg)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (c BaseCommand) GetCommand() *exec.Cmd {
|
||||
return exec.Command(c.name, c.args...)
|
||||
}
|
||||
|
||||
func (c BaseCommand) Cleanup() error {
|
||||
log.Infof("BaseCommand Cleanup do nothing")
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
|
||||
"yunion.io/x/log"
|
||||
)
|
||||
|
||||
type Kubectl struct {
|
||||
*BaseCommand
|
||||
kubeconfig string
|
||||
}
|
||||
|
||||
func NewKubectlCommand(kubeconfig, namespace string) *Kubectl {
|
||||
name := "kubectl"
|
||||
if len(namespace) == 0 {
|
||||
namespace = "default"
|
||||
}
|
||||
cmd := NewBaseCommand(name, "--namespace", namespace)
|
||||
return &Kubectl{
|
||||
BaseCommand: cmd,
|
||||
kubeconfig: kubeconfig,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Kubectl) GetCommand() *exec.Cmd {
|
||||
cmd := c.BaseCommand.GetCommand()
|
||||
cmd.Env = append(cmd.Env, fmt.Sprintf("KUBECONFIG=%s", c.kubeconfig))
|
||||
return cmd
|
||||
}
|
||||
|
||||
func (c Kubectl) GetProtocol() string {
|
||||
return PROTOCOL_TTY
|
||||
}
|
||||
|
||||
func (c *Kubectl) Cleanup() error {
|
||||
log.Debugf("Remove temp kubeconfig file: %s", c.kubeconfig)
|
||||
return os.Remove(c.kubeconfig)
|
||||
}
|
||||
|
||||
type KubectlExec struct {
|
||||
*Kubectl
|
||||
}
|
||||
|
||||
func (c *Kubectl) Exec() *KubectlExec {
|
||||
// Execute a command in a container
|
||||
cmd := &KubectlExec{
|
||||
Kubectl: c,
|
||||
}
|
||||
cmd.AppendArgs("exec")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func (c *KubectlExec) Stdin() *KubectlExec {
|
||||
// -i: Pass stdin to the container
|
||||
c.AppendArgs("-i")
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *KubectlExec) TTY() *KubectlExec {
|
||||
// -t: Stdin is a TTY
|
||||
c.AppendArgs("-t")
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *KubectlExec) Container(name string) *KubectlExec {
|
||||
if len(name) == 0 {
|
||||
return c
|
||||
}
|
||||
// -c: Container name. If ommitted, the first container in the pod will be chosen
|
||||
c.AppendArgs("-c", name)
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *KubectlExec) Pod(name string) *KubectlExec {
|
||||
// Pod name
|
||||
c.AppendArgs(name)
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *KubectlExec) Command(cmd string, args ...string) *KubectlExec {
|
||||
c.AppendArgs("--", cmd)
|
||||
c.AppendArgs(args...)
|
||||
return c
|
||||
}
|
||||
|
||||
func NewPodBashCommand(kubeconfig, namespace, pod, container string) ICommand {
|
||||
return NewKubectlCommand(kubeconfig, namespace).Exec().
|
||||
Stdin().
|
||||
TTY().
|
||||
Pod(pod).
|
||||
Container(container).
|
||||
Command("bash", "-i", "-l")
|
||||
}
|
||||
|
||||
type KubectlLog struct {
|
||||
*Kubectl
|
||||
}
|
||||
|
||||
func (c *Kubectl) Logs() *KubectlLog {
|
||||
// Print the logs for a container in a pod
|
||||
cmd := &KubectlLog{
|
||||
Kubectl: c,
|
||||
}
|
||||
cmd.AppendArgs("logs")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func (c *KubectlLog) Follow() *KubectlLog {
|
||||
// -f: Specify if the logs should be streamed
|
||||
c.AppendArgs("-f")
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *KubectlLog) Pod(name string) *KubectlLog {
|
||||
// Pod name
|
||||
c.AppendArgs(name)
|
||||
return c
|
||||
}
|
||||
|
||||
func NewPodLogCommand(kubeconfig, namespace, pod, container string) ICommand {
|
||||
return NewKubectlCommand(kubeconfig, namespace).Logs().
|
||||
Follow().
|
||||
Pod(pod)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestKubectlExec_Command(t *testing.T) {
|
||||
type fields struct {
|
||||
Kubectl *Kubectl
|
||||
}
|
||||
type args struct {
|
||||
cmd string
|
||||
args []string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
fields fields
|
||||
args args
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "bash command",
|
||||
fields: fields{
|
||||
Kubectl: NewKubectlCommand("/tmp/kubeconfig", "system"),
|
||||
},
|
||||
args: args{
|
||||
cmd: "bash",
|
||||
args: []string{"-il"},
|
||||
},
|
||||
want: "kubectl --namespace system exec -i -t Pod1 -c Container1 -- bash -il",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c := tt.fields.Kubectl.Exec().
|
||||
Stdin().TTY().
|
||||
Pod("Pod1").
|
||||
Container("Container1")
|
||||
cmd := c.Command(tt.args.cmd, tt.args.args...)
|
||||
name := cmd.name
|
||||
args := cmd.args
|
||||
got := []string{name}
|
||||
got = append(got, args...)
|
||||
if !reflect.DeepEqual(strings.Join(got, " "), tt.want) {
|
||||
t.Errorf("KubectlExec.Command() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package webconsole
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
|
||||
"yunion.io/x/jsonutils"
|
||||
"yunion.io/x/log"
|
||||
"yunion.io/x/pkg/util/sets"
|
||||
|
||||
"yunion.io/x/onecloud/pkg/appctx"
|
||||
"yunion.io/x/onecloud/pkg/appsrv"
|
||||
"yunion.io/x/onecloud/pkg/httperrors"
|
||||
"yunion.io/x/onecloud/pkg/mcclient/auth"
|
||||
"yunion.io/x/onecloud/pkg/mcclient/modules/k8s"
|
||||
"yunion.io/x/onecloud/pkg/webconsole/command"
|
||||
o "yunion.io/x/onecloud/pkg/webconsole/options"
|
||||
"yunion.io/x/onecloud/pkg/webconsole/session"
|
||||
)
|
||||
|
||||
const (
|
||||
ApiPathPrefix = "/webconsole/"
|
||||
ConnectPathPrefix = "/connect/"
|
||||
)
|
||||
|
||||
func InitHandlers(app *appsrv.Application) {
|
||||
app.AddHandler("POST", ApiPathPrefix+"k8s/<podName>/shell", auth.Authenticate(handleK8sShell))
|
||||
app.AddHandler("POST", ApiPathPrefix+"k8s/<podName>/log", auth.Authenticate(handleK8sLog))
|
||||
}
|
||||
|
||||
func fetchEnv(ctx context.Context, w http.ResponseWriter, r *http.Request) (map[string]string, jsonutils.JSONObject, jsonutils.JSONObject) {
|
||||
params := appctx.AppContextParams(ctx)
|
||||
query, e := jsonutils.ParseQueryString(r.URL.RawQuery)
|
||||
if e != nil {
|
||||
log.Errorf("Parse query string %q failed: %v", r.URL.RawQuery, e)
|
||||
}
|
||||
var body jsonutils.JSONObject = nil
|
||||
if sets.NewString("PUT", "POST", "DELETE", "PATCH").Has(r.Method) {
|
||||
body, e = appsrv.FetchJSON(r)
|
||||
if e != nil {
|
||||
log.Errorf("Failed to decode JSON request body: %v", e)
|
||||
}
|
||||
}
|
||||
return params, query, body
|
||||
}
|
||||
|
||||
type K8sEnv struct {
|
||||
Cluster string
|
||||
Namespace string
|
||||
Pod string
|
||||
Container string
|
||||
KubeConfig string
|
||||
}
|
||||
|
||||
func fetchK8sEnv(ctx context.Context, w http.ResponseWriter, r *http.Request) (*K8sEnv, error) {
|
||||
params, _, body := fetchEnv(ctx, w, r)
|
||||
cluster, _ := body.GetString("cluster")
|
||||
if cluster == "" {
|
||||
cluster = "default"
|
||||
}
|
||||
namespace, _ := body.GetString("namespace")
|
||||
if namespace == "" {
|
||||
namespace = "default"
|
||||
}
|
||||
podName := params["<podName>"]
|
||||
container, _ := body.GetString("container")
|
||||
adminSession := auth.GetAdminSession(o.Options.Region, "")
|
||||
|
||||
query := jsonutils.NewDict()
|
||||
query.Add(jsonutils.NewString(namespace), "namespace")
|
||||
query.Add(jsonutils.NewString(cluster), "cluster")
|
||||
obj, err := k8s.Pods.Get(adminSession, podName, query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if obj == nil {
|
||||
return nil, httperrors.NewNotFoundError("Not found pod %q", podName)
|
||||
}
|
||||
|
||||
data := jsonutils.NewDict()
|
||||
data.Add(jsonutils.JSONTrue, "directly")
|
||||
ret, err := k8s.Clusters.PerformAction(adminSession, cluster, "generate-kubeconfig", data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conf, err := ret.GetString("kubeconfig")
|
||||
if err != nil {
|
||||
return nil, httperrors.NewNotFoundError("Not found cluster %q kubeconfig", cluster)
|
||||
}
|
||||
f, err := ioutil.TempFile("", "kubeconfig-")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Save kubeconfig error: %v", err)
|
||||
}
|
||||
f.WriteString(conf)
|
||||
defer f.Close()
|
||||
|
||||
return &K8sEnv{
|
||||
Cluster: cluster,
|
||||
Namespace: namespace,
|
||||
Pod: podName,
|
||||
Container: container,
|
||||
KubeConfig: f.Name(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func handleK8sCommand(
|
||||
ctx context.Context,
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
cmdFactory func(kubeconfig, namespace, pod, container string) command.ICommand,
|
||||
) {
|
||||
env, err := fetchK8sEnv(ctx, w, r)
|
||||
if err != nil {
|
||||
httperrors.GeneralServerError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
cmd := cmdFactory(env.KubeConfig, env.Namespace, env.Pod, env.Container)
|
||||
cmdSession, err := session.Manager.Save(cmd)
|
||||
if err != nil {
|
||||
httperrors.GeneralServerError(w, err)
|
||||
return
|
||||
}
|
||||
data := jsonutils.NewDict()
|
||||
params, err := cmdSession.GetConnectParams()
|
||||
if err != nil {
|
||||
httperrors.GeneralServerError(w, err)
|
||||
return
|
||||
}
|
||||
data.Add(jsonutils.NewString(params), "connect_params")
|
||||
data.Add(jsonutils.NewString(cmdSession.Id), "session")
|
||||
sendJSON(w, data)
|
||||
}
|
||||
|
||||
func handleK8sShell(ctx context.Context, w http.ResponseWriter, r *http.Request) {
|
||||
handleK8sCommand(ctx, w, r, command.NewPodBashCommand)
|
||||
}
|
||||
|
||||
func handleK8sLog(ctx context.Context, w http.ResponseWriter, r *http.Request) {
|
||||
handleK8sCommand(ctx, w, r, command.NewPodLogCommand)
|
||||
}
|
||||
|
||||
func sendJSON(w http.ResponseWriter, body jsonutils.JSONObject) {
|
||||
ret := jsonutils.NewDict()
|
||||
if body != nil {
|
||||
ret.Add(body, "webconsole")
|
||||
}
|
||||
appsrv.SendJSON(w, ret)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package options
|
||||
|
||||
import (
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon"
|
||||
)
|
||||
|
||||
var (
|
||||
Options WebConsoleOptions
|
||||
)
|
||||
|
||||
type WebConsoleOptions struct {
|
||||
cloudcommon.Options
|
||||
|
||||
ApiServer string `help:"API server url to handle websocket connection, usually with public access" default:"http://webconsole.yunion.io"`
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"yunion.io/x/jsonutils"
|
||||
"yunion.io/x/log"
|
||||
|
||||
"yunion.io/x/onecloud/pkg/httperrors"
|
||||
"yunion.io/x/onecloud/pkg/webconsole/session"
|
||||
)
|
||||
|
||||
type ConnectionServer struct {
|
||||
}
|
||||
|
||||
func NewConnectionServer() *ConnectionServer {
|
||||
return &ConnectionServer{}
|
||||
}
|
||||
|
||||
func (s *ConnectionServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
query, err := jsonutils.ParseQueryString(req.URL.RawQuery)
|
||||
if err != nil {
|
||||
httperrors.GeneralServerError(w, err)
|
||||
return
|
||||
}
|
||||
log.Debugf("[connection] Get query: %v", query)
|
||||
accessToken, _ := query.GetString("access_token")
|
||||
if accessToken == "" {
|
||||
httperrors.BadRequestError(w, fmt.Sprintf("Empty access_token"))
|
||||
return
|
||||
}
|
||||
sessionObj, ok := session.Manager.Get(accessToken)
|
||||
if !ok {
|
||||
log.Warningf("Not found session by token: %q", accessToken)
|
||||
httperrors.NotFoundError(w, fmt.Sprintf("Not found session"))
|
||||
return
|
||||
}
|
||||
ttyServer, err := NewTTYServer(sessionObj)
|
||||
if err != nil {
|
||||
httperrors.GeneralServerError(w, fmt.Errorf("New TTY error: %v", err))
|
||||
return
|
||||
}
|
||||
ttyServer.ServeHTTP(w, req)
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
socketio "github.com/googollee/go-socket.io"
|
||||
"github.com/kr/pty"
|
||||
|
||||
"yunion.io/x/log"
|
||||
|
||||
"yunion.io/x/onecloud/pkg/webconsole/session"
|
||||
)
|
||||
|
||||
const (
|
||||
ON_CONNECTION = "connection"
|
||||
ON_DISCONNECTION = "disconnection"
|
||||
ON_ERROR = "error"
|
||||
|
||||
OUTPUT_EVENT = "output"
|
||||
INPUT_EVENT = "input"
|
||||
RESIZE_EVENT = "resize"
|
||||
|
||||
COMMAND_QUERY = "command"
|
||||
ARGS_QUERY = "args"
|
||||
)
|
||||
|
||||
type TTYServer struct {
|
||||
*socketio.Server
|
||||
}
|
||||
|
||||
func NewTTYServer(s *session.SSession) (*TTYServer, error) {
|
||||
socketioServer, err := socketio.NewServer(nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
server := &TTYServer{
|
||||
Server: socketioServer,
|
||||
}
|
||||
server.initEventHandler(s)
|
||||
return server, nil
|
||||
}
|
||||
|
||||
func (server *TTYServer) initEventHandler(s *session.SSession) {
|
||||
server.On(ON_CONNECTION, func(so socketio.Socket) error {
|
||||
log.Infof("[%q] On connection", so.Id())
|
||||
p, err := session.NewPty(s)
|
||||
if err != nil {
|
||||
log.Errorf("Create Pty error: %v", err)
|
||||
return err
|
||||
}
|
||||
initSocketHandler(so, p)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func initSocketHandler(so socketio.Socket, p *session.Pty) {
|
||||
// handle read
|
||||
go func() {
|
||||
buf := make([]byte, 1024)
|
||||
for {
|
||||
n, err := p.Pty.Read(buf)
|
||||
if err != nil {
|
||||
log.Errorf("Failed to read from pty master: %v", err)
|
||||
cleanUp(so, p)
|
||||
return
|
||||
}
|
||||
so.Emit(OUTPUT_EVENT, string(buf[0:n]))
|
||||
}
|
||||
}()
|
||||
|
||||
// handle write
|
||||
so.On(INPUT_EVENT, func(data string) {
|
||||
p.Pty.Write([]byte(data))
|
||||
})
|
||||
|
||||
// handle resize
|
||||
so.On(RESIZE_EVENT, func(colRow []uint16) {
|
||||
if len(colRow) != 2 {
|
||||
log.Errorf("Invalid window size: %v", colRow)
|
||||
cleanUp(so, p)
|
||||
return
|
||||
}
|
||||
//size, err := pty.GetsizeFull(p.Pty)
|
||||
//if err != nil {
|
||||
//log.Errorf("Get pty window size error: %v", err)
|
||||
//return
|
||||
//}
|
||||
newSize := pty.Winsize{
|
||||
Cols: colRow[0],
|
||||
Rows: colRow[1],
|
||||
}
|
||||
p.Resize(&newSize)
|
||||
})
|
||||
|
||||
// handle disconnection
|
||||
so.On(ON_DISCONNECTION, func(msg string) {
|
||||
log.Infof("[%s] closed: %s", so.Id(), msg)
|
||||
cleanUp(so, p)
|
||||
})
|
||||
|
||||
// handle error
|
||||
so.On(ON_ERROR, func(err error) {
|
||||
log.Errorf("[%s] on error: %v", so.Id(), err)
|
||||
cleanUp(so, p)
|
||||
})
|
||||
}
|
||||
|
||||
func cleanUp(so socketio.Socket, p *session.Pty) {
|
||||
so.Disconnect()
|
||||
p.Stop()
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
|
||||
"yunion.io/x/log"
|
||||
|
||||
"yunion.io/x/onecloud/pkg/cloudcommon"
|
||||
"yunion.io/x/onecloud/pkg/webconsole"
|
||||
o "yunion.io/x/onecloud/pkg/webconsole/options"
|
||||
"yunion.io/x/onecloud/pkg/webconsole/server"
|
||||
)
|
||||
|
||||
func StartService() {
|
||||
cloudcommon.ParseOptions(&o.Options, &o.Options.Options, os.Args, "webconsole.conf")
|
||||
|
||||
if o.Options.ApiServer == "" {
|
||||
log.Fatalf("--api-server must specified")
|
||||
}
|
||||
_, err := url.Parse(o.Options.ApiServer)
|
||||
if err != nil {
|
||||
log.Fatalf("invalid --api-server %s", o.Options.ApiServer)
|
||||
}
|
||||
|
||||
cloudcommon.InitAuth(&o.Options.Options, func() {
|
||||
log.Infof("Auth complete")
|
||||
})
|
||||
start()
|
||||
}
|
||||
|
||||
func start() {
|
||||
app := cloudcommon.InitApp(&o.Options.Options)
|
||||
webconsole.InitHandlers(app)
|
||||
|
||||
root := mux.NewRouter()
|
||||
root.UseEncodedPath()
|
||||
|
||||
// api handler
|
||||
root.PathPrefix(webconsole.ApiPathPrefix).Handler(app)
|
||||
|
||||
// websocket related console handler
|
||||
root.Handle(webconsole.ConnectPathPrefix, server.NewConnectionServer())
|
||||
|
||||
addr := net.JoinHostPort(o.Options.Address, strconv.Itoa(o.Options.Port))
|
||||
log.Infof("Start listen on %s", addr)
|
||||
err := http.ListenAndServe(addr, root)
|
||||
if err != nil {
|
||||
log.Fatalf("%v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"github.com/kr/pty"
|
||||
|
||||
"yunion.io/x/log"
|
||||
)
|
||||
|
||||
type Pty struct {
|
||||
Session *SSession
|
||||
Cmd *exec.Cmd
|
||||
Pty *os.File
|
||||
sizeCh chan os.Signal
|
||||
size *pty.Winsize
|
||||
}
|
||||
|
||||
func NewPty(session *SSession) (p *Pty, err error) {
|
||||
cmd := session.GetCommand()
|
||||
p = &Pty{
|
||||
Session: session,
|
||||
Cmd: cmd,
|
||||
}
|
||||
p.Pty, err = pty.Start(p.Cmd)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
p.sizeCh = make(chan os.Signal, 1)
|
||||
p.size = &pty.Winsize{}
|
||||
p.startResizeMonitor()
|
||||
signal.Notify(p.sizeCh, syscall.SIGWINCH) // Initail resize
|
||||
return
|
||||
}
|
||||
|
||||
func (p *Pty) startResizeMonitor() {
|
||||
go func() {
|
||||
for range p.sizeCh {
|
||||
if err := pty.Setsize(p.Pty, p.size); err != nil {
|
||||
log.Errorf("Resize pty error: %v", err)
|
||||
} else {
|
||||
log.Debugf("Resize pty to %#v, cmd: %#v", p.size, p.Cmd)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (p *Pty) Resize(size *pty.Winsize) {
|
||||
p.size = size
|
||||
p.sizeCh <- syscall.SIGWINCH
|
||||
}
|
||||
|
||||
func (p *Pty) Stop() {
|
||||
var err error
|
||||
err = p.Pty.Close()
|
||||
if err != nil {
|
||||
log.Errorf("Close PTY error: %v", err)
|
||||
}
|
||||
err = p.Cmd.Process.Signal(os.Kill)
|
||||
if err != nil {
|
||||
log.Errorf("Kill command process error: %v", err)
|
||||
}
|
||||
err = p.Cmd.Wait()
|
||||
if err != nil {
|
||||
log.Errorf("Wait command error: %v", err)
|
||||
}
|
||||
p.Session.Close()
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net/url"
|
||||
"sync"
|
||||
|
||||
"github.com/golang-plus/uuid"
|
||||
|
||||
"yunion.io/x/log"
|
||||
"yunion.io/x/pkg/utils"
|
||||
|
||||
"yunion.io/x/onecloud/pkg/webconsole/command"
|
||||
o "yunion.io/x/onecloud/pkg/webconsole/options"
|
||||
)
|
||||
|
||||
var (
|
||||
Manager *SSessionManager
|
||||
AES_KEY string
|
||||
)
|
||||
|
||||
func init() {
|
||||
Manager = NewSessionManager()
|
||||
AES_KEY = fmt.Sprintf("webconsole-%f", rand.Float32())
|
||||
}
|
||||
|
||||
type SSessionManager struct {
|
||||
*sync.Map
|
||||
}
|
||||
|
||||
func NewSessionManager() *SSessionManager {
|
||||
s := &SSessionManager{
|
||||
Map: &sync.Map{},
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (man *SSessionManager) Save(Command command.ICommand) (session *SSession, err error) {
|
||||
key, err := uuid.NewV4()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
idStr := key.String()
|
||||
token, err := utils.EncryptAESBase64Url(AES_KEY, idStr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
session = &SSession{
|
||||
Id: idStr,
|
||||
ICommand: Command,
|
||||
AccessToken: token,
|
||||
}
|
||||
man.Store(idStr, session)
|
||||
return
|
||||
}
|
||||
|
||||
func (man *SSessionManager) Get(accessToken string) (*SSession, bool) {
|
||||
id, err := utils.DescryptAESBase64Url(AES_KEY, accessToken)
|
||||
if err != nil {
|
||||
log.Errorf("DescryptAESBase64Url error: %v", err)
|
||||
return nil, false
|
||||
}
|
||||
obj, ok := man.Load(id)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
return obj.(*SSession), true
|
||||
}
|
||||
|
||||
type SSession struct {
|
||||
command.ICommand
|
||||
Id string
|
||||
AccessToken string
|
||||
}
|
||||
|
||||
func (s SSession) GetConnectParams() (string, error) {
|
||||
params := url.Values{
|
||||
"api_server": {o.Options.ApiServer},
|
||||
"access_token": {s.AccessToken},
|
||||
"protocol": {s.GetProtocol()},
|
||||
}
|
||||
return params.Encode(), nil
|
||||
}
|
||||
|
||||
func (s *SSession) Close() error {
|
||||
if err := s.ICommand.Cleanup(); err != nil {
|
||||
log.Errorf("Clean up command error: %v", err)
|
||||
}
|
||||
Manager.Delete(s.Id)
|
||||
return nil
|
||||
}
|
||||
Generated
Vendored
-1025
File diff suppressed because it is too large
Load Diff
Generated
Vendored
-434
@@ -1,434 +0,0 @@
|
||||
package network
|
||||
|
||||
// Copyright (c) Microsoft and contributors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
//
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Code generated by Microsoft (R) AutoRest Code Generator.
|
||||
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/Azure/go-autorest/autorest"
|
||||
"github.com/Azure/go-autorest/autorest/azure"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// ApplicationSecurityGroupsClient is the network Client
|
||||
type ApplicationSecurityGroupsClient struct {
|
||||
BaseClient
|
||||
}
|
||||
|
||||
// NewApplicationSecurityGroupsClient creates an instance of the ApplicationSecurityGroupsClient client.
|
||||
func NewApplicationSecurityGroupsClient(subscriptionID string) ApplicationSecurityGroupsClient {
|
||||
return NewApplicationSecurityGroupsClientWithBaseURI(DefaultBaseURI, subscriptionID)
|
||||
}
|
||||
|
||||
// NewApplicationSecurityGroupsClientWithBaseURI creates an instance of the ApplicationSecurityGroupsClient client.
|
||||
func NewApplicationSecurityGroupsClientWithBaseURI(baseURI string, subscriptionID string) ApplicationSecurityGroupsClient {
|
||||
return ApplicationSecurityGroupsClient{NewWithBaseURI(baseURI, subscriptionID)}
|
||||
}
|
||||
|
||||
// CreateOrUpdate creates or updates an application security group.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// applicationSecurityGroupName - the name of the application security group.
|
||||
// parameters - parameters supplied to the create or update ApplicationSecurityGroup operation.
|
||||
func (client ApplicationSecurityGroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string, parameters ApplicationSecurityGroup) (result ApplicationSecurityGroupsCreateOrUpdateFuture, err error) {
|
||||
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, applicationSecurityGroupName, parameters)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "CreateOrUpdate", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.CreateOrUpdateSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "CreateOrUpdate", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
|
||||
func (client ApplicationSecurityGroupsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string, parameters ApplicationSecurityGroup) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"applicationSecurityGroupName": autorest.Encode("path", applicationSecurityGroupName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsContentType("application/json; charset=utf-8"),
|
||||
autorest.AsPut(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationSecurityGroups/{applicationSecurityGroupName}", pathParameters),
|
||||
autorest.WithJSON(parameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ApplicationSecurityGroupsClient) CreateOrUpdateSender(req *http.Request) (future ApplicationSecurityGroupsCreateOrUpdateFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ApplicationSecurityGroupsClient) CreateOrUpdateResponder(resp *http.Response) (result ApplicationSecurityGroup, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// Delete deletes the specified application security group.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// applicationSecurityGroupName - the name of the application security group.
|
||||
func (client ApplicationSecurityGroupsClient) Delete(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string) (result ApplicationSecurityGroupsDeleteFuture, err error) {
|
||||
req, err := client.DeletePreparer(ctx, resourceGroupName, applicationSecurityGroupName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "Delete", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.DeleteSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "Delete", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// DeletePreparer prepares the Delete request.
|
||||
func (client ApplicationSecurityGroupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"applicationSecurityGroupName": autorest.Encode("path", applicationSecurityGroupName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsDelete(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationSecurityGroups/{applicationSecurityGroupName}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// DeleteSender sends the Delete request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ApplicationSecurityGroupsClient) DeleteSender(req *http.Request) (future ApplicationSecurityGroupsDeleteFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// DeleteResponder handles the response to the Delete request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ApplicationSecurityGroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
|
||||
autorest.ByClosing())
|
||||
result.Response = resp
|
||||
return
|
||||
}
|
||||
|
||||
// Get gets information about the specified application security group.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// applicationSecurityGroupName - the name of the application security group.
|
||||
func (client ApplicationSecurityGroupsClient) Get(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string) (result ApplicationSecurityGroup, err error) {
|
||||
req, err := client.GetPreparer(ctx, resourceGroupName, applicationSecurityGroupName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "Get", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.GetSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "Get", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.GetResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "Get", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetPreparer prepares the Get request.
|
||||
func (client ApplicationSecurityGroupsClient) GetPreparer(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"applicationSecurityGroupName": autorest.Encode("path", applicationSecurityGroupName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationSecurityGroups/{applicationSecurityGroupName}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// GetSender sends the Get request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ApplicationSecurityGroupsClient) GetSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// GetResponder handles the response to the Get request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ApplicationSecurityGroupsClient) GetResponder(resp *http.Response) (result ApplicationSecurityGroup, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// List gets all the application security groups in a resource group.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
func (client ApplicationSecurityGroupsClient) List(ctx context.Context, resourceGroupName string) (result ApplicationSecurityGroupListResultPage, err error) {
|
||||
result.fn = client.listNextResults
|
||||
req, err := client.ListPreparer(ctx, resourceGroupName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "List", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.ListSender(req)
|
||||
if err != nil {
|
||||
result.asglr.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "List", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result.asglr, err = client.ListResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "List", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// ListPreparer prepares the List request.
|
||||
func (client ApplicationSecurityGroupsClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationSecurityGroups", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// ListSender sends the List request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ApplicationSecurityGroupsClient) ListSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// ListResponder handles the response to the List request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ApplicationSecurityGroupsClient) ListResponder(resp *http.Response) (result ApplicationSecurityGroupListResult, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// listNextResults retrieves the next set of results, if any.
|
||||
func (client ApplicationSecurityGroupsClient) listNextResults(lastResults ApplicationSecurityGroupListResult) (result ApplicationSecurityGroupListResult, err error) {
|
||||
req, err := lastResults.applicationSecurityGroupListResultPreparer()
|
||||
if err != nil {
|
||||
return result, autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "listNextResults", nil, "Failure preparing next results request")
|
||||
}
|
||||
if req == nil {
|
||||
return
|
||||
}
|
||||
resp, err := client.ListSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return result, autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "listNextResults", resp, "Failure sending next results request")
|
||||
}
|
||||
result, err = client.ListResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "listNextResults", resp, "Failure responding to next results request")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ListComplete enumerates all values, automatically crossing page boundaries as required.
|
||||
func (client ApplicationSecurityGroupsClient) ListComplete(ctx context.Context, resourceGroupName string) (result ApplicationSecurityGroupListResultIterator, err error) {
|
||||
result.page, err = client.List(ctx, resourceGroupName)
|
||||
return
|
||||
}
|
||||
|
||||
// ListAll gets all application security groups in a subscription.
|
||||
func (client ApplicationSecurityGroupsClient) ListAll(ctx context.Context) (result ApplicationSecurityGroupListResultPage, err error) {
|
||||
result.fn = client.listAllNextResults
|
||||
req, err := client.ListAllPreparer(ctx)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "ListAll", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.ListAllSender(req)
|
||||
if err != nil {
|
||||
result.asglr.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "ListAll", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result.asglr, err = client.ListAllResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "ListAll", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// ListAllPreparer prepares the ListAll request.
|
||||
func (client ApplicationSecurityGroupsClient) ListAllPreparer(ctx context.Context) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationSecurityGroups", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// ListAllSender sends the ListAll request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ApplicationSecurityGroupsClient) ListAllSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// ListAllResponder handles the response to the ListAll request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ApplicationSecurityGroupsClient) ListAllResponder(resp *http.Response) (result ApplicationSecurityGroupListResult, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// listAllNextResults retrieves the next set of results, if any.
|
||||
func (client ApplicationSecurityGroupsClient) listAllNextResults(lastResults ApplicationSecurityGroupListResult) (result ApplicationSecurityGroupListResult, err error) {
|
||||
req, err := lastResults.applicationSecurityGroupListResultPreparer()
|
||||
if err != nil {
|
||||
return result, autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "listAllNextResults", nil, "Failure preparing next results request")
|
||||
}
|
||||
if req == nil {
|
||||
return
|
||||
}
|
||||
resp, err := client.ListAllSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return result, autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "listAllNextResults", resp, "Failure sending next results request")
|
||||
}
|
||||
result, err = client.ListAllResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "listAllNextResults", resp, "Failure responding to next results request")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ListAllComplete enumerates all values, automatically crossing page boundaries as required.
|
||||
func (client ApplicationSecurityGroupsClient) ListAllComplete(ctx context.Context) (result ApplicationSecurityGroupListResultIterator, err error) {
|
||||
result.page, err = client.ListAll(ctx)
|
||||
return
|
||||
}
|
||||
Generated
Vendored
-133
@@ -1,133 +0,0 @@
|
||||
package network
|
||||
|
||||
// Copyright (c) Microsoft and contributors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
//
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Code generated by Microsoft (R) AutoRest Code Generator.
|
||||
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/Azure/go-autorest/autorest"
|
||||
"github.com/Azure/go-autorest/autorest/azure"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// AvailableEndpointServicesClient is the network Client
|
||||
type AvailableEndpointServicesClient struct {
|
||||
BaseClient
|
||||
}
|
||||
|
||||
// NewAvailableEndpointServicesClient creates an instance of the AvailableEndpointServicesClient client.
|
||||
func NewAvailableEndpointServicesClient(subscriptionID string) AvailableEndpointServicesClient {
|
||||
return NewAvailableEndpointServicesClientWithBaseURI(DefaultBaseURI, subscriptionID)
|
||||
}
|
||||
|
||||
// NewAvailableEndpointServicesClientWithBaseURI creates an instance of the AvailableEndpointServicesClient client.
|
||||
func NewAvailableEndpointServicesClientWithBaseURI(baseURI string, subscriptionID string) AvailableEndpointServicesClient {
|
||||
return AvailableEndpointServicesClient{NewWithBaseURI(baseURI, subscriptionID)}
|
||||
}
|
||||
|
||||
// List list what values of endpoint services are available for use.
|
||||
// Parameters:
|
||||
// location - the location to check available endpoint services.
|
||||
func (client AvailableEndpointServicesClient) List(ctx context.Context, location string) (result EndpointServicesListResultPage, err error) {
|
||||
result.fn = client.listNextResults
|
||||
req, err := client.ListPreparer(ctx, location)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.AvailableEndpointServicesClient", "List", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.ListSender(req)
|
||||
if err != nil {
|
||||
result.eslr.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.AvailableEndpointServicesClient", "List", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result.eslr, err = client.ListResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.AvailableEndpointServicesClient", "List", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// ListPreparer prepares the List request.
|
||||
func (client AvailableEndpointServicesClient) ListPreparer(ctx context.Context, location string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"location": autorest.Encode("path", location),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/virtualNetworkAvailableEndpointServices", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// ListSender sends the List request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client AvailableEndpointServicesClient) ListSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// ListResponder handles the response to the List request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client AvailableEndpointServicesClient) ListResponder(resp *http.Response) (result EndpointServicesListResult, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// listNextResults retrieves the next set of results, if any.
|
||||
func (client AvailableEndpointServicesClient) listNextResults(lastResults EndpointServicesListResult) (result EndpointServicesListResult, err error) {
|
||||
req, err := lastResults.endpointServicesListResultPreparer()
|
||||
if err != nil {
|
||||
return result, autorest.NewErrorWithError(err, "network.AvailableEndpointServicesClient", "listNextResults", nil, "Failure preparing next results request")
|
||||
}
|
||||
if req == nil {
|
||||
return
|
||||
}
|
||||
resp, err := client.ListSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return result, autorest.NewErrorWithError(err, "network.AvailableEndpointServicesClient", "listNextResults", resp, "Failure sending next results request")
|
||||
}
|
||||
result, err = client.ListResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.AvailableEndpointServicesClient", "listNextResults", resp, "Failure responding to next results request")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ListComplete enumerates all values, automatically crossing page boundaries as required.
|
||||
func (client AvailableEndpointServicesClient) ListComplete(ctx context.Context, location string) (result EndpointServicesListResultIterator, err error) {
|
||||
result.page, err = client.List(ctx, location)
|
||||
return
|
||||
}
|
||||
Generated
Vendored
-434
@@ -1,434 +0,0 @@
|
||||
package network
|
||||
|
||||
// Copyright (c) Microsoft and contributors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
//
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Code generated by Microsoft (R) AutoRest Code Generator.
|
||||
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/Azure/go-autorest/autorest"
|
||||
"github.com/Azure/go-autorest/autorest/azure"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// AzureFirewallsClient is the network Client
|
||||
type AzureFirewallsClient struct {
|
||||
BaseClient
|
||||
}
|
||||
|
||||
// NewAzureFirewallsClient creates an instance of the AzureFirewallsClient client.
|
||||
func NewAzureFirewallsClient(subscriptionID string) AzureFirewallsClient {
|
||||
return NewAzureFirewallsClientWithBaseURI(DefaultBaseURI, subscriptionID)
|
||||
}
|
||||
|
||||
// NewAzureFirewallsClientWithBaseURI creates an instance of the AzureFirewallsClient client.
|
||||
func NewAzureFirewallsClientWithBaseURI(baseURI string, subscriptionID string) AzureFirewallsClient {
|
||||
return AzureFirewallsClient{NewWithBaseURI(baseURI, subscriptionID)}
|
||||
}
|
||||
|
||||
// CreateOrUpdate creates or updates the specified Azure Firewall.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// azureFirewallName - the name of the Azure Firewall.
|
||||
// parameters - parameters supplied to the create or update Azure Firewall operation.
|
||||
func (client AzureFirewallsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, azureFirewallName string, parameters AzureFirewall) (result AzureFirewallsCreateOrUpdateFuture, err error) {
|
||||
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, azureFirewallName, parameters)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "CreateOrUpdate", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.CreateOrUpdateSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "CreateOrUpdate", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
|
||||
func (client AzureFirewallsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, azureFirewallName string, parameters AzureFirewall) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"azureFirewallName": autorest.Encode("path", azureFirewallName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsContentType("application/json; charset=utf-8"),
|
||||
autorest.AsPut(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/azureFirewalls/{azureFirewallName}", pathParameters),
|
||||
autorest.WithJSON(parameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client AzureFirewallsClient) CreateOrUpdateSender(req *http.Request) (future AzureFirewallsCreateOrUpdateFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client AzureFirewallsClient) CreateOrUpdateResponder(resp *http.Response) (result AzureFirewall, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// Delete deletes the specified Azure Firewall.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// azureFirewallName - the name of the Azure Firewall.
|
||||
func (client AzureFirewallsClient) Delete(ctx context.Context, resourceGroupName string, azureFirewallName string) (result AzureFirewallsDeleteFuture, err error) {
|
||||
req, err := client.DeletePreparer(ctx, resourceGroupName, azureFirewallName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "Delete", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.DeleteSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "Delete", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// DeletePreparer prepares the Delete request.
|
||||
func (client AzureFirewallsClient) DeletePreparer(ctx context.Context, resourceGroupName string, azureFirewallName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"azureFirewallName": autorest.Encode("path", azureFirewallName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsDelete(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/azureFirewalls/{azureFirewallName}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// DeleteSender sends the Delete request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client AzureFirewallsClient) DeleteSender(req *http.Request) (future AzureFirewallsDeleteFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// DeleteResponder handles the response to the Delete request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client AzureFirewallsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
|
||||
autorest.ByClosing())
|
||||
result.Response = resp
|
||||
return
|
||||
}
|
||||
|
||||
// Get gets the specified Azure Firewall.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// azureFirewallName - the name of the Azure Firewall.
|
||||
func (client AzureFirewallsClient) Get(ctx context.Context, resourceGroupName string, azureFirewallName string) (result AzureFirewall, err error) {
|
||||
req, err := client.GetPreparer(ctx, resourceGroupName, azureFirewallName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "Get", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.GetSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "Get", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.GetResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "Get", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetPreparer prepares the Get request.
|
||||
func (client AzureFirewallsClient) GetPreparer(ctx context.Context, resourceGroupName string, azureFirewallName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"azureFirewallName": autorest.Encode("path", azureFirewallName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/azureFirewalls/{azureFirewallName}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// GetSender sends the Get request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client AzureFirewallsClient) GetSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// GetResponder handles the response to the Get request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client AzureFirewallsClient) GetResponder(resp *http.Response) (result AzureFirewall, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// List lists all Azure Firewalls in a resource group.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
func (client AzureFirewallsClient) List(ctx context.Context, resourceGroupName string) (result AzureFirewallListResultPage, err error) {
|
||||
result.fn = client.listNextResults
|
||||
req, err := client.ListPreparer(ctx, resourceGroupName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "List", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.ListSender(req)
|
||||
if err != nil {
|
||||
result.aflr.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "List", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result.aflr, err = client.ListResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "List", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// ListPreparer prepares the List request.
|
||||
func (client AzureFirewallsClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/azureFirewalls", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// ListSender sends the List request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client AzureFirewallsClient) ListSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// ListResponder handles the response to the List request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client AzureFirewallsClient) ListResponder(resp *http.Response) (result AzureFirewallListResult, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// listNextResults retrieves the next set of results, if any.
|
||||
func (client AzureFirewallsClient) listNextResults(lastResults AzureFirewallListResult) (result AzureFirewallListResult, err error) {
|
||||
req, err := lastResults.azureFirewallListResultPreparer()
|
||||
if err != nil {
|
||||
return result, autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "listNextResults", nil, "Failure preparing next results request")
|
||||
}
|
||||
if req == nil {
|
||||
return
|
||||
}
|
||||
resp, err := client.ListSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return result, autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "listNextResults", resp, "Failure sending next results request")
|
||||
}
|
||||
result, err = client.ListResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "listNextResults", resp, "Failure responding to next results request")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ListComplete enumerates all values, automatically crossing page boundaries as required.
|
||||
func (client AzureFirewallsClient) ListComplete(ctx context.Context, resourceGroupName string) (result AzureFirewallListResultIterator, err error) {
|
||||
result.page, err = client.List(ctx, resourceGroupName)
|
||||
return
|
||||
}
|
||||
|
||||
// ListAll gets all the Azure Firewalls in a subscription.
|
||||
func (client AzureFirewallsClient) ListAll(ctx context.Context) (result AzureFirewallListResultPage, err error) {
|
||||
result.fn = client.listAllNextResults
|
||||
req, err := client.ListAllPreparer(ctx)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "ListAll", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.ListAllSender(req)
|
||||
if err != nil {
|
||||
result.aflr.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "ListAll", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result.aflr, err = client.ListAllResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "ListAll", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// ListAllPreparer prepares the ListAll request.
|
||||
func (client AzureFirewallsClient) ListAllPreparer(ctx context.Context) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/azureFirewalls", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// ListAllSender sends the ListAll request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client AzureFirewallsClient) ListAllSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// ListAllResponder handles the response to the ListAll request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client AzureFirewallsClient) ListAllResponder(resp *http.Response) (result AzureFirewallListResult, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// listAllNextResults retrieves the next set of results, if any.
|
||||
func (client AzureFirewallsClient) listAllNextResults(lastResults AzureFirewallListResult) (result AzureFirewallListResult, err error) {
|
||||
req, err := lastResults.azureFirewallListResultPreparer()
|
||||
if err != nil {
|
||||
return result, autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "listAllNextResults", nil, "Failure preparing next results request")
|
||||
}
|
||||
if req == nil {
|
||||
return
|
||||
}
|
||||
resp, err := client.ListAllSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return result, autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "listAllNextResults", resp, "Failure sending next results request")
|
||||
}
|
||||
result, err = client.ListAllResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "listAllNextResults", resp, "Failure responding to next results request")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ListAllComplete enumerates all values, automatically crossing page boundaries as required.
|
||||
func (client AzureFirewallsClient) ListAllComplete(ctx context.Context) (result AzureFirewallListResultIterator, err error) {
|
||||
result.page, err = client.ListAll(ctx)
|
||||
return
|
||||
}
|
||||
Generated
Vendored
-130
@@ -1,130 +0,0 @@
|
||||
package network
|
||||
|
||||
// Copyright (c) Microsoft and contributors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
//
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Code generated by Microsoft (R) AutoRest Code Generator.
|
||||
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/Azure/go-autorest/autorest"
|
||||
"github.com/Azure/go-autorest/autorest/azure"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// BgpServiceCommunitiesClient is the network Client
|
||||
type BgpServiceCommunitiesClient struct {
|
||||
BaseClient
|
||||
}
|
||||
|
||||
// NewBgpServiceCommunitiesClient creates an instance of the BgpServiceCommunitiesClient client.
|
||||
func NewBgpServiceCommunitiesClient(subscriptionID string) BgpServiceCommunitiesClient {
|
||||
return NewBgpServiceCommunitiesClientWithBaseURI(DefaultBaseURI, subscriptionID)
|
||||
}
|
||||
|
||||
// NewBgpServiceCommunitiesClientWithBaseURI creates an instance of the BgpServiceCommunitiesClient client.
|
||||
func NewBgpServiceCommunitiesClientWithBaseURI(baseURI string, subscriptionID string) BgpServiceCommunitiesClient {
|
||||
return BgpServiceCommunitiesClient{NewWithBaseURI(baseURI, subscriptionID)}
|
||||
}
|
||||
|
||||
// List gets all the available bgp service communities.
|
||||
func (client BgpServiceCommunitiesClient) List(ctx context.Context) (result BgpServiceCommunityListResultPage, err error) {
|
||||
result.fn = client.listNextResults
|
||||
req, err := client.ListPreparer(ctx)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "List", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.ListSender(req)
|
||||
if err != nil {
|
||||
result.bsclr.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "List", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result.bsclr, err = client.ListResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "List", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// ListPreparer prepares the List request.
|
||||
func (client BgpServiceCommunitiesClient) ListPreparer(ctx context.Context) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/bgpServiceCommunities", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// ListSender sends the List request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client BgpServiceCommunitiesClient) ListSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// ListResponder handles the response to the List request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client BgpServiceCommunitiesClient) ListResponder(resp *http.Response) (result BgpServiceCommunityListResult, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// listNextResults retrieves the next set of results, if any.
|
||||
func (client BgpServiceCommunitiesClient) listNextResults(lastResults BgpServiceCommunityListResult) (result BgpServiceCommunityListResult, err error) {
|
||||
req, err := lastResults.bgpServiceCommunityListResultPreparer()
|
||||
if err != nil {
|
||||
return result, autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "listNextResults", nil, "Failure preparing next results request")
|
||||
}
|
||||
if req == nil {
|
||||
return
|
||||
}
|
||||
resp, err := client.ListSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return result, autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "listNextResults", resp, "Failure sending next results request")
|
||||
}
|
||||
result, err = client.ListResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "listNextResults", resp, "Failure responding to next results request")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ListComplete enumerates all values, automatically crossing page boundaries as required.
|
||||
func (client BgpServiceCommunitiesClient) ListComplete(ctx context.Context) (result BgpServiceCommunityListResultIterator, err error) {
|
||||
result.page, err = client.List(ctx)
|
||||
return
|
||||
}
|
||||
Generated
Vendored
-122
@@ -1,122 +0,0 @@
|
||||
// Package network implements the Azure ARM Network service API version .
|
||||
//
|
||||
// Network Client
|
||||
package network
|
||||
|
||||
// Copyright (c) Microsoft and contributors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
//
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Code generated by Microsoft (R) AutoRest Code Generator.
|
||||
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/Azure/go-autorest/autorest"
|
||||
"github.com/Azure/go-autorest/autorest/azure"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultBaseURI is the default URI used for the service Network
|
||||
DefaultBaseURI = "https://management.azure.com"
|
||||
)
|
||||
|
||||
// BaseClient is the base client for Network.
|
||||
type BaseClient struct {
|
||||
autorest.Client
|
||||
BaseURI string
|
||||
SubscriptionID string
|
||||
}
|
||||
|
||||
// New creates an instance of the BaseClient client.
|
||||
func New(subscriptionID string) BaseClient {
|
||||
return NewWithBaseURI(DefaultBaseURI, subscriptionID)
|
||||
}
|
||||
|
||||
// NewWithBaseURI creates an instance of the BaseClient client.
|
||||
func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {
|
||||
return BaseClient{
|
||||
Client: autorest.NewClientWithUserAgent(UserAgent()),
|
||||
BaseURI: baseURI,
|
||||
SubscriptionID: subscriptionID,
|
||||
}
|
||||
}
|
||||
|
||||
// CheckDNSNameAvailability checks whether a domain name in the cloudapp.azure.com zone is available for use.
|
||||
// Parameters:
|
||||
// location - the location of the domain name.
|
||||
// domainNameLabel - the domain name to be verified. It must conform to the following regular expression:
|
||||
// ^[a-z][a-z0-9-]{1,61}[a-z0-9]$.
|
||||
func (client BaseClient) CheckDNSNameAvailability(ctx context.Context, location string, domainNameLabel string) (result DNSNameAvailabilityResult, err error) {
|
||||
req, err := client.CheckDNSNameAvailabilityPreparer(ctx, location, domainNameLabel)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.BaseClient", "CheckDNSNameAvailability", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.CheckDNSNameAvailabilitySender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.BaseClient", "CheckDNSNameAvailability", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.CheckDNSNameAvailabilityResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.BaseClient", "CheckDNSNameAvailability", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// CheckDNSNameAvailabilityPreparer prepares the CheckDNSNameAvailability request.
|
||||
func (client BaseClient) CheckDNSNameAvailabilityPreparer(ctx context.Context, location string, domainNameLabel string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"location": autorest.Encode("path", location),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
"domainNameLabel": autorest.Encode("query", domainNameLabel),
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/CheckDnsNameAvailability", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// CheckDNSNameAvailabilitySender sends the CheckDNSNameAvailability request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client BaseClient) CheckDNSNameAvailabilitySender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// CheckDNSNameAvailabilityResponder handles the response to the CheckDNSNameAvailability request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client BaseClient) CheckDNSNameAvailabilityResponder(resp *http.Response) (result DNSNameAvailabilityResult, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
Generated
Vendored
-552
@@ -1,552 +0,0 @@
|
||||
package network
|
||||
|
||||
// Copyright (c) Microsoft and contributors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
//
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Code generated by Microsoft (R) AutoRest Code Generator.
|
||||
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/Azure/go-autorest/autorest"
|
||||
"github.com/Azure/go-autorest/autorest/azure"
|
||||
"github.com/Azure/go-autorest/autorest/validation"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// ConnectionMonitorsClient is the network Client
|
||||
type ConnectionMonitorsClient struct {
|
||||
BaseClient
|
||||
}
|
||||
|
||||
// NewConnectionMonitorsClient creates an instance of the ConnectionMonitorsClient client.
|
||||
func NewConnectionMonitorsClient(subscriptionID string) ConnectionMonitorsClient {
|
||||
return NewConnectionMonitorsClientWithBaseURI(DefaultBaseURI, subscriptionID)
|
||||
}
|
||||
|
||||
// NewConnectionMonitorsClientWithBaseURI creates an instance of the ConnectionMonitorsClient client.
|
||||
func NewConnectionMonitorsClientWithBaseURI(baseURI string, subscriptionID string) ConnectionMonitorsClient {
|
||||
return ConnectionMonitorsClient{NewWithBaseURI(baseURI, subscriptionID)}
|
||||
}
|
||||
|
||||
// CreateOrUpdate create or update a connection monitor.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group containing Network Watcher.
|
||||
// networkWatcherName - the name of the Network Watcher resource.
|
||||
// connectionMonitorName - the name of the connection monitor.
|
||||
// parameters - parameters that define the operation to create a connection monitor.
|
||||
func (client ConnectionMonitorsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, parameters ConnectionMonitor) (result ConnectionMonitorsCreateOrUpdateFuture, err error) {
|
||||
if err := validation.Validate([]validation.Validation{
|
||||
{TargetValue: parameters,
|
||||
Constraints: []validation.Constraint{{Target: "parameters.ConnectionMonitorParameters", Name: validation.Null, Rule: true,
|
||||
Chain: []validation.Constraint{{Target: "parameters.ConnectionMonitorParameters.Source", Name: validation.Null, Rule: true,
|
||||
Chain: []validation.Constraint{{Target: "parameters.ConnectionMonitorParameters.Source.ResourceID", Name: validation.Null, Rule: true, Chain: nil}}},
|
||||
{Target: "parameters.ConnectionMonitorParameters.Destination", Name: validation.Null, Rule: true, Chain: nil},
|
||||
}}}}}); err != nil {
|
||||
return result, validation.NewError("network.ConnectionMonitorsClient", "CreateOrUpdate", err.Error())
|
||||
}
|
||||
|
||||
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, networkWatcherName, connectionMonitorName, parameters)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "CreateOrUpdate", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.CreateOrUpdateSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "CreateOrUpdate", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
|
||||
func (client ConnectionMonitorsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, parameters ConnectionMonitor) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"connectionMonitorName": autorest.Encode("path", connectionMonitorName),
|
||||
"networkWatcherName": autorest.Encode("path", networkWatcherName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsContentType("application/json; charset=utf-8"),
|
||||
autorest.AsPut(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}", pathParameters),
|
||||
autorest.WithJSON(parameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ConnectionMonitorsClient) CreateOrUpdateSender(req *http.Request) (future ConnectionMonitorsCreateOrUpdateFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ConnectionMonitorsClient) CreateOrUpdateResponder(resp *http.Response) (result ConnectionMonitorResult, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// Delete deletes the specified connection monitor.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group containing Network Watcher.
|
||||
// networkWatcherName - the name of the Network Watcher resource.
|
||||
// connectionMonitorName - the name of the connection monitor.
|
||||
func (client ConnectionMonitorsClient) Delete(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (result ConnectionMonitorsDeleteFuture, err error) {
|
||||
req, err := client.DeletePreparer(ctx, resourceGroupName, networkWatcherName, connectionMonitorName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Delete", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.DeleteSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Delete", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// DeletePreparer prepares the Delete request.
|
||||
func (client ConnectionMonitorsClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"connectionMonitorName": autorest.Encode("path", connectionMonitorName),
|
||||
"networkWatcherName": autorest.Encode("path", networkWatcherName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsDelete(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// DeleteSender sends the Delete request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ConnectionMonitorsClient) DeleteSender(req *http.Request) (future ConnectionMonitorsDeleteFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// DeleteResponder handles the response to the Delete request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ConnectionMonitorsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
|
||||
autorest.ByClosing())
|
||||
result.Response = resp
|
||||
return
|
||||
}
|
||||
|
||||
// Get gets a connection monitor by name.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group containing Network Watcher.
|
||||
// networkWatcherName - the name of the Network Watcher resource.
|
||||
// connectionMonitorName - the name of the connection monitor.
|
||||
func (client ConnectionMonitorsClient) Get(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (result ConnectionMonitorResult, err error) {
|
||||
req, err := client.GetPreparer(ctx, resourceGroupName, networkWatcherName, connectionMonitorName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Get", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.GetSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Get", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.GetResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Get", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetPreparer prepares the Get request.
|
||||
func (client ConnectionMonitorsClient) GetPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"connectionMonitorName": autorest.Encode("path", connectionMonitorName),
|
||||
"networkWatcherName": autorest.Encode("path", networkWatcherName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// GetSender sends the Get request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ConnectionMonitorsClient) GetSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// GetResponder handles the response to the Get request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ConnectionMonitorsClient) GetResponder(resp *http.Response) (result ConnectionMonitorResult, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// List lists all connection monitors for the specified Network Watcher.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group containing Network Watcher.
|
||||
// networkWatcherName - the name of the Network Watcher resource.
|
||||
func (client ConnectionMonitorsClient) List(ctx context.Context, resourceGroupName string, networkWatcherName string) (result ConnectionMonitorListResult, err error) {
|
||||
req, err := client.ListPreparer(ctx, resourceGroupName, networkWatcherName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "List", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.ListSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "List", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.ListResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "List", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// ListPreparer prepares the List request.
|
||||
func (client ConnectionMonitorsClient) ListPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"networkWatcherName": autorest.Encode("path", networkWatcherName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// ListSender sends the List request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ConnectionMonitorsClient) ListSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// ListResponder handles the response to the List request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ConnectionMonitorsClient) ListResponder(resp *http.Response) (result ConnectionMonitorListResult, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// Query query a snapshot of the most recent connection states.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group containing Network Watcher.
|
||||
// networkWatcherName - the name of the Network Watcher resource.
|
||||
// connectionMonitorName - the name given to the connection monitor.
|
||||
func (client ConnectionMonitorsClient) Query(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (result ConnectionMonitorsQueryFuture, err error) {
|
||||
req, err := client.QueryPreparer(ctx, resourceGroupName, networkWatcherName, connectionMonitorName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Query", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.QuerySender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Query", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// QueryPreparer prepares the Query request.
|
||||
func (client ConnectionMonitorsClient) QueryPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"connectionMonitorName": autorest.Encode("path", connectionMonitorName),
|
||||
"networkWatcherName": autorest.Encode("path", networkWatcherName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsPost(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}/query", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// QuerySender sends the Query request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ConnectionMonitorsClient) QuerySender(req *http.Request) (future ConnectionMonitorsQueryFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// QueryResponder handles the response to the Query request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ConnectionMonitorsClient) QueryResponder(resp *http.Response) (result ConnectionMonitorQueryResult, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// Start starts the specified connection monitor.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group containing Network Watcher.
|
||||
// networkWatcherName - the name of the Network Watcher resource.
|
||||
// connectionMonitorName - the name of the connection monitor.
|
||||
func (client ConnectionMonitorsClient) Start(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (result ConnectionMonitorsStartFuture, err error) {
|
||||
req, err := client.StartPreparer(ctx, resourceGroupName, networkWatcherName, connectionMonitorName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Start", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.StartSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Start", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// StartPreparer prepares the Start request.
|
||||
func (client ConnectionMonitorsClient) StartPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"connectionMonitorName": autorest.Encode("path", connectionMonitorName),
|
||||
"networkWatcherName": autorest.Encode("path", networkWatcherName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsPost(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}/start", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// StartSender sends the Start request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ConnectionMonitorsClient) StartSender(req *http.Request) (future ConnectionMonitorsStartFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// StartResponder handles the response to the Start request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ConnectionMonitorsClient) StartResponder(resp *http.Response) (result autorest.Response, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
|
||||
autorest.ByClosing())
|
||||
result.Response = resp
|
||||
return
|
||||
}
|
||||
|
||||
// Stop stops the specified connection monitor.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group containing Network Watcher.
|
||||
// networkWatcherName - the name of the Network Watcher resource.
|
||||
// connectionMonitorName - the name of the connection monitor.
|
||||
func (client ConnectionMonitorsClient) Stop(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (result ConnectionMonitorsStopFuture, err error) {
|
||||
req, err := client.StopPreparer(ctx, resourceGroupName, networkWatcherName, connectionMonitorName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Stop", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.StopSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Stop", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// StopPreparer prepares the Stop request.
|
||||
func (client ConnectionMonitorsClient) StopPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"connectionMonitorName": autorest.Encode("path", connectionMonitorName),
|
||||
"networkWatcherName": autorest.Encode("path", networkWatcherName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsPost(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}/stop", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// StopSender sends the Stop request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ConnectionMonitorsClient) StopSender(req *http.Request) (future ConnectionMonitorsStopFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// StopResponder handles the response to the Stop request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ConnectionMonitorsClient) StopResponder(resp *http.Response) (result autorest.Response, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
|
||||
autorest.ByClosing())
|
||||
result.Response = resp
|
||||
return
|
||||
}
|
||||
Generated
Vendored
-434
@@ -1,434 +0,0 @@
|
||||
package network
|
||||
|
||||
// Copyright (c) Microsoft and contributors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
//
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Code generated by Microsoft (R) AutoRest Code Generator.
|
||||
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/Azure/go-autorest/autorest"
|
||||
"github.com/Azure/go-autorest/autorest/azure"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// DdosProtectionPlansClient is the network Client
|
||||
type DdosProtectionPlansClient struct {
|
||||
BaseClient
|
||||
}
|
||||
|
||||
// NewDdosProtectionPlansClient creates an instance of the DdosProtectionPlansClient client.
|
||||
func NewDdosProtectionPlansClient(subscriptionID string) DdosProtectionPlansClient {
|
||||
return NewDdosProtectionPlansClientWithBaseURI(DefaultBaseURI, subscriptionID)
|
||||
}
|
||||
|
||||
// NewDdosProtectionPlansClientWithBaseURI creates an instance of the DdosProtectionPlansClient client.
|
||||
func NewDdosProtectionPlansClientWithBaseURI(baseURI string, subscriptionID string) DdosProtectionPlansClient {
|
||||
return DdosProtectionPlansClient{NewWithBaseURI(baseURI, subscriptionID)}
|
||||
}
|
||||
|
||||
// CreateOrUpdate creates or updates a DDoS protection plan.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// ddosProtectionPlanName - the name of the DDoS protection plan.
|
||||
// parameters - parameters supplied to the create or update operation.
|
||||
func (client DdosProtectionPlansClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string, parameters DdosProtectionPlan) (result DdosProtectionPlansCreateOrUpdateFuture, err error) {
|
||||
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, ddosProtectionPlanName, parameters)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "CreateOrUpdate", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.CreateOrUpdateSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "CreateOrUpdate", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
|
||||
func (client DdosProtectionPlansClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string, parameters DdosProtectionPlan) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"ddosProtectionPlanName": autorest.Encode("path", ddosProtectionPlanName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsContentType("application/json; charset=utf-8"),
|
||||
autorest.AsPut(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosProtectionPlans/{ddosProtectionPlanName}", pathParameters),
|
||||
autorest.WithJSON(parameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client DdosProtectionPlansClient) CreateOrUpdateSender(req *http.Request) (future DdosProtectionPlansCreateOrUpdateFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client DdosProtectionPlansClient) CreateOrUpdateResponder(resp *http.Response) (result DdosProtectionPlan, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// Delete deletes the specified DDoS protection plan.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// ddosProtectionPlanName - the name of the DDoS protection plan.
|
||||
func (client DdosProtectionPlansClient) Delete(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string) (result DdosProtectionPlansDeleteFuture, err error) {
|
||||
req, err := client.DeletePreparer(ctx, resourceGroupName, ddosProtectionPlanName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "Delete", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.DeleteSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "Delete", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// DeletePreparer prepares the Delete request.
|
||||
func (client DdosProtectionPlansClient) DeletePreparer(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"ddosProtectionPlanName": autorest.Encode("path", ddosProtectionPlanName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsDelete(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosProtectionPlans/{ddosProtectionPlanName}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// DeleteSender sends the Delete request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client DdosProtectionPlansClient) DeleteSender(req *http.Request) (future DdosProtectionPlansDeleteFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// DeleteResponder handles the response to the Delete request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client DdosProtectionPlansClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
|
||||
autorest.ByClosing())
|
||||
result.Response = resp
|
||||
return
|
||||
}
|
||||
|
||||
// Get gets information about the specified DDoS protection plan.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// ddosProtectionPlanName - the name of the DDoS protection plan.
|
||||
func (client DdosProtectionPlansClient) Get(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string) (result DdosProtectionPlan, err error) {
|
||||
req, err := client.GetPreparer(ctx, resourceGroupName, ddosProtectionPlanName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "Get", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.GetSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "Get", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.GetResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "Get", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetPreparer prepares the Get request.
|
||||
func (client DdosProtectionPlansClient) GetPreparer(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"ddosProtectionPlanName": autorest.Encode("path", ddosProtectionPlanName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosProtectionPlans/{ddosProtectionPlanName}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// GetSender sends the Get request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client DdosProtectionPlansClient) GetSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// GetResponder handles the response to the Get request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client DdosProtectionPlansClient) GetResponder(resp *http.Response) (result DdosProtectionPlan, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// List gets all DDoS protection plans in a subscription.
|
||||
func (client DdosProtectionPlansClient) List(ctx context.Context) (result DdosProtectionPlanListResultPage, err error) {
|
||||
result.fn = client.listNextResults
|
||||
req, err := client.ListPreparer(ctx)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "List", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.ListSender(req)
|
||||
if err != nil {
|
||||
result.dpplr.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "List", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result.dpplr, err = client.ListResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "List", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// ListPreparer prepares the List request.
|
||||
func (client DdosProtectionPlansClient) ListPreparer(ctx context.Context) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/ddosProtectionPlans", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// ListSender sends the List request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client DdosProtectionPlansClient) ListSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// ListResponder handles the response to the List request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client DdosProtectionPlansClient) ListResponder(resp *http.Response) (result DdosProtectionPlanListResult, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// listNextResults retrieves the next set of results, if any.
|
||||
func (client DdosProtectionPlansClient) listNextResults(lastResults DdosProtectionPlanListResult) (result DdosProtectionPlanListResult, err error) {
|
||||
req, err := lastResults.ddosProtectionPlanListResultPreparer()
|
||||
if err != nil {
|
||||
return result, autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "listNextResults", nil, "Failure preparing next results request")
|
||||
}
|
||||
if req == nil {
|
||||
return
|
||||
}
|
||||
resp, err := client.ListSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return result, autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "listNextResults", resp, "Failure sending next results request")
|
||||
}
|
||||
result, err = client.ListResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "listNextResults", resp, "Failure responding to next results request")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ListComplete enumerates all values, automatically crossing page boundaries as required.
|
||||
func (client DdosProtectionPlansClient) ListComplete(ctx context.Context) (result DdosProtectionPlanListResultIterator, err error) {
|
||||
result.page, err = client.List(ctx)
|
||||
return
|
||||
}
|
||||
|
||||
// ListByResourceGroup gets all the DDoS protection plans in a resource group.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
func (client DdosProtectionPlansClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result DdosProtectionPlanListResultPage, err error) {
|
||||
result.fn = client.listByResourceGroupNextResults
|
||||
req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "ListByResourceGroup", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.ListByResourceGroupSender(req)
|
||||
if err != nil {
|
||||
result.dpplr.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "ListByResourceGroup", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result.dpplr, err = client.ListByResourceGroupResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "ListByResourceGroup", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// ListByResourceGroupPreparer prepares the ListByResourceGroup request.
|
||||
func (client DdosProtectionPlansClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosProtectionPlans", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client DdosProtectionPlansClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client DdosProtectionPlansClient) ListByResourceGroupResponder(resp *http.Response) (result DdosProtectionPlanListResult, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// listByResourceGroupNextResults retrieves the next set of results, if any.
|
||||
func (client DdosProtectionPlansClient) listByResourceGroupNextResults(lastResults DdosProtectionPlanListResult) (result DdosProtectionPlanListResult, err error) {
|
||||
req, err := lastResults.ddosProtectionPlanListResultPreparer()
|
||||
if err != nil {
|
||||
return result, autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request")
|
||||
}
|
||||
if req == nil {
|
||||
return
|
||||
}
|
||||
resp, err := client.ListByResourceGroupSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return result, autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "listByResourceGroupNextResults", resp, "Failure sending next results request")
|
||||
}
|
||||
result, err = client.ListByResourceGroupResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required.
|
||||
func (client DdosProtectionPlansClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result DdosProtectionPlanListResultIterator, err error) {
|
||||
result.page, err = client.ListByResourceGroup(ctx, resourceGroupName)
|
||||
return
|
||||
}
|
||||
Generated
Vendored
-204
@@ -1,204 +0,0 @@
|
||||
package network
|
||||
|
||||
// Copyright (c) Microsoft and contributors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
//
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Code generated by Microsoft (R) AutoRest Code Generator.
|
||||
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/Azure/go-autorest/autorest"
|
||||
"github.com/Azure/go-autorest/autorest/azure"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// DefaultSecurityRulesClient is the network Client
|
||||
type DefaultSecurityRulesClient struct {
|
||||
BaseClient
|
||||
}
|
||||
|
||||
// NewDefaultSecurityRulesClient creates an instance of the DefaultSecurityRulesClient client.
|
||||
func NewDefaultSecurityRulesClient(subscriptionID string) DefaultSecurityRulesClient {
|
||||
return NewDefaultSecurityRulesClientWithBaseURI(DefaultBaseURI, subscriptionID)
|
||||
}
|
||||
|
||||
// NewDefaultSecurityRulesClientWithBaseURI creates an instance of the DefaultSecurityRulesClient client.
|
||||
func NewDefaultSecurityRulesClientWithBaseURI(baseURI string, subscriptionID string) DefaultSecurityRulesClient {
|
||||
return DefaultSecurityRulesClient{NewWithBaseURI(baseURI, subscriptionID)}
|
||||
}
|
||||
|
||||
// Get get the specified default network security rule.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// networkSecurityGroupName - the name of the network security group.
|
||||
// defaultSecurityRuleName - the name of the default security rule.
|
||||
func (client DefaultSecurityRulesClient) Get(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, defaultSecurityRuleName string) (result SecurityRule, err error) {
|
||||
req, err := client.GetPreparer(ctx, resourceGroupName, networkSecurityGroupName, defaultSecurityRuleName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "Get", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.GetSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "Get", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.GetResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "Get", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetPreparer prepares the Get request.
|
||||
func (client DefaultSecurityRulesClient) GetPreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, defaultSecurityRuleName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"defaultSecurityRuleName": autorest.Encode("path", defaultSecurityRuleName),
|
||||
"networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/defaultSecurityRules/{defaultSecurityRuleName}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// GetSender sends the Get request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client DefaultSecurityRulesClient) GetSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// GetResponder handles the response to the Get request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client DefaultSecurityRulesClient) GetResponder(resp *http.Response) (result SecurityRule, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// List gets all default security rules in a network security group.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// networkSecurityGroupName - the name of the network security group.
|
||||
func (client DefaultSecurityRulesClient) List(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) (result SecurityRuleListResultPage, err error) {
|
||||
result.fn = client.listNextResults
|
||||
req, err := client.ListPreparer(ctx, resourceGroupName, networkSecurityGroupName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "List", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.ListSender(req)
|
||||
if err != nil {
|
||||
result.srlr.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "List", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result.srlr, err = client.ListResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "List", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// ListPreparer prepares the List request.
|
||||
func (client DefaultSecurityRulesClient) ListPreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/defaultSecurityRules", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// ListSender sends the List request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client DefaultSecurityRulesClient) ListSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// ListResponder handles the response to the List request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client DefaultSecurityRulesClient) ListResponder(resp *http.Response) (result SecurityRuleListResult, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// listNextResults retrieves the next set of results, if any.
|
||||
func (client DefaultSecurityRulesClient) listNextResults(lastResults SecurityRuleListResult) (result SecurityRuleListResult, err error) {
|
||||
req, err := lastResults.securityRuleListResultPreparer()
|
||||
if err != nil {
|
||||
return result, autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "listNextResults", nil, "Failure preparing next results request")
|
||||
}
|
||||
if req == nil {
|
||||
return
|
||||
}
|
||||
resp, err := client.ListSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return result, autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "listNextResults", resp, "Failure sending next results request")
|
||||
}
|
||||
result, err = client.ListResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "listNextResults", resp, "Failure responding to next results request")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ListComplete enumerates all values, automatically crossing page boundaries as required.
|
||||
func (client DefaultSecurityRulesClient) ListComplete(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) (result SecurityRuleListResultIterator, err error) {
|
||||
result.page, err = client.List(ctx, resourceGroupName, networkSecurityGroupName)
|
||||
return
|
||||
}
|
||||
Generated
Vendored
-355
@@ -1,355 +0,0 @@
|
||||
package network
|
||||
|
||||
// Copyright (c) Microsoft and contributors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
//
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Code generated by Microsoft (R) AutoRest Code Generator.
|
||||
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/Azure/go-autorest/autorest"
|
||||
"github.com/Azure/go-autorest/autorest/azure"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// ExpressRouteCircuitAuthorizationsClient is the network Client
|
||||
type ExpressRouteCircuitAuthorizationsClient struct {
|
||||
BaseClient
|
||||
}
|
||||
|
||||
// NewExpressRouteCircuitAuthorizationsClient creates an instance of the ExpressRouteCircuitAuthorizationsClient
|
||||
// client.
|
||||
func NewExpressRouteCircuitAuthorizationsClient(subscriptionID string) ExpressRouteCircuitAuthorizationsClient {
|
||||
return NewExpressRouteCircuitAuthorizationsClientWithBaseURI(DefaultBaseURI, subscriptionID)
|
||||
}
|
||||
|
||||
// NewExpressRouteCircuitAuthorizationsClientWithBaseURI creates an instance of the
|
||||
// ExpressRouteCircuitAuthorizationsClient client.
|
||||
func NewExpressRouteCircuitAuthorizationsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteCircuitAuthorizationsClient {
|
||||
return ExpressRouteCircuitAuthorizationsClient{NewWithBaseURI(baseURI, subscriptionID)}
|
||||
}
|
||||
|
||||
// CreateOrUpdate creates or updates an authorization in the specified express route circuit.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// circuitName - the name of the express route circuit.
|
||||
// authorizationName - the name of the authorization.
|
||||
// authorizationParameters - parameters supplied to the create or update express route circuit authorization
|
||||
// operation.
|
||||
func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string, authorizationParameters ExpressRouteCircuitAuthorization) (result ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture, err error) {
|
||||
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, circuitName, authorizationName, authorizationParameters)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.CreateOrUpdateSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
|
||||
func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string, authorizationParameters ExpressRouteCircuitAuthorization) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"authorizationName": autorest.Encode("path", authorizationName),
|
||||
"circuitName": autorest.Encode("path", circuitName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsContentType("application/json; charset=utf-8"),
|
||||
autorest.AsPut(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}", pathParameters),
|
||||
autorest.WithJSON(authorizationParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCircuitAuthorization, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// Delete deletes the specified authorization from the specified express route circuit.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// circuitName - the name of the express route circuit.
|
||||
// authorizationName - the name of the authorization.
|
||||
func (client ExpressRouteCircuitAuthorizationsClient) Delete(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string) (result ExpressRouteCircuitAuthorizationsDeleteFuture, err error) {
|
||||
req, err := client.DeletePreparer(ctx, resourceGroupName, circuitName, authorizationName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Delete", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.DeleteSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Delete", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// DeletePreparer prepares the Delete request.
|
||||
func (client ExpressRouteCircuitAuthorizationsClient) DeletePreparer(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"authorizationName": autorest.Encode("path", authorizationName),
|
||||
"circuitName": autorest.Encode("path", circuitName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsDelete(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// DeleteSender sends the Delete request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitAuthorizationsClient) DeleteSender(req *http.Request) (future ExpressRouteCircuitAuthorizationsDeleteFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// DeleteResponder handles the response to the Delete request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitAuthorizationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
|
||||
autorest.ByClosing())
|
||||
result.Response = resp
|
||||
return
|
||||
}
|
||||
|
||||
// Get gets the specified authorization from the specified express route circuit.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// circuitName - the name of the express route circuit.
|
||||
// authorizationName - the name of the authorization.
|
||||
func (client ExpressRouteCircuitAuthorizationsClient) Get(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string) (result ExpressRouteCircuitAuthorization, err error) {
|
||||
req, err := client.GetPreparer(ctx, resourceGroupName, circuitName, authorizationName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Get", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.GetSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Get", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.GetResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Get", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetPreparer prepares the Get request.
|
||||
func (client ExpressRouteCircuitAuthorizationsClient) GetPreparer(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"authorizationName": autorest.Encode("path", authorizationName),
|
||||
"circuitName": autorest.Encode("path", circuitName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// GetSender sends the Get request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitAuthorizationsClient) GetSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// GetResponder handles the response to the Get request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitAuthorizationsClient) GetResponder(resp *http.Response) (result ExpressRouteCircuitAuthorization, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// List gets all authorizations in an express route circuit.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// circuitName - the name of the circuit.
|
||||
func (client ExpressRouteCircuitAuthorizationsClient) List(ctx context.Context, resourceGroupName string, circuitName string) (result AuthorizationListResultPage, err error) {
|
||||
result.fn = client.listNextResults
|
||||
req, err := client.ListPreparer(ctx, resourceGroupName, circuitName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.ListSender(req)
|
||||
if err != nil {
|
||||
result.alr.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result.alr, err = client.ListResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// ListPreparer prepares the List request.
|
||||
func (client ExpressRouteCircuitAuthorizationsClient) ListPreparer(ctx context.Context, resourceGroupName string, circuitName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"circuitName": autorest.Encode("path", circuitName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// ListSender sends the List request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitAuthorizationsClient) ListSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// ListResponder handles the response to the List request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitAuthorizationsClient) ListResponder(resp *http.Response) (result AuthorizationListResult, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// listNextResults retrieves the next set of results, if any.
|
||||
func (client ExpressRouteCircuitAuthorizationsClient) listNextResults(lastResults AuthorizationListResult) (result AuthorizationListResult, err error) {
|
||||
req, err := lastResults.authorizationListResultPreparer()
|
||||
if err != nil {
|
||||
return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "listNextResults", nil, "Failure preparing next results request")
|
||||
}
|
||||
if req == nil {
|
||||
return
|
||||
}
|
||||
resp, err := client.ListSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "listNextResults", resp, "Failure sending next results request")
|
||||
}
|
||||
result, err = client.ListResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "listNextResults", resp, "Failure responding to next results request")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ListComplete enumerates all values, automatically crossing page boundaries as required.
|
||||
func (client ExpressRouteCircuitAuthorizationsClient) ListComplete(ctx context.Context, resourceGroupName string, circuitName string) (result AuthorizationListResultIterator, err error) {
|
||||
result.page, err = client.List(ctx, resourceGroupName, circuitName)
|
||||
return
|
||||
}
|
||||
Generated
Vendored
-265
@@ -1,265 +0,0 @@
|
||||
package network
|
||||
|
||||
// Copyright (c) Microsoft and contributors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
//
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Code generated by Microsoft (R) AutoRest Code Generator.
|
||||
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/Azure/go-autorest/autorest"
|
||||
"github.com/Azure/go-autorest/autorest/azure"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// ExpressRouteCircuitConnectionsClient is the network Client
|
||||
type ExpressRouteCircuitConnectionsClient struct {
|
||||
BaseClient
|
||||
}
|
||||
|
||||
// NewExpressRouteCircuitConnectionsClient creates an instance of the ExpressRouteCircuitConnectionsClient client.
|
||||
func NewExpressRouteCircuitConnectionsClient(subscriptionID string) ExpressRouteCircuitConnectionsClient {
|
||||
return NewExpressRouteCircuitConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID)
|
||||
}
|
||||
|
||||
// NewExpressRouteCircuitConnectionsClientWithBaseURI creates an instance of the ExpressRouteCircuitConnectionsClient
|
||||
// client.
|
||||
func NewExpressRouteCircuitConnectionsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteCircuitConnectionsClient {
|
||||
return ExpressRouteCircuitConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)}
|
||||
}
|
||||
|
||||
// CreateOrUpdate creates or updates a Express Route Circuit Connection in the specified express route circuits.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// circuitName - the name of the express route circuit.
|
||||
// peeringName - the name of the peering.
|
||||
// connectionName - the name of the express route circuit connection.
|
||||
// expressRouteCircuitConnectionParameters - parameters supplied to the create or update express route circuit
|
||||
// circuit connection operation.
|
||||
func (client ExpressRouteCircuitConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string, expressRouteCircuitConnectionParameters ExpressRouteCircuitConnection) (result ExpressRouteCircuitConnectionsCreateOrUpdateFuture, err error) {
|
||||
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, circuitName, peeringName, connectionName, expressRouteCircuitConnectionParameters)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.CreateOrUpdateSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "CreateOrUpdate", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
|
||||
func (client ExpressRouteCircuitConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string, expressRouteCircuitConnectionParameters ExpressRouteCircuitConnection) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"circuitName": autorest.Encode("path", circuitName),
|
||||
"connectionName": autorest.Encode("path", connectionName),
|
||||
"peeringName": autorest.Encode("path", peeringName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsContentType("application/json; charset=utf-8"),
|
||||
autorest.AsPut(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/connections/{connectionName}", pathParameters),
|
||||
autorest.WithJSON(expressRouteCircuitConnectionParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitConnectionsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteCircuitConnectionsCreateOrUpdateFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCircuitConnection, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// Delete deletes the specified Express Route Circuit Connection from the specified express route circuit.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// circuitName - the name of the express route circuit.
|
||||
// peeringName - the name of the peering.
|
||||
// connectionName - the name of the express route circuit connection.
|
||||
func (client ExpressRouteCircuitConnectionsClient) Delete(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string) (result ExpressRouteCircuitConnectionsDeleteFuture, err error) {
|
||||
req, err := client.DeletePreparer(ctx, resourceGroupName, circuitName, peeringName, connectionName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "Delete", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.DeleteSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "Delete", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// DeletePreparer prepares the Delete request.
|
||||
func (client ExpressRouteCircuitConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"circuitName": autorest.Encode("path", circuitName),
|
||||
"connectionName": autorest.Encode("path", connectionName),
|
||||
"peeringName": autorest.Encode("path", peeringName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsDelete(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/connections/{connectionName}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// DeleteSender sends the Delete request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitConnectionsClient) DeleteSender(req *http.Request) (future ExpressRouteCircuitConnectionsDeleteFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// DeleteResponder handles the response to the Delete request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
|
||||
autorest.ByClosing())
|
||||
result.Response = resp
|
||||
return
|
||||
}
|
||||
|
||||
// Get gets the specified Express Route Circuit Connection from the specified express route circuit.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// circuitName - the name of the express route circuit.
|
||||
// peeringName - the name of the peering.
|
||||
// connectionName - the name of the express route circuit connection.
|
||||
func (client ExpressRouteCircuitConnectionsClient) Get(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string) (result ExpressRouteCircuitConnection, err error) {
|
||||
req, err := client.GetPreparer(ctx, resourceGroupName, circuitName, peeringName, connectionName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "Get", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.GetSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "Get", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.GetResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "Get", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetPreparer prepares the Get request.
|
||||
func (client ExpressRouteCircuitConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"circuitName": autorest.Encode("path", circuitName),
|
||||
"connectionName": autorest.Encode("path", connectionName),
|
||||
"peeringName": autorest.Encode("path", peeringName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/connections/{connectionName}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// GetSender sends the Get request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitConnectionsClient) GetSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// GetResponder handles the response to the Get request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitConnectionsClient) GetResponder(resp *http.Response) (result ExpressRouteCircuitConnection, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
Generated
Vendored
-364
@@ -1,364 +0,0 @@
|
||||
package network
|
||||
|
||||
// Copyright (c) Microsoft and contributors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
//
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Code generated by Microsoft (R) AutoRest Code Generator.
|
||||
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/Azure/go-autorest/autorest"
|
||||
"github.com/Azure/go-autorest/autorest/azure"
|
||||
"github.com/Azure/go-autorest/autorest/validation"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// ExpressRouteCircuitPeeringsClient is the network Client
|
||||
type ExpressRouteCircuitPeeringsClient struct {
|
||||
BaseClient
|
||||
}
|
||||
|
||||
// NewExpressRouteCircuitPeeringsClient creates an instance of the ExpressRouteCircuitPeeringsClient client.
|
||||
func NewExpressRouteCircuitPeeringsClient(subscriptionID string) ExpressRouteCircuitPeeringsClient {
|
||||
return NewExpressRouteCircuitPeeringsClientWithBaseURI(DefaultBaseURI, subscriptionID)
|
||||
}
|
||||
|
||||
// NewExpressRouteCircuitPeeringsClientWithBaseURI creates an instance of the ExpressRouteCircuitPeeringsClient client.
|
||||
func NewExpressRouteCircuitPeeringsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteCircuitPeeringsClient {
|
||||
return ExpressRouteCircuitPeeringsClient{NewWithBaseURI(baseURI, subscriptionID)}
|
||||
}
|
||||
|
||||
// CreateOrUpdate creates or updates a peering in the specified express route circuits.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// circuitName - the name of the express route circuit.
|
||||
// peeringName - the name of the peering.
|
||||
// peeringParameters - parameters supplied to the create or update express route circuit peering operation.
|
||||
func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, peeringParameters ExpressRouteCircuitPeering) (result ExpressRouteCircuitPeeringsCreateOrUpdateFuture, err error) {
|
||||
if err := validation.Validate([]validation.Validation{
|
||||
{TargetValue: peeringParameters,
|
||||
Constraints: []validation.Constraint{{Target: "peeringParameters.ExpressRouteCircuitPeeringPropertiesFormat", Name: validation.Null, Rule: false,
|
||||
Chain: []validation.Constraint{{Target: "peeringParameters.ExpressRouteCircuitPeeringPropertiesFormat.PeerASN", Name: validation.Null, Rule: false,
|
||||
Chain: []validation.Constraint{{Target: "peeringParameters.ExpressRouteCircuitPeeringPropertiesFormat.PeerASN", Name: validation.InclusiveMaximum, Rule: int64(4294967295), Chain: nil},
|
||||
{Target: "peeringParameters.ExpressRouteCircuitPeeringPropertiesFormat.PeerASN", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil},
|
||||
}},
|
||||
}}}}}); err != nil {
|
||||
return result, validation.NewError("network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", err.Error())
|
||||
}
|
||||
|
||||
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, circuitName, peeringName, peeringParameters)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.CreateOrUpdateSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
|
||||
func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, peeringParameters ExpressRouteCircuitPeering) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"circuitName": autorest.Encode("path", circuitName),
|
||||
"peeringName": autorest.Encode("path", peeringName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsContentType("application/json; charset=utf-8"),
|
||||
autorest.AsPut(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}", pathParameters),
|
||||
autorest.WithJSON(peeringParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteCircuitPeeringsCreateOrUpdateFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCircuitPeering, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// Delete deletes the specified peering from the specified express route circuit.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// circuitName - the name of the express route circuit.
|
||||
// peeringName - the name of the peering.
|
||||
func (client ExpressRouteCircuitPeeringsClient) Delete(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (result ExpressRouteCircuitPeeringsDeleteFuture, err error) {
|
||||
req, err := client.DeletePreparer(ctx, resourceGroupName, circuitName, peeringName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.DeleteSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// DeletePreparer prepares the Delete request.
|
||||
func (client ExpressRouteCircuitPeeringsClient) DeletePreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"circuitName": autorest.Encode("path", circuitName),
|
||||
"peeringName": autorest.Encode("path", peeringName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsDelete(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// DeleteSender sends the Delete request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitPeeringsClient) DeleteSender(req *http.Request) (future ExpressRouteCircuitPeeringsDeleteFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// DeleteResponder handles the response to the Delete request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitPeeringsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
|
||||
autorest.ByClosing())
|
||||
result.Response = resp
|
||||
return
|
||||
}
|
||||
|
||||
// Get gets the specified peering for the express route circuit.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// circuitName - the name of the express route circuit.
|
||||
// peeringName - the name of the peering.
|
||||
func (client ExpressRouteCircuitPeeringsClient) Get(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (result ExpressRouteCircuitPeering, err error) {
|
||||
req, err := client.GetPreparer(ctx, resourceGroupName, circuitName, peeringName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.GetSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.GetResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetPreparer prepares the Get request.
|
||||
func (client ExpressRouteCircuitPeeringsClient) GetPreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"circuitName": autorest.Encode("path", circuitName),
|
||||
"peeringName": autorest.Encode("path", peeringName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// GetSender sends the Get request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitPeeringsClient) GetSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// GetResponder handles the response to the Get request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitPeeringsClient) GetResponder(resp *http.Response) (result ExpressRouteCircuitPeering, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// List gets all peerings in a specified express route circuit.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// circuitName - the name of the express route circuit.
|
||||
func (client ExpressRouteCircuitPeeringsClient) List(ctx context.Context, resourceGroupName string, circuitName string) (result ExpressRouteCircuitPeeringListResultPage, err error) {
|
||||
result.fn = client.listNextResults
|
||||
req, err := client.ListPreparer(ctx, resourceGroupName, circuitName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.ListSender(req)
|
||||
if err != nil {
|
||||
result.ercplr.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result.ercplr, err = client.ListResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// ListPreparer prepares the List request.
|
||||
func (client ExpressRouteCircuitPeeringsClient) ListPreparer(ctx context.Context, resourceGroupName string, circuitName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"circuitName": autorest.Encode("path", circuitName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// ListSender sends the List request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitPeeringsClient) ListSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// ListResponder handles the response to the List request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitPeeringsClient) ListResponder(resp *http.Response) (result ExpressRouteCircuitPeeringListResult, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// listNextResults retrieves the next set of results, if any.
|
||||
func (client ExpressRouteCircuitPeeringsClient) listNextResults(lastResults ExpressRouteCircuitPeeringListResult) (result ExpressRouteCircuitPeeringListResult, err error) {
|
||||
req, err := lastResults.expressRouteCircuitPeeringListResultPreparer()
|
||||
if err != nil {
|
||||
return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "listNextResults", nil, "Failure preparing next results request")
|
||||
}
|
||||
if req == nil {
|
||||
return
|
||||
}
|
||||
resp, err := client.ListSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "listNextResults", resp, "Failure sending next results request")
|
||||
}
|
||||
result, err = client.ListResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "listNextResults", resp, "Failure responding to next results request")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ListComplete enumerates all values, automatically crossing page boundaries as required.
|
||||
func (client ExpressRouteCircuitPeeringsClient) ListComplete(ctx context.Context, resourceGroupName string, circuitName string) (result ExpressRouteCircuitPeeringListResultIterator, err error) {
|
||||
result.page, err = client.List(ctx, resourceGroupName, circuitName)
|
||||
return
|
||||
}
|
||||
Generated
Vendored
-871
@@ -1,871 +0,0 @@
|
||||
package network
|
||||
|
||||
// Copyright (c) Microsoft and contributors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
//
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Code generated by Microsoft (R) AutoRest Code Generator.
|
||||
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/Azure/go-autorest/autorest"
|
||||
"github.com/Azure/go-autorest/autorest/azure"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// ExpressRouteCircuitsClient is the network Client
|
||||
type ExpressRouteCircuitsClient struct {
|
||||
BaseClient
|
||||
}
|
||||
|
||||
// NewExpressRouteCircuitsClient creates an instance of the ExpressRouteCircuitsClient client.
|
||||
func NewExpressRouteCircuitsClient(subscriptionID string) ExpressRouteCircuitsClient {
|
||||
return NewExpressRouteCircuitsClientWithBaseURI(DefaultBaseURI, subscriptionID)
|
||||
}
|
||||
|
||||
// NewExpressRouteCircuitsClientWithBaseURI creates an instance of the ExpressRouteCircuitsClient client.
|
||||
func NewExpressRouteCircuitsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteCircuitsClient {
|
||||
return ExpressRouteCircuitsClient{NewWithBaseURI(baseURI, subscriptionID)}
|
||||
}
|
||||
|
||||
// CreateOrUpdate creates or updates an express route circuit.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// circuitName - the name of the circuit.
|
||||
// parameters - parameters supplied to the create or update express route circuit operation.
|
||||
func (client ExpressRouteCircuitsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, circuitName string, parameters ExpressRouteCircuit) (result ExpressRouteCircuitsCreateOrUpdateFuture, err error) {
|
||||
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, circuitName, parameters)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "CreateOrUpdate", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.CreateOrUpdateSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "CreateOrUpdate", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
|
||||
func (client ExpressRouteCircuitsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, circuitName string, parameters ExpressRouteCircuit) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"circuitName": autorest.Encode("path", circuitName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsContentType("application/json; charset=utf-8"),
|
||||
autorest.AsPut(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}", pathParameters),
|
||||
autorest.WithJSON(parameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteCircuitsCreateOrUpdateFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCircuit, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// Delete deletes the specified express route circuit.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// circuitName - the name of the express route circuit.
|
||||
func (client ExpressRouteCircuitsClient) Delete(ctx context.Context, resourceGroupName string, circuitName string) (result ExpressRouteCircuitsDeleteFuture, err error) {
|
||||
req, err := client.DeletePreparer(ctx, resourceGroupName, circuitName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Delete", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.DeleteSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Delete", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// DeletePreparer prepares the Delete request.
|
||||
func (client ExpressRouteCircuitsClient) DeletePreparer(ctx context.Context, resourceGroupName string, circuitName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"circuitName": autorest.Encode("path", circuitName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsDelete(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// DeleteSender sends the Delete request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitsClient) DeleteSender(req *http.Request) (future ExpressRouteCircuitsDeleteFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// DeleteResponder handles the response to the Delete request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
|
||||
autorest.ByClosing())
|
||||
result.Response = resp
|
||||
return
|
||||
}
|
||||
|
||||
// Get gets information about the specified express route circuit.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// circuitName - the name of express route circuit.
|
||||
func (client ExpressRouteCircuitsClient) Get(ctx context.Context, resourceGroupName string, circuitName string) (result ExpressRouteCircuit, err error) {
|
||||
req, err := client.GetPreparer(ctx, resourceGroupName, circuitName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Get", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.GetSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Get", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.GetResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Get", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetPreparer prepares the Get request.
|
||||
func (client ExpressRouteCircuitsClient) GetPreparer(ctx context.Context, resourceGroupName string, circuitName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"circuitName": autorest.Encode("path", circuitName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// GetSender sends the Get request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitsClient) GetSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// GetResponder handles the response to the Get request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitsClient) GetResponder(resp *http.Response) (result ExpressRouteCircuit, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// GetPeeringStats gets all stats from an express route circuit in a resource group.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// circuitName - the name of the express route circuit.
|
||||
// peeringName - the name of the peering.
|
||||
func (client ExpressRouteCircuitsClient) GetPeeringStats(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (result ExpressRouteCircuitStats, err error) {
|
||||
req, err := client.GetPeeringStatsPreparer(ctx, resourceGroupName, circuitName, peeringName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetPeeringStats", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.GetPeeringStatsSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetPeeringStats", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.GetPeeringStatsResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetPeeringStats", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetPeeringStatsPreparer prepares the GetPeeringStats request.
|
||||
func (client ExpressRouteCircuitsClient) GetPeeringStatsPreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"circuitName": autorest.Encode("path", circuitName),
|
||||
"peeringName": autorest.Encode("path", peeringName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/stats", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// GetPeeringStatsSender sends the GetPeeringStats request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitsClient) GetPeeringStatsSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// GetPeeringStatsResponder handles the response to the GetPeeringStats request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitsClient) GetPeeringStatsResponder(resp *http.Response) (result ExpressRouteCircuitStats, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// GetStats gets all the stats from an express route circuit in a resource group.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// circuitName - the name of the express route circuit.
|
||||
func (client ExpressRouteCircuitsClient) GetStats(ctx context.Context, resourceGroupName string, circuitName string) (result ExpressRouteCircuitStats, err error) {
|
||||
req, err := client.GetStatsPreparer(ctx, resourceGroupName, circuitName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetStats", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.GetStatsSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetStats", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.GetStatsResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetStats", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetStatsPreparer prepares the GetStats request.
|
||||
func (client ExpressRouteCircuitsClient) GetStatsPreparer(ctx context.Context, resourceGroupName string, circuitName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"circuitName": autorest.Encode("path", circuitName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/stats", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// GetStatsSender sends the GetStats request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitsClient) GetStatsSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// GetStatsResponder handles the response to the GetStats request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitsClient) GetStatsResponder(resp *http.Response) (result ExpressRouteCircuitStats, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// List gets all the express route circuits in a resource group.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
func (client ExpressRouteCircuitsClient) List(ctx context.Context, resourceGroupName string) (result ExpressRouteCircuitListResultPage, err error) {
|
||||
result.fn = client.listNextResults
|
||||
req, err := client.ListPreparer(ctx, resourceGroupName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.ListSender(req)
|
||||
if err != nil {
|
||||
result.erclr.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result.erclr, err = client.ListResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// ListPreparer prepares the List request.
|
||||
func (client ExpressRouteCircuitsClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// ListSender sends the List request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitsClient) ListSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// ListResponder handles the response to the List request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitsClient) ListResponder(resp *http.Response) (result ExpressRouteCircuitListResult, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// listNextResults retrieves the next set of results, if any.
|
||||
func (client ExpressRouteCircuitsClient) listNextResults(lastResults ExpressRouteCircuitListResult) (result ExpressRouteCircuitListResult, err error) {
|
||||
req, err := lastResults.expressRouteCircuitListResultPreparer()
|
||||
if err != nil {
|
||||
return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "listNextResults", nil, "Failure preparing next results request")
|
||||
}
|
||||
if req == nil {
|
||||
return
|
||||
}
|
||||
resp, err := client.ListSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "listNextResults", resp, "Failure sending next results request")
|
||||
}
|
||||
result, err = client.ListResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "listNextResults", resp, "Failure responding to next results request")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ListComplete enumerates all values, automatically crossing page boundaries as required.
|
||||
func (client ExpressRouteCircuitsClient) ListComplete(ctx context.Context, resourceGroupName string) (result ExpressRouteCircuitListResultIterator, err error) {
|
||||
result.page, err = client.List(ctx, resourceGroupName)
|
||||
return
|
||||
}
|
||||
|
||||
// ListAll gets all the express route circuits in a subscription.
|
||||
func (client ExpressRouteCircuitsClient) ListAll(ctx context.Context) (result ExpressRouteCircuitListResultPage, err error) {
|
||||
result.fn = client.listAllNextResults
|
||||
req, err := client.ListAllPreparer(ctx)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.ListAllSender(req)
|
||||
if err != nil {
|
||||
result.erclr.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result.erclr, err = client.ListAllResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// ListAllPreparer prepares the ListAll request.
|
||||
func (client ExpressRouteCircuitsClient) ListAllPreparer(ctx context.Context) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteCircuits", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// ListAllSender sends the ListAll request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitsClient) ListAllSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// ListAllResponder handles the response to the ListAll request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitsClient) ListAllResponder(resp *http.Response) (result ExpressRouteCircuitListResult, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// listAllNextResults retrieves the next set of results, if any.
|
||||
func (client ExpressRouteCircuitsClient) listAllNextResults(lastResults ExpressRouteCircuitListResult) (result ExpressRouteCircuitListResult, err error) {
|
||||
req, err := lastResults.expressRouteCircuitListResultPreparer()
|
||||
if err != nil {
|
||||
return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "listAllNextResults", nil, "Failure preparing next results request")
|
||||
}
|
||||
if req == nil {
|
||||
return
|
||||
}
|
||||
resp, err := client.ListAllSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "listAllNextResults", resp, "Failure sending next results request")
|
||||
}
|
||||
result, err = client.ListAllResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "listAllNextResults", resp, "Failure responding to next results request")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ListAllComplete enumerates all values, automatically crossing page boundaries as required.
|
||||
func (client ExpressRouteCircuitsClient) ListAllComplete(ctx context.Context) (result ExpressRouteCircuitListResultIterator, err error) {
|
||||
result.page, err = client.ListAll(ctx)
|
||||
return
|
||||
}
|
||||
|
||||
// ListArpTable gets the currently advertised ARP table associated with the express route circuit in a resource group.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// circuitName - the name of the express route circuit.
|
||||
// peeringName - the name of the peering.
|
||||
// devicePath - the path of the device.
|
||||
func (client ExpressRouteCircuitsClient) ListArpTable(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string) (result ExpressRouteCircuitsListArpTableFuture, err error) {
|
||||
req, err := client.ListArpTablePreparer(ctx, resourceGroupName, circuitName, peeringName, devicePath)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListArpTable", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.ListArpTableSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListArpTable", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// ListArpTablePreparer prepares the ListArpTable request.
|
||||
func (client ExpressRouteCircuitsClient) ListArpTablePreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"circuitName": autorest.Encode("path", circuitName),
|
||||
"devicePath": autorest.Encode("path", devicePath),
|
||||
"peeringName": autorest.Encode("path", peeringName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsPost(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/arpTables/{devicePath}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// ListArpTableSender sends the ListArpTable request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitsClient) ListArpTableSender(req *http.Request) (future ExpressRouteCircuitsListArpTableFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// ListArpTableResponder handles the response to the ListArpTable request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitsClient) ListArpTableResponder(resp *http.Response) (result ExpressRouteCircuitsArpTableListResult, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// ListRoutesTable gets the currently advertised routes table associated with the express route circuit in a resource
|
||||
// group.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// circuitName - the name of the express route circuit.
|
||||
// peeringName - the name of the peering.
|
||||
// devicePath - the path of the device.
|
||||
func (client ExpressRouteCircuitsClient) ListRoutesTable(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string) (result ExpressRouteCircuitsListRoutesTableFuture, err error) {
|
||||
req, err := client.ListRoutesTablePreparer(ctx, resourceGroupName, circuitName, peeringName, devicePath)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTable", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.ListRoutesTableSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTable", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// ListRoutesTablePreparer prepares the ListRoutesTable request.
|
||||
func (client ExpressRouteCircuitsClient) ListRoutesTablePreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"circuitName": autorest.Encode("path", circuitName),
|
||||
"devicePath": autorest.Encode("path", devicePath),
|
||||
"peeringName": autorest.Encode("path", peeringName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsPost(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/routeTables/{devicePath}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// ListRoutesTableSender sends the ListRoutesTable request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitsClient) ListRoutesTableSender(req *http.Request) (future ExpressRouteCircuitsListRoutesTableFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// ListRoutesTableResponder handles the response to the ListRoutesTable request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitsClient) ListRoutesTableResponder(resp *http.Response) (result ExpressRouteCircuitsRoutesTableListResult, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// ListRoutesTableSummary gets the currently advertised routes table summary associated with the express route circuit
|
||||
// in a resource group.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// circuitName - the name of the express route circuit.
|
||||
// peeringName - the name of the peering.
|
||||
// devicePath - the path of the device.
|
||||
func (client ExpressRouteCircuitsClient) ListRoutesTableSummary(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string) (result ExpressRouteCircuitsListRoutesTableSummaryFuture, err error) {
|
||||
req, err := client.ListRoutesTableSummaryPreparer(ctx, resourceGroupName, circuitName, peeringName, devicePath)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTableSummary", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.ListRoutesTableSummarySender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTableSummary", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// ListRoutesTableSummaryPreparer prepares the ListRoutesTableSummary request.
|
||||
func (client ExpressRouteCircuitsClient) ListRoutesTableSummaryPreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"circuitName": autorest.Encode("path", circuitName),
|
||||
"devicePath": autorest.Encode("path", devicePath),
|
||||
"peeringName": autorest.Encode("path", peeringName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsPost(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/routeTablesSummary/{devicePath}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// ListRoutesTableSummarySender sends the ListRoutesTableSummary request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitsClient) ListRoutesTableSummarySender(req *http.Request) (future ExpressRouteCircuitsListRoutesTableSummaryFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// ListRoutesTableSummaryResponder handles the response to the ListRoutesTableSummary request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitsClient) ListRoutesTableSummaryResponder(resp *http.Response) (result ExpressRouteCircuitsRoutesTableSummaryListResult, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// UpdateTags updates an express route circuit tags.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// circuitName - the name of the circuit.
|
||||
// parameters - parameters supplied to update express route circuit tags.
|
||||
func (client ExpressRouteCircuitsClient) UpdateTags(ctx context.Context, resourceGroupName string, circuitName string, parameters TagsObject) (result ExpressRouteCircuitsUpdateTagsFuture, err error) {
|
||||
req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, circuitName, parameters)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "UpdateTags", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.UpdateTagsSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "UpdateTags", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// UpdateTagsPreparer prepares the UpdateTags request.
|
||||
func (client ExpressRouteCircuitsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, circuitName string, parameters TagsObject) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"circuitName": autorest.Encode("path", circuitName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsContentType("application/json; charset=utf-8"),
|
||||
autorest.AsPatch(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}", pathParameters),
|
||||
autorest.WithJSON(parameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// UpdateTagsSender sends the UpdateTags request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCircuitsClient) UpdateTagsSender(req *http.Request) (future ExpressRouteCircuitsUpdateTagsFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// UpdateTagsResponder handles the response to the UpdateTags request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCircuitsClient) UpdateTagsResponder(resp *http.Response) (result ExpressRouteCircuit, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
Generated
Vendored
-367
@@ -1,367 +0,0 @@
|
||||
package network
|
||||
|
||||
// Copyright (c) Microsoft and contributors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
//
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Code generated by Microsoft (R) AutoRest Code Generator.
|
||||
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/Azure/go-autorest/autorest"
|
||||
"github.com/Azure/go-autorest/autorest/azure"
|
||||
"github.com/Azure/go-autorest/autorest/validation"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// ExpressRouteCrossConnectionPeeringsClient is the network Client
|
||||
type ExpressRouteCrossConnectionPeeringsClient struct {
|
||||
BaseClient
|
||||
}
|
||||
|
||||
// NewExpressRouteCrossConnectionPeeringsClient creates an instance of the ExpressRouteCrossConnectionPeeringsClient
|
||||
// client.
|
||||
func NewExpressRouteCrossConnectionPeeringsClient(subscriptionID string) ExpressRouteCrossConnectionPeeringsClient {
|
||||
return NewExpressRouteCrossConnectionPeeringsClientWithBaseURI(DefaultBaseURI, subscriptionID)
|
||||
}
|
||||
|
||||
// NewExpressRouteCrossConnectionPeeringsClientWithBaseURI creates an instance of the
|
||||
// ExpressRouteCrossConnectionPeeringsClient client.
|
||||
func NewExpressRouteCrossConnectionPeeringsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteCrossConnectionPeeringsClient {
|
||||
return ExpressRouteCrossConnectionPeeringsClient{NewWithBaseURI(baseURI, subscriptionID)}
|
||||
}
|
||||
|
||||
// CreateOrUpdate creates or updates a peering in the specified ExpressRouteCrossConnection.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// crossConnectionName - the name of the ExpressRouteCrossConnection.
|
||||
// peeringName - the name of the peering.
|
||||
// peeringParameters - parameters supplied to the create or update ExpressRouteCrossConnection peering
|
||||
// operation.
|
||||
func (client ExpressRouteCrossConnectionPeeringsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, peeringParameters ExpressRouteCrossConnectionPeering) (result ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture, err error) {
|
||||
if err := validation.Validate([]validation.Validation{
|
||||
{TargetValue: peeringParameters,
|
||||
Constraints: []validation.Constraint{{Target: "peeringParameters.ExpressRouteCrossConnectionPeeringProperties", Name: validation.Null, Rule: false,
|
||||
Chain: []validation.Constraint{{Target: "peeringParameters.ExpressRouteCrossConnectionPeeringProperties.PeerASN", Name: validation.Null, Rule: false,
|
||||
Chain: []validation.Constraint{{Target: "peeringParameters.ExpressRouteCrossConnectionPeeringProperties.PeerASN", Name: validation.InclusiveMaximum, Rule: int64(4294967295), Chain: nil},
|
||||
{Target: "peeringParameters.ExpressRouteCrossConnectionPeeringProperties.PeerASN", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil},
|
||||
}},
|
||||
}}}}}); err != nil {
|
||||
return result, validation.NewError("network.ExpressRouteCrossConnectionPeeringsClient", "CreateOrUpdate", err.Error())
|
||||
}
|
||||
|
||||
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, crossConnectionName, peeringName, peeringParameters)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "CreateOrUpdate", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.CreateOrUpdateSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "CreateOrUpdate", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
|
||||
func (client ExpressRouteCrossConnectionPeeringsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, peeringParameters ExpressRouteCrossConnectionPeering) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"crossConnectionName": autorest.Encode("path", crossConnectionName),
|
||||
"peeringName": autorest.Encode("path", peeringName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsContentType("application/json; charset=utf-8"),
|
||||
autorest.AsPut(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}", pathParameters),
|
||||
autorest.WithJSON(peeringParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCrossConnectionPeeringsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCrossConnectionPeeringsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCrossConnectionPeering, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// Delete deletes the specified peering from the ExpressRouteCrossConnection.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// crossConnectionName - the name of the ExpressRouteCrossConnection.
|
||||
// peeringName - the name of the peering.
|
||||
func (client ExpressRouteCrossConnectionPeeringsClient) Delete(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string) (result ExpressRouteCrossConnectionPeeringsDeleteFuture, err error) {
|
||||
req, err := client.DeletePreparer(ctx, resourceGroupName, crossConnectionName, peeringName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "Delete", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.DeleteSender(req)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "Delete", result.Response(), "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// DeletePreparer prepares the Delete request.
|
||||
func (client ExpressRouteCrossConnectionPeeringsClient) DeletePreparer(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"crossConnectionName": autorest.Encode("path", crossConnectionName),
|
||||
"peeringName": autorest.Encode("path", peeringName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsDelete(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// DeleteSender sends the Delete request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCrossConnectionPeeringsClient) DeleteSender(req *http.Request) (future ExpressRouteCrossConnectionPeeringsDeleteFuture, err error) {
|
||||
var resp *http.Response
|
||||
resp, err = autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
future.Future, err = azure.NewFutureFromResponse(resp)
|
||||
return
|
||||
}
|
||||
|
||||
// DeleteResponder handles the response to the Delete request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCrossConnectionPeeringsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
|
||||
autorest.ByClosing())
|
||||
result.Response = resp
|
||||
return
|
||||
}
|
||||
|
||||
// Get gets the specified peering for the ExpressRouteCrossConnection.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// crossConnectionName - the name of the ExpressRouteCrossConnection.
|
||||
// peeringName - the name of the peering.
|
||||
func (client ExpressRouteCrossConnectionPeeringsClient) Get(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string) (result ExpressRouteCrossConnectionPeering, err error) {
|
||||
req, err := client.GetPreparer(ctx, resourceGroupName, crossConnectionName, peeringName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "Get", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.GetSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "Get", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err = client.GetResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "Get", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetPreparer prepares the Get request.
|
||||
func (client ExpressRouteCrossConnectionPeeringsClient) GetPreparer(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"crossConnectionName": autorest.Encode("path", crossConnectionName),
|
||||
"peeringName": autorest.Encode("path", peeringName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// GetSender sends the Get request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCrossConnectionPeeringsClient) GetSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// GetResponder handles the response to the Get request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCrossConnectionPeeringsClient) GetResponder(resp *http.Response) (result ExpressRouteCrossConnectionPeering, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// List gets all peerings in a specified ExpressRouteCrossConnection.
|
||||
// Parameters:
|
||||
// resourceGroupName - the name of the resource group.
|
||||
// crossConnectionName - the name of the ExpressRouteCrossConnection.
|
||||
func (client ExpressRouteCrossConnectionPeeringsClient) List(ctx context.Context, resourceGroupName string, crossConnectionName string) (result ExpressRouteCrossConnectionPeeringListPage, err error) {
|
||||
result.fn = client.listNextResults
|
||||
req, err := client.ListPreparer(ctx, resourceGroupName, crossConnectionName)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "List", nil, "Failure preparing request")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.ListSender(req)
|
||||
if err != nil {
|
||||
result.erccpl.Response = autorest.Response{Response: resp}
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "List", resp, "Failure sending request")
|
||||
return
|
||||
}
|
||||
|
||||
result.erccpl, err = client.ListResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "List", resp, "Failure responding to request")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// ListPreparer prepares the List request.
|
||||
func (client ExpressRouteCrossConnectionPeeringsClient) ListPreparer(ctx context.Context, resourceGroupName string, crossConnectionName string) (*http.Request, error) {
|
||||
pathParameters := map[string]interface{}{
|
||||
"crossConnectionName": autorest.Encode("path", crossConnectionName),
|
||||
"resourceGroupName": autorest.Encode("path", resourceGroupName),
|
||||
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
|
||||
}
|
||||
|
||||
const APIVersion = "2018-04-01"
|
||||
queryParameters := map[string]interface{}{
|
||||
"api-version": APIVersion,
|
||||
}
|
||||
|
||||
preparer := autorest.CreatePreparer(
|
||||
autorest.AsGet(),
|
||||
autorest.WithBaseURL(client.BaseURI),
|
||||
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings", pathParameters),
|
||||
autorest.WithQueryParameters(queryParameters))
|
||||
return preparer.Prepare((&http.Request{}).WithContext(ctx))
|
||||
}
|
||||
|
||||
// ListSender sends the List request. The method will close the
|
||||
// http.Response Body if it receives an error.
|
||||
func (client ExpressRouteCrossConnectionPeeringsClient) ListSender(req *http.Request) (*http.Response, error) {
|
||||
return autorest.SendWithSender(client, req,
|
||||
azure.DoRetryWithRegistration(client.Client))
|
||||
}
|
||||
|
||||
// ListResponder handles the response to the List request. The method always
|
||||
// closes the http.Response Body.
|
||||
func (client ExpressRouteCrossConnectionPeeringsClient) ListResponder(resp *http.Response) (result ExpressRouteCrossConnectionPeeringList, err error) {
|
||||
err = autorest.Respond(
|
||||
resp,
|
||||
client.ByInspecting(),
|
||||
azure.WithErrorUnlessStatusCode(http.StatusOK),
|
||||
autorest.ByUnmarshallingJSON(&result),
|
||||
autorest.ByClosing())
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return
|
||||
}
|
||||
|
||||
// listNextResults retrieves the next set of results, if any.
|
||||
func (client ExpressRouteCrossConnectionPeeringsClient) listNextResults(lastResults ExpressRouteCrossConnectionPeeringList) (result ExpressRouteCrossConnectionPeeringList, err error) {
|
||||
req, err := lastResults.expressRouteCrossConnectionPeeringListPreparer()
|
||||
if err != nil {
|
||||
return result, autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "listNextResults", nil, "Failure preparing next results request")
|
||||
}
|
||||
if req == nil {
|
||||
return
|
||||
}
|
||||
resp, err := client.ListSender(req)
|
||||
if err != nil {
|
||||
result.Response = autorest.Response{Response: resp}
|
||||
return result, autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "listNextResults", resp, "Failure sending next results request")
|
||||
}
|
||||
result, err = client.ListResponder(resp)
|
||||
if err != nil {
|
||||
err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "listNextResults", resp, "Failure responding to next results request")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ListComplete enumerates all values, automatically crossing page boundaries as required.
|
||||
func (client ExpressRouteCrossConnectionPeeringsClient) ListComplete(ctx context.Context, resourceGroupName string, crossConnectionName string) (result ExpressRouteCrossConnectionPeeringListIterator, err error) {
|
||||
result.page, err = client.List(ctx, resourceGroupName, crossConnectionName)
|
||||
return
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user