diff --git a/bce/client.go b/bce/client.go index 1600920b..efc189e5 100644 --- a/bce/client.go +++ b/bce/client.go @@ -86,6 +86,7 @@ func (c *BceClient) buildHttpRequest(request *BceRequest) { // Set the BCE request headers request.SetHeader(http.HOST, request.Host()) + request.SetHeader(http.CONTENT_TYPE, "application/json;charset=UTF-8") request.SetHeader(http.USER_AGENT, c.Config.UserAgent) request.SetHeader(http.BCE_DATE, util.FormatISO8601Date(util.NowUTCSeconds())) @@ -253,12 +254,12 @@ func NewBceClientWithAkSk(ak, sk, endPoint string) (*BceClient, error) { HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} defaultConf := &BceClientConfiguration{ - Endpoint: endPoint, - Region: DEFAULT_REGION, - UserAgent: DEFAULT_USER_AGENT, - Credentials: credentials, - SignOption: defaultSignOptions, - Retry: DEFAULT_RETRY_POLICY, + Endpoint: endPoint, + Region: DEFAULT_REGION, + UserAgent: DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: DEFAULT_RETRY_POLICY, ConnectionTimeoutInMillis: DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS, RedirectDisabled: false} v1Signer := &auth.BceV1Signer{} diff --git a/services/bbc/client.go b/services/bbc/client.go index 3cd5dda4..5425c26e 100644 --- a/services/bbc/client.go +++ b/services/bbc/client.go @@ -19,6 +19,7 @@ package bbc import ( "encoding/json" + "github.com/baidubce/bce-sdk-go/auth" "github.com/baidubce/bce-sdk-go/bce" "github.com/baidubce/bce-sdk-go/services/bcc/api" @@ -656,6 +657,28 @@ func (c *Client) ListImage(args *ListImageArgs) (*ListImageResult, error) { return ListImage(c, args) } +//ListImage - list Custom Flavor images +// +// PARAMS: +// - args: the arguments to list all images +// RETURNS: +// - *ListImageResult: the result of list all images +// - error: nil if success otherwise the specific error +func (c *Client) ListCustomFlavorImage(args *ListImageArgs) (*FlavorImageResult, error) { + return ListCustomFlavorImage(c, args) +} + +//ListImage - list Flavor images +// +// PARAMS: +// - args: the arguments to list all images +// RETURNS: +// - *ListImageResult: the result of list all images +// - error: nil if success otherwise the specific error +func (c *Client) ListFlavorImage(args *ListImageArgs) (*FlavorImageResult, error) { + return ListFlavorImage(c, args) +} + // GetImageDetail - get an image's detail info // // PARAMS: @@ -908,7 +931,6 @@ func (c *Client) RemoteCopyImage(imageId string, args *RemoteCopyImageArgs) erro return RemoteCopyImage(c, imageId, args) } - // RemoteCopyImageReturnImageIds - copy an image from other region // // PARAMS: diff --git a/services/bbc/image.go b/services/bbc/image.go index f3ec660e..213c4c8a 100644 --- a/services/bbc/image.go +++ b/services/bbc/image.go @@ -108,6 +108,98 @@ func ListImage(cli bce.Client, queryArgs *ListImageArgs) (*ListImageResult, erro return jsonBody, nil } +//ListImage - list custom flavor images +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to list all images +// RETURNS: +// - *ListImageResult: the result of list all images +// - error: nil if success otherwise the specific error +func ListCustomFlavorImage(cli bce.Client, queryArgs *ListImageArgs) (*FlavorImageResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getCustomFlavorImageUri()) + req.SetMethod(http.POST) + + if queryArgs != nil { + if len(queryArgs.Marker) != 0 { + req.SetParam("marker", queryArgs.Marker) + } + if queryArgs.MaxKeys != 0 { + req.SetParam("maxKeys", strconv.Itoa(queryArgs.MaxKeys)) + } + if len(queryArgs.ImageType) != 0 { + req.SetParam("imageType", queryArgs.ImageType) + } + } + + if queryArgs == nil || queryArgs.MaxKeys == 0 { + req.SetParam("maxKeys", "1000") + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &FlavorImageResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +//ListImage - list flavor images +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to list all images +// RETURNS: +// - *ListImageResult: the result of list all images +// - error: nil if success otherwise the specific error +func ListFlavorImage(cli bce.Client, queryArgs *ListImageArgs) (*FlavorImageResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getFlavorImageUri()) + req.SetMethod(http.POST) + + if queryArgs != nil { + if len(queryArgs.Marker) != 0 { + req.SetParam("marker", queryArgs.Marker) + } + if queryArgs.MaxKeys != 0 { + req.SetParam("maxKeys", strconv.Itoa(queryArgs.MaxKeys)) + } + if len(queryArgs.ImageType) != 0 { + req.SetParam("imageType", queryArgs.ImageType) + } + } + + if queryArgs == nil || queryArgs.MaxKeys == 0 { + req.SetParam("maxKeys", "1000") + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &FlavorImageResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + // GetImageDetail - get an image's detail info // // PARAMS: @@ -449,6 +541,13 @@ func getImageUri() string { return URI_PREFIX_V1 + REQUEST_IMAGE_URI } +func getFlavorImageUri() string { + return URI_PREFIX_V1 + "/flavor/image" +} +func getCustomFlavorImageUri() string { + return URI_PREFIX_V1 + "/customFlavor/image" +} + func getImageUriWithId(id string) string { return URI_PREFIX_V1 + REQUEST_IMAGE_URI + "/" + id } @@ -463,4 +562,4 @@ func getCustomImageUri() string { func getImageSharedUserUri(id string) string { return URI_PREFIX_V1 + REQUEST_IMAGE_URI + "/" + id + REQUEST_IMAGE_SHAREDUSER_URI -} \ No newline at end of file +} diff --git a/services/bbc/model.go b/services/bbc/model.go index e1f81779..2b683504 100644 --- a/services/bbc/model.go +++ b/services/bbc/model.go @@ -121,9 +121,11 @@ type CreateInstanceArgs struct { Tags []model.TagModel `json:"tags,omitempty"` InternalIps []string `json:"internalIps,omitempty"` RequestToken string `json:"requestToken"` - EnableNuma bool `json:"enableNuma"` + EnableNuma bool `json:"enableNuma,omitempty"` + EnableHt bool `json:"enableHt"` RootPartitionType string `json:"rootPartitionType,omitempty"` DataPartitionType string `json:"dataPartitionType,omitempty"` + KeypairId string `json:"keypairId,omitempty"` } const ( @@ -216,23 +218,23 @@ type ListRecycledInstancesResult struct { } type RecycledInstancesModel struct { - ServiceType string `json:"serviceType"` - ServiceName string `json:"serviceName"` - Name string `json:"name"` - Id string `json:"id"` - SerialNumber string `json:"serialNumber"` - RecycleTime string `json:"recycleTime"` - DeleteTime string `json:"deleteTime"` - PaymentTiming string `json:"paymentTiming"` - ConfigItems []string `json:"configItems"` - ConfigItem RecycleInstanceModelConfigItem `json:"configItem"` + ServiceType string `json:"serviceType"` + ServiceName string `json:"serviceName"` + Name string `json:"name"` + Id string `json:"id"` + SerialNumber string `json:"serialNumber"` + RecycleTime string `json:"recycleTime"` + DeleteTime string `json:"deleteTime"` + PaymentTiming string `json:"paymentTiming"` + ConfigItems []string `json:"configItems"` + ConfigItem RecycleInstanceModelConfigItem `json:"configItem"` } type RecycleInstanceModelConfigItem struct { - Cpu int `json:"cpu"` - Memory int `json:"memory"` - Type string `json:"type"` - ZoneName string `json:"zoneName"` + Cpu int `json:"cpu"` + Memory int `json:"memory"` + Type string `json:"type"` + ZoneName string `json:"zoneName"` } type ListInstancesResult struct { @@ -304,6 +306,7 @@ type ModifyInstanceHostnameArgs struct { type RebuildInstanceArgs struct { ImageId string `json:"imageId"` AdminPass string `json:"adminPass"` + KeypairId string `json:"keypairId,omitempty"` IsPreserveData bool `json:"isPreserveData"` RaidId string `json:"raidId,omitempty"` SysRootSize int `json:"sysRootSize,omitempty"` @@ -423,6 +426,13 @@ type ListImageResult struct { MaxKeys int `json:"maxKeys"` Images []ImageModel `json:"images"` } +type FlavorImageMapping struct { + FlavorID string `json:"flavorId"` + Images []ImageModel `json:"images"` +} +type FlavorImageResult struct { + Result []FlavorImageMapping `json:"result"` +} type ImageModel struct { OsVersion string `json:"osVersion"` diff --git a/services/bcc/api/instance.go b/services/bcc/api/instance.go index 0d75604f..0ec27127 100644 --- a/services/bcc/api/instance.go +++ b/services/bcc/api/instance.go @@ -968,6 +968,33 @@ func InstancePurchaseReserved(cli bce.Client, instanceId, relatedRenewFlag, clie return nil } +// DeletePrepaidInstanceWithRelatedResource - delete a prepaid instance with related resources +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: request body to delete instance +// RETURNS: +// - error: nil if success otherwise the specific error +func DeletePrepaidInstanceWithRelatedResource(cli bce.Client, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeletePrepaidInstanceUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + // DeleteInstanceWithRelatedResource - delete an instance with related resources // // PARAMS: diff --git a/services/bcc/api/model.go b/services/bcc/api/model.go index 247b654a..c918cbd7 100644 --- a/services/bcc/api/model.go +++ b/services/bcc/api/model.go @@ -780,6 +780,13 @@ type DeleteInstanceWithRelateResourceArgs struct { DeleteRelatedEnisFlag bool `json:"deleteRelatedEnisFlag"` } +type DeletePrepaidInstanceWithRelateResourceArgs struct { + RelatedReleaseFlag bool `json:"relatedReleaseFlag"` + DeleteCdsSnapshotFlag bool `json:"deleteCdsSnapshotFlag"` + InstanceId string `json:"instanceId"` + DeleteRelatedEnisFlag bool `json:"deleteRelatedEnisFlag"` +} + type InstanceChangeVpcArgs struct { InstanceId string `json:"instanceId"` SubnetId string `json:"subnetId"` diff --git a/services/bcc/api/util.go b/services/bcc/api/util.go index 7d4e2896..30f5d605 100644 --- a/services/bcc/api/util.go +++ b/services/bcc/api/util.go @@ -107,6 +107,9 @@ func getInstanceBySpecUri() string { func getInstanceUriWithId(id string) string { return URI_PREFIXV2 + REQUEST_INSTANCE_URI + "/" + id } +func getDeletePrepaidInstanceUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + "/delete" +} func getRecoveryInstanceUri() string { return URI_PREFIXV2 + REQUEST_INSTANCE_URI + REQUEST_RECOVERY_URI diff --git a/services/bcc/client.go b/services/bcc/client.go index 4a632bab..eb79ceaf 100644 --- a/services/bcc/client.go +++ b/services/bcc/client.go @@ -250,7 +250,7 @@ func (c *Client) DeleteInstance(instanceId string) error { // - error: nil if success otherwise the specific error func (c *Client) AutoReleaseInstance(instanceId string, releaseTime string) error { args := &api.AutoReleaseArgs{ - ReleaseTime: releaseTime, + ReleaseTime: releaseTime, } return api.AutoReleaseInstance(c, instanceId, args) } @@ -632,6 +632,25 @@ func (c *Client) DeleteInstanceWithRelateResource(instanceId string, args *api.D return api.DeleteInstanceWithRelatedResource(c, instanceId, body) } +// DeletePrepaidInstanceWithRelateResource - delete a prepaid instance and all eip/cds relate it +// +// PARAMS: +// - args: the arguments to delete instance and its relate resource +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeletePrepaidInstanceWithRelateResource(args *api.DeletePrepaidInstanceWithRelateResourceArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.DeletePrepaidInstanceWithRelatedResource(c, body) +} + // InstanceChangeSubnet - change an instance's subnet // // PARAMS: @@ -1015,7 +1034,6 @@ func (c *Client) RemoteCopyImage(imageId string, args *api.RemoteCopyImageArgs) return api.RemoteCopyImage(c, imageId, args) } - // RemoteCopyImageReturnImageIds - copy an image from other region // // PARAMS: @@ -1531,7 +1549,6 @@ func (c *Client) GetAvailableDiskInfo(zoneName string) (*api.GetAvailableDiskInf return api.GetAvailableDiskInfo(c, zoneName) } - // DeletePrepayVolume - delete the volumes for prepay // // PARAMS: @@ -1690,6 +1707,3 @@ func (c *Client) DeleteRecycledInstance(instanceId string) error { func (c *Client) ListInstanceByInstanceIds(args *api.ListInstanceByInstanceIdArgs) (*api.ListInstancesResult, error) { return api.ListInstanceByInstanceIds(c, args) } - - - diff --git a/services/bes/client.go b/services/bes/client.go new file mode 100644 index 00000000..a88b9a15 --- /dev/null +++ b/services/bes/client.go @@ -0,0 +1,211 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for BES service + +// Package bes defines the BES services of BCE. The supported APIs are all defined in sub-package +package bes + +import ( + "encoding/json" + + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +const DEFAULT_SERVICE_DOMAIN = "bes." + bce.DEFAULT_REGION + ".baidubce.com" + +// Client of BES service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +// NewClient make the BES service client with default configuration. +// Use `cli.Config.xxx` to access the config or change it to non-default value. +func NewClient(ak, sk, endPoint string) (*Client, error) { + credentials, err := auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + if endPoint == "" { + endPoint = DEFAULT_SERVICE_DOMAIN + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endPoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + + client := &Client{bce.NewBceClient(defaultConf, v1Signer)} + return client, nil +} + +// CreateInstance - create an instance with the specific parameters +// +// PARAMS: +// - args: the arguments to create instance +// RETURNS: +// - *CreateInstanceResult: the result of create Instance, contains new Instance ID +// - error: nil if success otherwise the specific error +func (c *Client) CreateCluster(args *ESClusterRequest) (*ESClusterResponse, error) { + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return CreateCluster(c, args, body) +} +func (c *Client) DeleteCluster(args *GetESClusterRequest) (*DeleteESClusterResponse, error) { + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return DeleteCluster(c, args, body) +} +func (c *Client) GetCluster(args *GetESClusterRequest) (*DetailESClusterResponse, error) { + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return GetCluster(c, args, body) +} +func getCreateUri() string { + return "/api/bes/cluster/create" +} +func getReadUri() string { + return "/api/bes/cluster/detail" +} +func getDeleteUri() string { + return "/api/bes/cluster/delete" +} + +func GetCluster(cli bce.Client, args *GetESClusterRequest, reqBody *bce.Body) (*DetailESClusterResponse, error) { + //clientToken := args.ClientToken + //requestToken := args.RequestToken + // Build the request + req := &bce.BceRequest{} + req.SetUri(getReadUri()) + req.SetHeader("Content-Type", "application/json;charset=UTF-8") + req.SetHeader("X-Region", cli.GetBceClientConfig().Region) + req.SetMethod(http.POST) + req.SetBody(reqBody) + //req.SetHeader("x-request-token", requestToken) + + //if clientToken != "" { + // req.SetParam("clientToken", clientToken) + //} + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &DetailESClusterResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +func DeleteCluster(cli bce.Client, args *GetESClusterRequest, reqBody *bce.Body) (*DeleteESClusterResponse, error) { + //clientToken := args.ClientToken + //requestToken := args.RequestToken + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeleteUri()) + req.SetHeader("Content-Type", "application/json;charset=UTF-8") + req.SetHeader("X-Region", cli.GetBceClientConfig().Region) + req.SetMethod(http.POST) + req.SetBody(reqBody) + //req.SetHeader("x-request-token", requestToken) + + //if clientToken != "" { + // req.SetParam("clientToken", clientToken) + //} + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &DeleteESClusterResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} +func CreateCluster(cli bce.Client, args *ESClusterRequest, reqBody *bce.Body) (*ESClusterResponse, error) { + //clientToken := args.ClientToken + //requestToken := args.RequestToken + // Build the request + req := &bce.BceRequest{} + req.SetUri(getCreateUri()) + req.SetHeader("Content-Type", "application/json;charset=UTF-8") + req.SetHeader("X-Region", cli.GetBceClientConfig().Region) + req.SetMethod(http.POST) + req.SetBody(reqBody) + //req.SetHeader("x-request-token", requestToken) + + //if clientToken != "" { + // req.SetParam("clientToken", clientToken) + //} + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ESClusterResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} diff --git a/services/bes/client_test.go b/services/bes/client_test.go new file mode 100644 index 00000000..42328a27 --- /dev/null +++ b/services/bes/client_test.go @@ -0,0 +1,105 @@ +package bes + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "runtime" + "testing" + + "github.com/baidubce/bce-sdk-go/model" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + BES_CLIENT *Client + BES_TestBbcId string + BES_TestImageId string + BES_TestFlavorId string + BES_TestRaidId string + BES_TestZoneName string + BES_TestSubnetId string + BES_TestName string + BES_TestAdminPass string + BES_TestDeploySetId string + BES_TestClientToken string + BES_TestSecurityGroupId string + BES_TestTaskId string + BES_TestErrResult string + BES_TestRuleId string +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +func init() { + _, f, _, _ := runtime.Caller(0) + for i := 0; i < 6; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fmt.Println(conf) + fp, err := os.Open(conf) + if err != nil { + fmt.Println("config json file of ak/sk not given: ", conf) + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + BES_TestFlavorId = "flavor-id" + BES_TestImageId = "image-id" + BES_TestRaidId = "raid-id" + BES_TestZoneName = "zone-name" + BES_TestSubnetId = "subnet-id" + BES_TestName = "sdkTest" + BES_TestAdminPass = "123@adminPass" + BES_TestDeploySetId = "deployset-id" + BES_TestBbcId = "bbc_id" + BES_TestSecurityGroupId = "bbc-security-group-id" + BES_TestTaskId = "task-id" + BES_TestErrResult = "err-result" + BES_TestRuleId = "rule-id" + BES_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + log.SetLogLevel(log.WARN) + //log.SetLogLevel(log.DEBUG) +} + +func TestCreateInstance(t *testing.T) { + InternalIps := []string{"ip"} + createInstanceArgs := &CreateInstanceArgs{ + FlavorId: BES_TestFlavorId, + ImageId: BES_TestImageId, + RaidId: BES_TestRaidId, + RootDiskSizeInGb: 40, + PurchaseCount: 1, + AdminPass: "AdminPass", + ZoneName: BES_TestZoneName, + SubnetId: BES_TestSubnetId, + SecurityGroupId: BES_TestSecurityGroupId, + ClientToken: BES_TestClientToken, + Billing: Billing{ + PaymentTiming: PaymentTimingPostPaid, + }, + DeploySetId: BES_TestDeploySetId, + Name: BES_TestName, + EnableNuma: false, + InternalIps: InternalIps, + Tags: []model.TagModel{ + { + TagKey: "tag1", + TagValue: "var1", + }, + }, + } + res, err := BES_CLIENT.CreateInstance(createInstanceArgs) + fmt.Println(res) + ExpectEqual(t.Errorf, err, nil) +} diff --git a/services/bes/es_model.go b/services/bes/es_model.go new file mode 100644 index 00000000..b70f5b9f --- /dev/null +++ b/services/bes/es_model.go @@ -0,0 +1,107 @@ +package bes + +type ESDiskSlotInfo struct { + Size int `json:"size,omitempty"` + Type string `json:"type,omitempty"` +} +type ESAutoRenewInfo struct { + RenewTimeUnit string `json:"renewTimeUnit,omitempty"` + RenewTime int `json:"renewTime,omitempty"` +} +type ESClusterModule struct { + InstanceNum int `json:"instanceNum"` + SlotType string `json:"slotType"` + DiskSlotInfo *ESDiskSlotInfo `json:"diskSlotInfo,omitempty"` + Type string `json:"type"` +} +type ESBilling struct { + PaymentType string `json:"paymentType,omitempty"` + Time *int `json:"time,omitempty"` + EnableAutoRenew *bool `json:"enableAutoRenew,omitempty"` + AutoRenewInfo *ESAutoRenewInfo `json:"autoRenewInfo,omitempty"` +} +type ESClusterRequest struct { + Name string `json:"name"` + Password string `json:"password,omitempty"` + SecurityGroupID string `json:"securityGroupId"` + SubnetUUID string `json:"subnetUuid"` + AvailableZone string `json:"availableZone"` + VpcID string `json:"vpcId"` + IsOldPackage bool `json:"isOldPackage"` + Version string `json:"version"` + Modules []*ESClusterModule `json:"modules"` + Billing ESBilling `json:"billing"` +} + +type DetailESClusterResponse struct { + Result struct { + DesireStatus string `json:"desireStatus"` + Subnet string `json:"subnet"` + EsURL string `json:"esUrl"` + KibanaURL string `json:"kibanaUrl"` + KibanaEip string `json:"kibanaEip"` + Instances []struct { + InstanceID string `json:"instanceId"` + ModuleType string `json:"moduleType"` + HostIP string `json:"hostIp"` + ModuleVersion string `json:"moduleVersion"` + Status string `json:"status"` + } `json:"instances"` + Vpc string `json:"vpc"` + ClusterID string `json:"clusterId"` + SecurityGroup string `json:"securityGroup"` + Modules []struct { + SlotDescription string `json:"slotDescription"` + SlotType string `json:"slotType"` + ActualInstanceNum int `json:"actualInstanceNum"` + Type string `json:"type"` + Version string `json:"version"` + } `json:"modules"` + Billing struct { + PaymentType string `json:"paymentType"` + } `json:"billing"` + Network []struct { + SubnetID string `json:"subnetId"` + Subnet string `json:"subnet"` + AvailableZone string `json:"availableZone"` + } `json:"network"` + AdminUsername string `json:"adminUsername"` + AvailableZone string `json:"availableZone"` + ExpireTime string `json:"expireTime"` + ActualStatus string `json:"actualStatus"` + ClusterName string `json:"clusterName"` + VpcID string `json:"vpcId"` + EsEip string `json:"esEip"` + Region string `json:"region"` + } `json:"result"` + Success bool `json:"success"` + Status int `json:"status"` +} + +type GetESClusterRequest struct { + ClusterId string `json:"clusterId"` +} + +type ESClusterResponse struct { + Status int `json:"status"` + Success bool `json:"success"` + Code string `json:"code"` + Error struct { + RequestId string `json:"requestId"` + Code string `json:"code"` + Message string `json:"message"` + } + Message struct { + Global string `json:"global"` + } + Result struct { + OrderId string `json:"orderId"` + ClusterId string `json:"clusterId"` + } `json:"result"` +} + +type DeleteESClusterResponse struct { + Result string `json:"result"` + Success bool `json:"success"` + Status int `json:"status"` +} diff --git a/services/bes/util.go b/services/bes/util.go new file mode 100644 index 00000000..4d830b95 --- /dev/null +++ b/services/bes/util.go @@ -0,0 +1,91 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// util.go - define the utilities for api package of BES service +package bes + +import ( + "encoding/hex" + "fmt" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/util/crypto" +) + +const ( + URI_PREFIX_V1 = bce.URI_PREFIX + "v1" + URI_PREFIX_V2 = bce.URI_PREFIX + "v2" + + REQUEST_INSTANCE_URI = "/instance" + REQUEST_INSTANCE_LABEL_URI = "/instanceByLabel" + REQUEST_BATCH_DELETE_URI = "/batchDelete" + REQUEST_RECYCLE_URI = "/recycle" + REQUEST_RECOVERY_URI = "/recovery" + REQUEST_SUBNET_URI = "/vpcSubnet" + REQUEST_VPC_URI = "/vpc" + SECURITY_GROUP_URI = "/securitygroup" + + REQUEST_IMAGE_URI = "/image" + REQUEST_BATCHADDIP_URI = "/batchAddIp" + REQUEST_BATCHADDIPCROSSSUBNET_URI = "/batchAddIpCrossSubnet" + REQUEST_BATCHDELIP_URI = "/batchDelIp" + REQUEST_BATCH_CREATE_AUTORENEW_RULES_URI = "/batchCreateAutoRenewRules" + REQUEST_BATCH_Delete_AUTORENEW_RULES_URI = "/batchDeleteAutoRenewRules" + REQUEST_BATCH_REBUILD_INSTANCE_URI = "/batchRebuild" + + REQUEST_FLAVOR_URI = "/flavor" + REQUEST_FLAVOR_RAID_URI = "/flavorRaid" + REQUEST_COMMON_IMAGE_URI = "/flavor/image" + REQUEST_CUSTOM_IMAGE_URI = "/customFlavor/image" + REQUEST_IMAGE_SHAREDUSER_URI = "/sharedUsers" + + REQUEST_FLAVOR_ZONE_URI = "/order/flavorZone" + REQUEST_FLAVORS_URI = "/order/flavor" + + REQUEST_OPERATION_LOG_URI = "/operationLog" + + REQUEST_DEPLOY_SET_URI = "/deployset" + REQUEST_INSTANCE_PORT_URI = "/vpcPort" + + REQUEST_REPAIR_TASK_URI = "/task" + REQUEST_REPAIR_CLOSED_TASK_URI = "/closedTask" + + REQUEST_RULE_URI = "/rule" + REQUEST_CREATE_URI = "/create" + REQUEST_DELETE_URI = "/delete" + REQUEST_DISABLE_URI = "/disable" + REQUEST_ENABLE_URI = "/enable" + REQUEST_VOLUME_URI = "/volume" +) + +func Aes128EncryptUseSecreteKey(sk string, data string) (string, error) { + if len(sk) < 16 { + return "", fmt.Errorf("error secrete key") + } + + crypted, err := crypto.EBCEncrypto([]byte(sk[:16]), []byte(data)) + if err != nil { + return "", err + } + + return hex.EncodeToString(crypted), nil +} + +func getVolumeUri() string { + return URI_PREFIX_V1 + REQUEST_VOLUME_URI +} + +func geBbcStockWithDeploySetUri() string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI + "/getStockWithDeploySet" +} diff --git a/services/blb/model.go b/services/blb/model.go index 3a257f35..41692cb6 100644 --- a/services/blb/model.go +++ b/services/blb/model.go @@ -43,6 +43,7 @@ type CreateLoadBalancerArgs struct { Description string `json:"desc,omitempty"` SubnetId string `json:"subnetId"` VpcId string `json:"vpcId"` + Eip string `json:"eip,omitempty"` ClusterProperty string `json:"clusterProperty"` Tags []model.TagModel `json:"tags,omitempty"` } @@ -82,7 +83,7 @@ type BLBModel struct { Layer4ClusterId string `json:"layer4ClusterId"` Layer7ClusterId string `json:"layer7ClusterId"` Tags []model.TagModel `json:"tags"` - EipRouteType string `json:"eipRouteType"` + EipRouteType string `json:"eipRouteType"` } type DescribeLoadBalancersResult struct { @@ -96,7 +97,7 @@ type ListenerModel struct { } type PortTypeModel struct { - Port int `json:"port"` + Port int `json:"port"` Type string `json:"type"` } @@ -114,7 +115,7 @@ type DescribeLoadBalancerDetailResult struct { Layer7ClusterId string `json:"layer7ClusterId"` Listener []ListenerModel `json:"listener"` Tags []model.TagModel `json:"tags"` - EipRouteType string `json:"eipRouteType"` + EipRouteType string `json:"eipRouteType"` } type CreateTCPListenerArgs struct { @@ -376,7 +377,7 @@ type HTTPSListenerModel struct { ClientCertIds []string `json:"clientCertIds"` EncryptionType string `json:"encryptionType"` EncryptionProtocols []string `json:"encryptionProtocols"` - AppliedCiphers string `json:"appliedCiphers"` + AppliedCiphers string `json:"appliedCiphers"` } type SSLListenerModel struct { @@ -391,7 +392,7 @@ type SSLListenerModel struct { CertIds []string `json:"certIds"` EncryptionType string `json:"encryptionType"` EncryptionProtocols []string `json:"encryptionProtocols"` - AppliedCiphers string `json:"appliedCiphers"` + AppliedCiphers string `json:"appliedCiphers"` DualAuth bool `json:"dualAuth"` ClientCertIds []string `json:"clientCertIds"` ServerTimeout int `json:"serverTimeout"` @@ -419,15 +420,15 @@ type AllListenerModel struct { UnhealthyThreshold int `json:"unhealthyThreshold"` HealthyThreshold int `json:"healthyThreshold"` HealthCheckNormalStatus string `json:"healthCheckNormalStatus"` - HealthCheckHost string `json:"healthCheckHost"` + HealthCheckHost string `json:"healthCheckHost"` ServerTimeout int `json:"serverTimeout"` RedirectPort int `json:"redirectPort"` CertIds []string `json:"certIds"` DualAuth bool `json:"dualAuth"` ClientCertIds []string `json:"clientCertIds"` - EncryptionType string `json:"encryptionType"` + EncryptionType string `json:"encryptionType"` EncryptionProtocols []string `json:"encryptionProtocols"` - AppliedCiphers string `json:"appliedCiphers"` + AppliedCiphers string `json:"appliedCiphers"` } type DescribeListenerArgs struct { @@ -467,9 +468,9 @@ type DescribeAllListenersResult struct { } type DeleteListenersArgs struct { - ClientToken string `json:"-"` - PortList []uint16 `json:"portList"` - PortTypeList []PortTypeModel `json:"portTypeList"` + ClientToken string `json:"-"` + PortList []uint16 `json:"portList"` + PortTypeList []PortTypeModel `json:"portTypeList"` } type AddBackendServersArgs struct { diff --git a/services/cce/model.go b/services/cce/model.go index cf5d4146..1ee9b712 100644 --- a/services/cce/model.go +++ b/services/cce/model.go @@ -138,7 +138,7 @@ const ( type DiskSizeConfig struct { Size string `json:"size"` VolumeType VolumeType `json:"volumeType"` - SnapshotId string `json:"snapshotId,omitempty"` + SnapshotId string `json:"snapshotId"` } type CdsConfig struct { diff --git a/services/cce/v2/types/cluster.go b/services/cce/v2/types/cluster.go index b2512dc7..7261916b 100644 --- a/services/cce/v2/types/cluster.go +++ b/services/cce/v2/types/cluster.go @@ -101,7 +101,7 @@ const ( //支持在console创建集群 K8S_1_13_10 K8SVersion = "1.13.10" //K8S_1_16_3 K8SVersion = "1.16.3" - K8S_1_16_8 K8SVersion = "1.16.8" + K8S_1_16_8 K8SVersion = "1.16.8" ) // MasterConfig Master 配置 @@ -121,14 +121,16 @@ type MasterConfig struct { // ManagedClusterMasterOption 托管集群 Master 配置 type ManagedClusterMasterOption struct { - MasterVPCSubnetZone AvailableZone `json:"masterVPCSubnetZone,omitempty"` + MasterVPCSubnetZone AvailableZone `json:"masterVPCSubnetZone,omitempty"` } // RuntimeType defines the runtime on each node type RuntimeType string const ( - RuntimeTypeDocker RuntimeType = "docker" + RuntimeTypeDocker RuntimeType = "docker" + RuntimeTypeContainerd RuntimeType = "containerd" + RuntimeTypeBci RuntimeType = "bci" ) // ContainerNetworkConfig defines the network config @@ -234,6 +236,8 @@ const ( // MasterTypeServerless Serverless集群Master MasterTypeServerless MasterType = "serverless" + // 容器化部署 + MasterTypeContainerizedCustom MasterType = "containerizedCustom" ) // ClusterHA Cluster Master 对应副本数 @@ -288,4 +292,4 @@ const ( // AuthenticateModeOIDC - OIDC AuthenticateModeOIDC AuthenticateMode = "oidc" -) \ No newline at end of file +) diff --git a/services/cce/v2/types/instance.go b/services/cce/v2/types/instance.go index 2ff22a29..8ed5befb 100644 --- a/services/cce/v2/types/instance.go +++ b/services/cce/v2/types/instance.go @@ -49,7 +49,7 @@ type InstanceSpec struct { BidOption BidOption `json:"bidOption,omitempty"` // VPC 相关配置 - VPCConfig VPCConfig `json:"vpcConfig,omitempty"` + VPCConfig *VPCConfig `json:"vpcConfig,omitempty"` // 集群规格相关配置 InstanceResource InstanceResource `json:"instanceResource,omitempty"` @@ -86,12 +86,18 @@ type InstanceSpec struct { AutoSnapshotID string `json:"autoSnapshotID,omitempty"` // 自动快照策略 ID } +type SecurityGroup struct { + CustomSecurityGroups []string `json:"customSecurityGroups,omitempty"` + EnableCCERequiredSecurityGroup bool `json:"enableCCERequiredSecurityGroup,omitempty"` + EnableCCEOptionalSecurityGroup bool `json:"enableCCEOptionalSecurityGroup,omitempty"` +} + // VPCConfig 定义 Instance VPC type VPCConfig struct { - VPCID string `json:"vpcID,omitempty"` - VPCSubnetID string `json:"vpcSubnetID,omitempty"` - SecurityGroupID string `json:"securityGroupID,omitempty"` - + VPCID string `json:"vpcID,omitempty"` + VPCSubnetID string `json:"vpcSubnetID,omitempty"` + SecurityGroupID string `json:"securityGroupID,omitempty"` + SecurityGroup SecurityGroup `json:"securityGroup,omitempty"` VPCSubnetType vpc.SubnetType `json:"vpcSubnetType,omitempty"` VPCSubnetCIDR string `json:"vpcSubnetCIDR,omitempty"` VPCSubnetCIDRIPv6 string `json:"vpcSubnetCIDRIPv6,omitempty"` @@ -102,6 +108,7 @@ type VPCConfig struct { // InstanceResource 定义 Instance CPU/MEM/Disk 配置 type InstanceResource struct { MachineSpec string `json:"machineSpec,omitempty"` // 机器规格,例:bcc.g5.c2m8 + SpecId string `json:"specId,omitempty"` // 机器规格系列,例: g5 CPU int `json:"cpu,omitempty"` // unit: Core MEM int `json:"mem,omitempty"` // unit: GB @@ -161,9 +168,9 @@ type BBCOption struct { // DeployCustomConfig - 部署自定义配置 type DeployCustomConfig struct { // Docker相关配置 - DockerConfig DockerConfig `json:"dockerConfig,omitempty"` + DockerConfig *DockerConfig `json:"dockerConfig,omitempty"` // containerd相关配置 - ContainerdConfig ContainerdConfig `json:"containerdConfig,omitempty"` + ContainerdConfig *ContainerdConfig `json:"containerdConfig,omitempty"` // kubelet数据目录 KubeletRootDir string `json:"kubeletRootDir,omitempty"`