This commit is contained in:
zhouqunjie 2022-04-04 17:36:54 +08:00
parent 42e11cd2d6
commit 3317bc7404
50 changed files with 678 additions and 2398 deletions

View File

@ -1,26 +0,0 @@
[pod_create_conf]
region_id=cn-hangzhou
#容器实例名称(pod名) 对应阿里 ContainerGroupName(阿里必需)
container_group_name=pcm-test-ali-pod
#镜像地址 对应阿里 Container.Image(阿里必需)
container_image=registry-vpc.cn-hangzhou.aliyuncs.com/eci_open/nginx
#容器名称 对应阿里 Container.Name(阿里必需)
container_name=pcm-test-ali-container
[pod_delete_conf]
# 地域id
region_id=cn-hangzhou
#容器实例ID
container_group_id=eci-bp1c3eqfq98nz2kbiooo
[pod_list_conf]
# 地域id
region_id=cn-hangzhou
[pod_update_conf]
# 地域id
region_id=cn-hangzhou
#容器实例ID
container_group_id=eci-bp1c3eqfq98nz2kbiooo
#可选 这里用重启策略做更新测试
restart_policy=Never

View File

@ -1,121 +0,0 @@
package eci
import (
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/services/eci"
"gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/common/auth/aksk"
"gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/common/config"
)
// CreateContainerGroup 创建
func CreateContainerGroup(cloudStack string, akskPath string, configPath string) string {
var client *eci.Client
configCommon, _ := config.PCMconfig(configPath)
configAksk, _ := aksk.AkskConfig(cloudStack, akskPath)
//创建客户端
client, _ = eci.NewClientWithAccessKey(configCommon.RegionId, configAksk.AccessKey, configAksk.SecretKey)
// 生成创建请求
createContainerRequest := eci.CreateCreateContainerGroupRequest()
// 必需参数
//区域ID
createContainerRequest.RegionId = configCommon.RegionId
//POD名称
createContainerRequest.ContainerGroupName = configCommon.ContainerGroupName
//容器名称和镜像名称
createContainerRequestContainer := make([]eci.CreateContainerGroupContainer, 1)
createContainerRequestContainer[0].Image = configCommon.ContainerImage
createContainerRequestContainer[0].Name = configCommon.ContainerName
createContainerRequest.Container = &createContainerRequestContainer
client.GetConfig().MaxRetryTime = 0
createContainerGroupResponse, err := client.CreateContainerGroup(createContainerRequest)
if err != nil {
panic(err)
}
containerGroupId := createContainerGroupResponse.ContainerGroupId
fmt.Println("Alibaba ContainerGroup created:", containerGroupId)
return containerGroupId
}
// DescribeContainerGroup 查询Pod
func DescribeContainerGroup(cloudStack string, akskPath string, configPath string) eci.DescribeContainerGroupsContainerGroup0 {
var client *eci.Client
configCommon, _ := config.PCMconfig(configPath)
configAksk, _ := aksk.AkskConfig(cloudStack, akskPath)
client, _ = eci.NewClientWithAccessKey(configCommon.RegionId, configAksk.AccessKey, configAksk.SecretKey)
// 生成查询请求
describeContainerGroupsRequest := eci.CreateDescribeContainerGroupsRequest()
describeContainerGroupsRequest.RegionId = configCommon.RegionIdList
describeContainerGroupsResponse, err := client.DescribeContainerGroups(describeContainerGroupsRequest)
if err != nil {
panic(err)
}
describeContainerGroupNumber := len(describeContainerGroupsResponse.ContainerGroups)
//当前区域没有Pod情形的处理
if describeContainerGroupsResponse.TotalCount != 1 && describeContainerGroupNumber != 1 {
fmt.Println("Invalid ContainerGroups count", describeContainerGroupsResponse.TotalCount, describeContainerGroupNumber)
panic("Invalid ContainerGroups count")
}
fmt.Println("Alibaba ContainerGroup Name:", describeContainerGroupsResponse.ContainerGroups[0].ContainerGroupName, "\n",
"ContainerGroup Id:", describeContainerGroupsResponse.ContainerGroups[0].ContainerGroupId)
return describeContainerGroupsResponse.ContainerGroups[0]
}
// UpdateContainerGroup 更新Pod
func UpdateContainerGroup(cloudStack string, akskPath string, configPath string) string {
var client *eci.Client
configCommon, _ := config.PCMconfig(configPath)
configAksk, _ := aksk.AkskConfig(cloudStack, akskPath)
client, _ = eci.NewClientWithAccessKey(configCommon.RegionId, configAksk.AccessKey, configAksk.SecretKey)
//生成更新请求
updateContainerGroupRequest := eci.CreateUpdateContainerGroupRequest()
updateContainerGroupRequest.RegionId = configCommon.RegionIdUpdate
updateContainerGroupRequest.ContainerGroupId = configCommon.ContainerGroupIdUpdate
//容器实体内容,这里测试可以修改配置文件中的重启策略
updateContainerRequestContainer := make([]eci.UpdateContainerGroupContainer, 1)
updateContainerRequestContainer[0].Image = configCommon.ContainerImage
updateContainerRequestContainer[0].Name = configCommon.ContainerName
updateContainerGroupRequest.Container = &updateContainerRequestContainer
updateContainerGroupRequest.RestartPolicy = configCommon.RestartPolicyUpdate
updateContainerGroupResponse, err := client.UpdateContainerGroup(updateContainerGroupRequest)
if err != nil {
panic(err)
}
requestId := updateContainerGroupResponse.RequestId
fmt.Println("Alibaba ContainerGroup: ", configCommon.ContainerGroupIdUpdate, " Updated with request ID:", requestId)
return requestId
}
// DeleteContainerGroup 删除Pod
func DeleteContainerGroup(cloudStack string, akskPath string, configPath string) string {
var client *eci.Client
configCommon, _ := config.PCMconfig(configPath)
configAksk, _ := aksk.AkskConfig(cloudStack, akskPath)
client, _ = eci.NewClientWithAccessKey(configCommon.RegionId, configAksk.AccessKey, configAksk.SecretKey)
//生成删除请求
deleteContainerGroupRequest := eci.CreateDeleteContainerGroupRequest()
deleteContainerGroupRequest.RegionId = configCommon.RegionIdDelete
deleteContainerGroupRequest.ContainerGroupId = configCommon.ContainerGroupIdDelete
deleteContainerGroupResponse, err := client.DeleteContainerGroup(deleteContainerGroupRequest)
if err != nil {
panic(err)
}
requestId := deleteContainerGroupResponse.RequestId
fmt.Println("Alibaba ContainerGroup: ", configCommon.ContainerGroupIdUpdate, " Deleted with request ID:", requestId)
return requestId
}

View File

@ -1,99 +0,0 @@
package api
import (
"gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/alibaba/eci"
cciAksk "gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/huawei/pkg/auth/aksk"
cci "gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/huawei/resources/pod"
"gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/tencent/eks"
)
//CreatePod 创建Pod通用方法
func CreatePod(cloudStack string, akskPath string, configPath string) {
switch cloudStack {
case "alibaba":
eci.CreateContainerGroup(cloudStack, akskPath, configPath)
case "huawei":
cs, err := cciAksk.NewClient(cloudStack, akskPath, configPath)
if err != nil {
panic(err)
}
_, err = cci.CreatePod(cs, configPath)
if err != nil {
return
}
case "tencent":
eks.CreateEksInstance(cloudStack, akskPath, configPath)
}
}
// DeletePod 删除Pod 通用方法
func DeletePod(cloudStack string, akskPath string, configPath string) {
switch cloudStack {
case "alibaba":
eci.DeleteContainerGroup(cloudStack, akskPath, configPath)
case "huawei":
cs, err := cciAksk.NewClient(cloudStack, akskPath, configPath)
if err != nil {
panic(err)
}
err = cci.DeletePod(cs, configPath)
if err != nil {
return
}
case "tencent":
eks.DeleteEksInstance(cloudStack, akskPath, configPath)
}
}
//UpdatePod 更新Pod通用方法
func UpdatePod(cloudStack string, akskPath string, configPath string) {
switch cloudStack {
case "alibaba":
eci.UpdateContainerGroup(cloudStack, akskPath, configPath)
case "huawei":
cs, err := cciAksk.NewClient(cloudStack, akskPath, configPath)
if err != nil {
panic(err)
}
_, err = cci.UpdatePod(cs, configPath)
if err != nil {
return
}
case "tencent":
eks.UpdateEksInstance(cloudStack, akskPath, configPath)
}
}
//ListPod 查询Pod通用方法
func ListPod(cloudStack string, akskPath string, configPath string) {
switch cloudStack {
case "alibaba":
eci.DescribeContainerGroup(cloudStack, akskPath, configPath)
case "huawei":
cs, err := cciAksk.NewClient(cloudStack, akskPath, configPath)
if err != nil {
panic(err)
}
_, err = cci.ListPod(cs, configPath)
if err != nil {
return
}
case "tencent":
eks.ListEksInstance(cloudStack, akskPath, configPath)
}
}

View File

@ -1,43 +0,0 @@
package aksk
import (
"fmt"
"github.com/Unknwon/goconfig"
"os"
)
type AkskContainerConfig struct {
AccessKey string
SecretKey string
}
func AkskConfig(cloudStack string, akskPath string) (AkskContainerConfig, error) {
var cfg *goconfig.ConfigFile
config, err := goconfig.LoadConfigFile(akskPath)
if err != nil {
fmt.Println("get config file error:", err.Error())
os.Exit(-1)
}
cfg = config
var accessKey string
var secretKey string
switch cloudStack {
case "alibaba":
accessKey, _ = cfg.GetValue(cloudStack, "access_key")
secretKey, _ = cfg.GetValue(cloudStack, "secret_key")
case "huawei":
accessKey, _ = cfg.GetValue(cloudStack, "access_key")
secretKey, _ = cfg.GetValue(cloudStack, "secret_key")
case "tencent":
accessKey, _ = cfg.GetValue(cloudStack, "access_key")
secretKey, _ = cfg.GetValue(cloudStack, "secret_key")
}
var akskConfig = AkskContainerConfig{
AccessKey: accessKey,
SecretKey: secretKey,
}
return akskConfig, nil
}

View File

@ -1,14 +0,0 @@
#阿里
[alibaba]
access_key =
secret_key =
#华为
[huawei]
access_key =
secret_key =
#腾讯
[tencent]
access_key =
secret_key =

View File

@ -1,133 +0,0 @@
package config
import (
"fmt"
"github.com/Unknwon/goconfig"
"os"
"strconv"
)
type PCMContainerConfig struct {
RegionId string
ContainerGroupName string
ContainerImage string
ContainerName string
CpuPod string
MemoryPod string
CpuContainer string
MemoryContainer string
CpuPodFloat float64
MemoryPodFloat float64
CpuContainerFloat float64
MemoryContainerFloat float64
NameSpace string
SecurityGroupId string
SubnetId string
VpcId string
RegionIdDelete string
ContainerGroupIdDelete string
RegionIdList string
NamespaceUpdate string
RegionIdUpdate string
ContainerImageUpdate string
ContainerNameUpdate string
CpuPodUpdate string
MemoryPodUpdate string
ContainerGroupNameUpdate string
ContainerGroupIdUpdate string
RestartPolicyUpdate string
NamespaceDelete string
ContainerGroupNameDelete string
}
func PCMconfig(configPath string) (PCMContainerConfig, error) {
//加载配置文件
var cfg *goconfig.ConfigFile
config, err := goconfig.LoadConfigFile(configPath)
if err != nil {
fmt.Println("get config file error:", err.Error())
os.Exit(-1)
}
cfg = config
//[创建]通用创建必需信息
regionId, _ := cfg.GetValue("pod_create_conf", "region_id")
containerGroupName, _ := cfg.GetValue("pod_create_conf", "container_group_name")
containerImage, _ := cfg.GetValue("pod_create_conf", "container_image")
containerName, _ := cfg.GetValue("pod_create_conf", "container_name")
//[创建]阿里创建必需(unique)
//[创建]腾讯创建必需(unique)
cpuPod, _ := cfg.GetValue("pod_create_conf", "cpu_pod")
memoryPod, _ := cfg.GetValue("pod_create_conf", "memory_pod")
cpuPodFloat, _ := strconv.ParseFloat(cpuPod, 64)
memoryPodFloat, _ := strconv.ParseFloat(memoryPod, 64)
securityGroupId, _ := cfg.GetValue("pod_create_conf", "security_group_id")
subnetId, _ := cfg.GetValue("pod_create_conf", "subnet_id")
vpcId, _ := cfg.GetValue("pod_create_conf", "vpc_id")
//[创建]华为创建必需(unique)
nameSpace, _ := cfg.GetValue("pod_create_conf", "namespace")
//[创建]非必需参数
cpuContainer, _ := cfg.GetValue("pod_create_conf", "cpu_container")
memoryContainer, _ := cfg.GetValue("pod_create_conf", "memory_container")
cpuContainerFloat, _ := strconv.ParseFloat(cpuContainer, 64)
memoryContainerFloat, _ := strconv.ParseFloat(memoryContainer, 64)
//[删除]通用删除配置信息
regionIdDelete, _ := cfg.GetValue("pod_delete_conf", "region_id")
containerGroupIdDelete, _ := cfg.GetValue("pod_delete_conf", "container_group_id")
nameSpaceDelete, _ := cfg.GetValue("pod_delete_conf", "namespace")
containerGroupNameDelete, _ := cfg.GetValue("pod_delete_conf", "container_group_name")
//[查询]通用查询配置信息
regionIdList, _ := cfg.GetValue("pod_list_conf", "region_id")
//[更新]通用更新配置信息
regionIdUpdate, _ := cfg.GetValue("pod_update_conf", "region_id")
namespaceUpdate, _ := cfg.GetValue("pod_update_conf", "namespace")
containerGroupIdUpdate, _ := cfg.GetValue("pod_update_conf", "container_group_id")
restartPolicyUpdate, _ := cfg.GetValue("pod_update_conf", "restart_policy")
ContainerNameUpdate, _ := cfg.GetValue("pod_update_conf", "container_name")
CpuPodUpdate, _ := cfg.GetValue("pod_update_conf", "cpu_pod")
MemoryPodUpdate, _ := cfg.GetValue("pod_update_conf", "memory_pod")
ContainerGroupNameUpdate, _ := cfg.GetValue("pod_update_conf", "container_group_name")
var configCommon = PCMContainerConfig{
RegionId: regionId,
ContainerGroupName: containerGroupName,
ContainerImage: containerImage,
ContainerName: containerName,
CpuPod: cpuPod,
MemoryPod: memoryPod,
CpuContainer: cpuContainer,
MemoryContainer: memoryContainer,
CpuPodFloat: cpuPodFloat,
MemoryPodFloat: memoryPodFloat,
CpuContainerFloat: cpuContainerFloat,
MemoryContainerFloat: memoryContainerFloat,
NameSpace: nameSpace,
SecurityGroupId: securityGroupId,
SubnetId: subnetId,
VpcId: vpcId,
RegionIdDelete: regionIdDelete,
ContainerGroupIdDelete: containerGroupIdDelete,
RegionIdList: regionIdList,
RegionIdUpdate: regionIdUpdate,
NamespaceUpdate: namespaceUpdate,
ContainerGroupIdUpdate: containerGroupIdUpdate,
RestartPolicyUpdate: restartPolicyUpdate,
ContainerImageUpdate: containerName,
ContainerNameUpdate: ContainerNameUpdate,
CpuPodUpdate: CpuPodUpdate,
MemoryPodUpdate: MemoryPodUpdate,
ContainerGroupNameUpdate: ContainerGroupNameUpdate,
NamespaceDelete: nameSpaceDelete,
ContainerGroupNameDelete: containerGroupNameDelete,
}
return configCommon, nil
}

View File

@ -1,45 +0,0 @@
[container_conf]
[pod_create_conf]
#测试账号ak
access_key =
secret_key =
#region
region_id=
#容器实例名称(pod名)
container_group_name=
#镜像地址
container_image=
#容器名称
container_name=
#namespace 华为CCI基于K8S namespace进行管理,需要单独提供namespace (华为必需)
namespace=
#Pod拥有核数 对应腾讯 Cpu(腾讯必需)
cpu_pod=1
#Pod拥有内存大小 对应腾讯 Memory(腾讯必需)
memory_pod=2
#安全组ID 对应腾讯 SecurityGroupIds(腾讯必需)
security_group_id=
#子网ID 对应腾讯 SubnetId(腾讯必需)
subnet_id=
#VPC ID 对应腾讯 VpcId(腾讯必需)
vpc_id=
##考虑多个函数分成不同的配置组
##用户可以在请求中指定任务在各厂商调度比例
##地域、厂商、用户AKSK等信息通过独立的配置文件进行导入
[pod_create_conf]
#可选项,框架可以不必过于细节
ali_count=10000
huawei_count=10000
tencent_count=20000
hangzhou_count=20000
shanghai_count=20000
[pod_delete_conf]
[pod_update_conf]
[pod_list_conf]

View File

@ -1,29 +0,0 @@
package main
func main() {
aliConfigPath := "adaptor/container_api_adaptor/alibaba/eci/config_eci.conf"
huaweiConfigPath := "adaptor/container_api_adaptor/huawei/cci/config_cci.conf"
tencentConfigPath := "adaptor/container_api_adaptor/tencent/eks/config_eks.conf"
akskPath := "adaptor/container_api_adaptor/common/auth/aksk/aksk.conf"
println(aliConfigPath)
println(huaweiConfigPath)
println(tencentConfigPath)
println(akskPath)
//api.CreatePod("alibaba", akskPath, aliConfigPath)
//api.ListPod("alibaba", akskPath, aliConfigPath)
//api.UpdatePod("alibaba", akskPath, aliConfigPath)
//api.DeletePod("alibaba", akskPath, aliConfigPath)
//api.CreatePod("huawei", akskPath, huaweiConfigPath)
//api.ListPod("huawei", akskPath, huaweiConfigPath)
//api.UpdatePod("huawei", akskPath, huaweiConfigPath)
//api.DeletePod("huawei", akskPath, huaweiConfigPath)
//api.CreatePod("tencent", akskPath, tencentConfigPath)
//api.ListPod("tencent", akskPath, tencentConfigPath)
//api.UpdatePod("tencent", akskPath, tencentConfigPath)
//api.DeletePod("tencent", akskPath, tencentConfigPath)
}

View File

@ -1,39 +0,0 @@
[pod_create_conf]
#region 对应华为 Region (华为创建Namespace必需)
region_id=cn-north-4
#namespace 华为CCI基于K8S namespace进行管理,需要单独提供namespace 对应Pod.ObjectMeta.Namespace (华为必需)
namespace=test-k8s-client-namespace1
#容器实例名称(pod名) 对应华为 Pod.ObjectMeta.Name (华为必需)
container_group_name=pcm-test-huawei-pod
#镜像地址 对应华为 Pod.PodSpec.Containers.Container.Image (华为必需)
container_image=library/nginx:stable-alpine-perl
#容器名称 对应华为 Pod.PodSpec.Containers.Container.Name (华为必需)
container_name=pcm-test-huawei-container
#Pod拥有核数 对应华为 Pod.PodSpec.Containers.Container.Resources.Limits.ResourceCPU (华为必需)
cpu_pod=500m
#Pod拥有内存大小 对应华为 Pod.PodSpec.Containers.Container.Resources.Limits.ResourceMemory (华为必需)
memory_pod=1024Mi
[pod_delete_conf]
# 地域id
namespace=test-k8s-client-namespace1
#容器实例名称(pod名) 对应华为 Pod.ObjectMeta.Name (华为必需)
container_group_name=pcm-test-huawei-pod
[pod_list_conf]
# 地域id
region_id=cn-hangzhou
[pod_update_conf]
#容器实例名称(pod名) 对应华为 Pod.ObjectMeta.Name (华为必需)
container_group_name=pcm-test-huawei-pod
#镜像地址 对应华为 Pod.PodSpec.Containers.Container.Image (华为必需)
container_image=library/nginx:stable-alpine-perl
#容器名称 对应华为 Pod.PodSpec.Containers.Container.Name (华为必需)
container_name=pcm-test-huawei-container-new
#Pod拥有核数 对应华为 Pod.PodSpec.Containers.Container.Resources.Limits.ResourceCPU (华为必需)
cpu_pod=500m
#Pod拥有内存大小 对应华为 Pod.PodSpec.Containers.Container.Resources.Limits.ResourceMemory (华为必需)
memory_pod=2048Mi
namespace=test-k8s-client-namespace1
restart_policy=Always

View File

@ -1,4 +0,0 @@
// +k8s:deepcopy-gen=package
// +groupName=networking.cci.io
// +groupGoName=NetworkingCCI
package v1beta1

View File

@ -1,51 +0,0 @@
/*
Copyright 2015 The Kubernetes Authors.
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.
*/
package v1beta1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
// GroupName is the group name use in this package
const GroupName = "networking.cci.io"
// SchemeGroupVersion is group version used to register these objects
var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1beta1"}
// Resource takes an unqualified resource and returns a Group qualified GroupResource
func Resource(resource string) schema.GroupResource {
return SchemeGroupVersion.WithResource(resource).GroupResource()
}
var (
// localSchemeBuilder and AddToScheme will stay in k8s.io/kubernetes.
SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes)
localSchemeBuilder = &SchemeBuilder
AddToScheme = localSchemeBuilder.AddToScheme
)
// Adds the list of known types to the given scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&Network{},
&NetworkList{},
)
// Add the watch version that applies
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}

View File

@ -1,87 +0,0 @@
/*
Copyright (c) 2017 OpenStack Foundation.
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.
*/
package v1beta1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// NetworkList is a list of network resource in container.
type NetworkList struct {
metav1.TypeMeta `json:",inline"`
// Standard list metadata.
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
// +optional
metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
Items []Network `json:"items" protobuf:"bytes,2,rep,name=items"`
}
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// Network is a network resource in container.
type Network struct {
metav1.TypeMeta `json:",inline"`
// +optional
metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
// Spec defines the attributes on a network
// +optional
Spec NetworkSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`
// Status describes the network status
// +optional
Status NetworkStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}
// NetworkSpec describes the attributes on a network resource.
type NetworkSpec struct {
// network type
NetworkType string `json:"networkType,omitempty" protobuf:"bytes,5,opt,name=networkType"`
// ID of the VPC to attach
AttachedVPC string `json:"attachedVPC,omitempty" protobuf:"bytes,4,opt,name=attachedVPC"`
// network ID
NetworkID string `json:"networkID,omitempty" protobuf:"bytes,7,opt,name=networkID"`
// Subnet ID
SubnetID string `json:"subnetID,omitempty" protobuf:"bytes,8,opt,name=subnetID"`
// available zone
AvailableZone string `json:"availableZone,omitempty" protobuf:"bytes,9,opt,name=availableZone"`
// The CIDR of the network
CIDR string `json:"cidr,omitempty" protobuf:"bytes,3,opt,name=cidr"`
}
// NetworkStatus describes the status of a network
type NetworkStatus struct {
// State describes the network state
// +optional
State string `json:"state" protobuf:"bytes,1,opt,name=state"`
// Message describes why network is in current state
// +optional
Message string `json:"message,omitempty" protobuf:"bytes,2,opt,name=message"`
}
const (
// NetworkInitializing means the network is initializing
NetworkInitializing = "Initializing"
// NetworkPending means the network is processing
NetworkPending = "Pending"
// NetworkActive means the network is available
NetworkActive = "Active"
// NetworkFailed means the network is not available
NetworkFailed = "Failed"
// NetworkTerminating means the network is undergoing graceful termination
NetworkTerminating = "Terminating"
)

View File

@ -1,119 +0,0 @@
//go:build !ignore_autogenerated
// +build !ignore_autogenerated
/*
Copyright The Kubernetes Authors.
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 deepcopy-gen. DO NOT EDIT.
package v1beta1
import (
runtime "k8s.io/apimachinery/pkg/runtime"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Network) DeepCopyInto(out *Network) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
out.Spec = in.Spec
out.Status = in.Status
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Network.
func (in *Network) DeepCopy() *Network {
if in == nil {
return nil
}
out := new(Network)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *Network) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *NetworkList) DeepCopyInto(out *NetworkList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]Network, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NetworkList.
func (in *NetworkList) DeepCopy() *NetworkList {
if in == nil {
return nil
}
out := new(NetworkList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *NetworkList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *NetworkSpec) DeepCopyInto(out *NetworkSpec) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NetworkSpec.
func (in *NetworkSpec) DeepCopy() *NetworkSpec {
if in == nil {
return nil
}
out := new(NetworkSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *NetworkStatus) DeepCopyInto(out *NetworkStatus) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NetworkStatus.
func (in *NetworkStatus) DeepCopy() *NetworkStatus {
if in == nil {
return nil
}
out := new(NetworkStatus)
in.DeepCopyInto(out)
return out
}

View File

@ -1,91 +0,0 @@
package aksk
import (
"fmt"
"gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/common/auth/aksk"
"gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/common/config"
clientset "gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/huawei/pkg/client/networking.cci.io/v1beta1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/clientcmd/api"
)
const (
apiVersion = "client.authentication.k8s.io/v1beta1"
// 云容器实例 CCI参考https://developer.huaweicloud.com/endpoint
//cciEndpoint = "https://cci.cn-north-4.myhuaweicloud.com"
// 统一身份认证服务 IAM参考https://developer.huaweicloud.com/endpoint
iamEndpoint = "https://iam.myhuaweicloud.com"
// 地区和终端节点参考https://developer.huaweicloud.com/endpoint
//projectName = "cn-north-4"
// 获取AK/SK参考: https://support.huaweicloud.com/devg-cci/cci_kubectl_01.html#cci_kubectl_01__section17023744719
//ak = "ATQTIWUT9K66VRMMXKVY"
//sk = "Wa0aixDVuhZOfDZGWvgIJQBHnyiDlGdgDn1Ai5Yy"
DomainId = "0a4e7f245680f3040fdfc011720e50a0" //账号ID可以在我的凭证获取
ProjectId = "0a62ffb0d48026c12fbfc011b8d23f0b" //项目ID可以在我的凭证获取
SecurityGroupID = "5157f1d1-fe7d-47a1-beaf-aee027b99755" //安全组ID可以在安全组控制台获取
AvailableZone = "cn-north-4a" //az名称例如cn-north-1a、cn-north-4a或cn-east-3a
VpcID = "0333b519-7903-49e8-908e-ed56216fe921" //虚拟私有云的ID可在VPC控制台获取
Cidr = "10.0.0.0/10" //子网网段例如192.168.128.0/18
NetworkID = "2a14ac3f-07f7-4479-9930-3ea06a888f54" //<子网的网络ID可在VPC控制台 > 子网中获取>
SubnetID = "0dea26d7-2544-424c-b7aa-620b206fce35" //<子网ID可在VPC控制台 > 子网获取>
)
// NewClient 通过AK/SK认证创建Clientset
func NewClient(cloudStack string, akskPath string, configPath string) (*kubernetes.Clientset, error) {
configAksk, _ := aksk.AkskConfig(cloudStack, akskPath)
configCommon, _ := config.PCMconfig(configPath)
ak := configAksk.AccessKey
sk := configAksk.SecretKey
regionId := configCommon.RegionId
cciEndpoint := "https://cci." + regionId + ".myhuaweicloud.com"
cciConfig, err := clientcmd.BuildConfigFromFlags(cciEndpoint, "")
if err != nil {
return nil, err
}
var optionArgs []string
optionArgs = append(optionArgs, fmt.Sprintf("--iam-endpoint=%s", iamEndpoint))
optionArgs = append(optionArgs, fmt.Sprintf("--project-name=%s", regionId))
optionArgs = append(optionArgs, fmt.Sprintf("--ak=%s", ak))
optionArgs = append(optionArgs, fmt.Sprintf("--sk=%s", sk))
cciConfig.ExecProvider = &api.ExecConfig{
Command: "cci-iam-authenticator",
APIVersion: apiVersion,
Args: append([]string{"token"}, optionArgs...),
Env: make([]api.ExecEnvVar, 0),
}
return kubernetes.NewForConfig(cciConfig)
}
func NewNetworkClient(cloudStack string, akskPath string, configPath string) (*clientset.Clientset, error) {
configAksk, _ := aksk.AkskConfig(cloudStack, akskPath)
configCommon, _ := config.PCMconfig(configPath)
ak := configAksk.AccessKey
sk := configAksk.SecretKey
regionId := configCommon.RegionId
cciEndpoint := "https://cci." + regionId + ".myhuaweicloud.com"
configFromFlags, err := clientcmd.BuildConfigFromFlags(cciEndpoint, "")
if err != nil {
return nil, err
}
var optionArgs []string
optionArgs = append(optionArgs, fmt.Sprintf("--iam-endpoint=%s", iamEndpoint))
optionArgs = append(optionArgs, fmt.Sprintf("--project-name=%s", regionId))
optionArgs = append(optionArgs, fmt.Sprintf("--ak=%s", ak))
optionArgs = append(optionArgs, fmt.Sprintf("--sk=%s", sk))
configFromFlags.ExecProvider = &api.ExecConfig{
Command: "cci-iam-authenticator",
APIVersion: apiVersion,
Args: append([]string{"token"}, optionArgs...),
Env: make([]api.ExecEnvVar, 0),
}
return clientset.NewForConfig(configFromFlags)
}

View File

@ -1,16 +0,0 @@
package kubeconfig
import (
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
// NewClient 通过kubeconfig配置文件创建Clientset
// kubeconfig配置文件需包含认证相关信息具体请参考《cci-iam-authenticator使用参考》生成kubeconfig配置文件https://support.huaweicloud.com/devg-cci/cci_kubectl_03.html
func NewClient() (*kubernetes.Clientset, error) {
config, err := clientcmd.BuildConfigFromFlags("", "/path/to/kubeconfig")
if err != nil {
return nil, err
}
return kubernetes.NewForConfig(config)
}

View File

@ -1,45 +0,0 @@
package password
import (
"fmt"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/clientcmd/api"
)
const (
apiVersion = "client.authentication.k8s.io/v1beta1"
// 云容器实例 CCI参考https://developer.huaweicloud.com/endpoint
cciEndpoint = "<例如华北-北京四: https://cci.cn-north-4.myhuaweicloud.com>"
// 统一身份认证服务 IAM参考https://developer.huaweicloud.com/endpoint
iamEndpoint = "<例如华北-北京四: https://iam.cn-north-4.myhuaweicloud.com>"
// 地区和终端节点参考https://developer.huaweicloud.com/endpoint
projectName = "<例如华北-北京四: cn-north-4>"
userName = "<Your Account User Name>"
domainName = "<Your Account Domain Name>"
password = "<Your Account Password>"
)
// NewClient 通过username/password创建Clientset
func NewClient() (*kubernetes.Clientset, error) {
config, err := clientcmd.BuildConfigFromFlags(cciEndpoint, "")
if err != nil {
return nil, err
}
var optionArgs []string
optionArgs = append(optionArgs, fmt.Sprintf("--iam-endpoint=%s", iamEndpoint))
optionArgs = append(optionArgs, fmt.Sprintf("--project-name=%s", projectName))
optionArgs = append(optionArgs, fmt.Sprintf("--token-only=false"))
optionArgs = append(optionArgs, fmt.Sprintf("--domain-name=%s", domainName))
optionArgs = append(optionArgs, fmt.Sprintf("--user-name=%s", userName))
optionArgs = append(optionArgs, fmt.Sprintf("--password=%s", password))
config.ExecProvider = &api.ExecConfig{
Command: "cci-iam-authenticator",
APIVersion: apiVersion,
Args: append([]string{"token"}, optionArgs...),
Env: make([]api.ExecEnvVar, 0),
}
return kubernetes.NewForConfig(config)
}

View File

@ -1,90 +0,0 @@
/*
Copyright The Kubernetes Authors.
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 client-gen. DO NOT EDIT.
package v1beta1
import (
networkingcciv1beta1 "gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/huawei/pkg/client/networking.cci.io/v1beta1/typed/networking.cci.io/v1beta1"
discovery "k8s.io/client-go/discovery"
rest "k8s.io/client-go/rest"
flowcontrol "k8s.io/client-go/util/flowcontrol"
)
type Interface interface {
Discovery() discovery.DiscoveryInterface
NetworkingCCIV1beta1() networkingcciv1beta1.NetworkingCCIV1beta1Interface
}
// Clientset contains the clients for groups. Each group has exactly one
// version included in a Clientset.
type Clientset struct {
*discovery.DiscoveryClient
networkingCCIV1beta1 *networkingcciv1beta1.NetworkingCCIV1beta1Client
}
// NetworkingCCIV1beta1 retrieves the NetworkingCCIV1beta1Client
func (c *Clientset) NetworkingCCIV1beta1() networkingcciv1beta1.NetworkingCCIV1beta1Interface {
return c.networkingCCIV1beta1
}
// Discovery retrieves the DiscoveryClient
func (c *Clientset) Discovery() discovery.DiscoveryInterface {
if c == nil {
return nil
}
return c.DiscoveryClient
}
// NewForConfig creates a new Clientset for the given config.
func NewForConfig(c *rest.Config) (*Clientset, error) {
configShallowCopy := *c
if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 {
configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)
}
var cs Clientset
var err error
cs.networkingCCIV1beta1, err = networkingcciv1beta1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
return &cs, nil
}
// NewForConfigOrDie creates a new Clientset for the given config and
// panics if there is an error in the config.
func NewForConfigOrDie(c *rest.Config) *Clientset {
var cs Clientset
cs.networkingCCIV1beta1 = networkingcciv1beta1.NewForConfigOrDie(c)
cs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c)
return &cs
}
// New creates a new Clientset for the given RESTClient.
func New(c rest.Interface) *Clientset {
var cs Clientset
cs.networkingCCIV1beta1 = networkingcciv1beta1.New(c)
cs.DiscoveryClient = discovery.NewDiscoveryClient(c)
return &cs
}

View File

@ -1,20 +0,0 @@
/*
Copyright The Kubernetes Authors.
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 client-gen. DO NOT EDIT.
// This package has the automatically generated clientset.
package v1beta1

View File

@ -1,82 +0,0 @@
/*
Copyright The Kubernetes Authors.
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 client-gen. DO NOT EDIT.
package fake
import (
clientset "gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/huawei/pkg/client/networking.cci.io/v1beta1"
networkingcciv1beta1 "gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/huawei/pkg/client/networking.cci.io/v1beta1/typed/networking.cci.io/v1beta1"
fakenetworkingcciv1beta1 "gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/huawei/pkg/client/networking.cci.io/v1beta1/typed/networking.cci.io/v1beta1/fake"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/discovery"
fakediscovery "k8s.io/client-go/discovery/fake"
"k8s.io/client-go/testing"
)
// NewSimpleClientset returns a clientset that will respond with the provided objects.
// It's backed by a very simple object tracker that processes creates, updates and deletions as-is,
// without applying any validations and/or defaults. It shouldn't be considered a replacement
// for a real clientset and is mostly useful in simple unit tests.
func NewSimpleClientset(objects ...runtime.Object) *Clientset {
o := testing.NewObjectTracker(scheme, codecs.UniversalDecoder())
for _, obj := range objects {
if err := o.Add(obj); err != nil {
panic(err)
}
}
cs := &Clientset{tracker: o}
cs.discovery = &fakediscovery.FakeDiscovery{Fake: &cs.Fake}
cs.AddReactor("*", "*", testing.ObjectReaction(o))
cs.AddWatchReactor("*", func(action testing.Action) (handled bool, ret watch.Interface, err error) {
gvr := action.GetResource()
ns := action.GetNamespace()
watch, err := o.Watch(gvr, ns)
if err != nil {
return false, nil, err
}
return true, watch, nil
})
return cs
}
// Clientset implements clientset.Interface. Meant to be embedded into a
// struct to get a default implementation. This makes faking out just the method
// you want to test easier.
type Clientset struct {
testing.Fake
discovery *fakediscovery.FakeDiscovery
tracker testing.ObjectTracker
}
func (c *Clientset) Discovery() discovery.DiscoveryInterface {
return c.discovery
}
func (c *Clientset) Tracker() testing.ObjectTracker {
return c.tracker
}
var _ clientset.Interface = &Clientset{}
// NetworkingCCIV1beta1 retrieves the NetworkingCCIV1beta1Client
func (c *Clientset) NetworkingCCIV1beta1() networkingcciv1beta1.NetworkingCCIV1beta1Interface {
return &fakenetworkingcciv1beta1.FakeNetworkingCCIV1beta1{Fake: &c.Fake}
}

View File

@ -1,20 +0,0 @@
/*
Copyright The Kubernetes Authors.
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 client-gen. DO NOT EDIT.
// This package has the automatically generated fake clientset.
package fake

View File

@ -1,56 +0,0 @@
/*
Copyright The Kubernetes Authors.
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 client-gen. DO NOT EDIT.
package fake
import (
networkingcciv1beta1 "gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/huawei/pkg/apis/networking.cci.io/v1beta1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
schema "k8s.io/apimachinery/pkg/runtime/schema"
serializer "k8s.io/apimachinery/pkg/runtime/serializer"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
)
var scheme = runtime.NewScheme()
var codecs = serializer.NewCodecFactory(scheme)
var parameterCodec = runtime.NewParameterCodec(scheme)
var localSchemeBuilder = runtime.SchemeBuilder{
networkingcciv1beta1.AddToScheme,
}
// AddToScheme adds all types of this clientset into the given scheme. This allows composition
// of clientsets, like in:
//
// import (
// "k8s.io/client-go/kubernetes"
// clientsetscheme "k8s.io/client-go/kubernetes/scheme"
// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme"
// )
//
// kclientset, _ := kubernetes.NewForConfig(c)
// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme)
//
// After this, RawExtensions in Kubernetes types will serialize kube-aggregator types
// correctly.
var AddToScheme = localSchemeBuilder.AddToScheme
func init() {
v1.AddToGroupVersion(scheme, schema.GroupVersion{Version: "v1"})
utilruntime.Must(AddToScheme(scheme))
}

View File

@ -1,20 +0,0 @@
/*
Copyright The Kubernetes Authors.
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 client-gen. DO NOT EDIT.
// This package contains the scheme of the automatically generated clientset.
package scheme

View File

@ -1,56 +0,0 @@
/*
Copyright The Kubernetes Authors.
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 client-gen. DO NOT EDIT.
package scheme
import (
networkingcciv1beta1 "gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/huawei/pkg/apis/networking.cci.io/v1beta1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
schema "k8s.io/apimachinery/pkg/runtime/schema"
serializer "k8s.io/apimachinery/pkg/runtime/serializer"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
)
var Scheme = runtime.NewScheme()
var Codecs = serializer.NewCodecFactory(Scheme)
var ParameterCodec = runtime.NewParameterCodec(Scheme)
var localSchemeBuilder = runtime.SchemeBuilder{
networkingcciv1beta1.AddToScheme,
}
// AddToScheme adds all types of this clientset into the given scheme. This allows composition
// of clientsets, like in:
//
// import (
// "k8s.io/client-go/kubernetes"
// clientsetscheme "k8s.io/client-go/kubernetes/scheme"
// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme"
// )
//
// kclientset, _ := kubernetes.NewForConfig(c)
// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme)
//
// After this, RawExtensions in Kubernetes types will serialize kube-aggregator types
// correctly.
var AddToScheme = localSchemeBuilder.AddToScheme
func init() {
v1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"})
utilruntime.Must(AddToScheme(Scheme))
}

View File

@ -1,20 +0,0 @@
/*
Copyright The Kubernetes Authors.
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 client-gen. DO NOT EDIT.
// This package has the automatically generated typed clients.
package v1beta1

View File

@ -1,20 +0,0 @@
/*
Copyright The Kubernetes Authors.
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 client-gen. DO NOT EDIT.
// Package fake has the automatically generated clients.
package fake

View File

@ -1,140 +0,0 @@
/*
Copyright The Kubernetes Authors.
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 client-gen. DO NOT EDIT.
package fake
import (
v1beta1 "gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/huawei/pkg/apis/networking.cci.io/v1beta1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
labels "k8s.io/apimachinery/pkg/labels"
schema "k8s.io/apimachinery/pkg/runtime/schema"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
testing "k8s.io/client-go/testing"
)
// FakeNetworks implements NetworkInterface
type FakeNetworks struct {
Fake *FakeNetworkingCCIV1beta1
ns string
}
var networksResource = schema.GroupVersionResource{Group: "networking.cci.io", Version: "v1beta1", Resource: "networks"}
var networksKind = schema.GroupVersionKind{Group: "networking.cci.io", Version: "v1beta1", Kind: "Network"}
// Get takes name of the network, and returns the corresponding network object, and an error if there is any.
func (c *FakeNetworks) Get(name string, options v1.GetOptions) (result *v1beta1.Network, err error) {
obj, err := c.Fake.
Invokes(testing.NewGetAction(networksResource, c.ns, name), &v1beta1.Network{})
if obj == nil {
return nil, err
}
return obj.(*v1beta1.Network), err
}
// List takes label and field selectors, and returns the list of Networks that match those selectors.
func (c *FakeNetworks) List(opts v1.ListOptions) (result *v1beta1.NetworkList, err error) {
obj, err := c.Fake.
Invokes(testing.NewListAction(networksResource, networksKind, c.ns, opts), &v1beta1.NetworkList{})
if obj == nil {
return nil, err
}
label, _, _ := testing.ExtractFromListOptions(opts)
if label == nil {
label = labels.Everything()
}
list := &v1beta1.NetworkList{ListMeta: obj.(*v1beta1.NetworkList).ListMeta}
for _, item := range obj.(*v1beta1.NetworkList).Items {
if label.Matches(labels.Set(item.Labels)) {
list.Items = append(list.Items, item)
}
}
return list, err
}
// Watch returns a watch.Interface that watches the requested networks.
func (c *FakeNetworks) Watch(opts v1.ListOptions) (watch.Interface, error) {
return c.Fake.
InvokesWatch(testing.NewWatchAction(networksResource, c.ns, opts))
}
// Create takes the representation of a network and creates it. Returns the server's representation of the network, and an error, if there is any.
func (c *FakeNetworks) Create(network *v1beta1.Network) (result *v1beta1.Network, err error) {
obj, err := c.Fake.
Invokes(testing.NewCreateAction(networksResource, c.ns, network), &v1beta1.Network{})
if obj == nil {
return nil, err
}
return obj.(*v1beta1.Network), err
}
// Update takes the representation of a network and updates it. Returns the server's representation of the network, and an error, if there is any.
func (c *FakeNetworks) Update(network *v1beta1.Network) (result *v1beta1.Network, err error) {
obj, err := c.Fake.
Invokes(testing.NewUpdateAction(networksResource, c.ns, network), &v1beta1.Network{})
if obj == nil {
return nil, err
}
return obj.(*v1beta1.Network), err
}
// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *FakeNetworks) UpdateStatus(network *v1beta1.Network) (*v1beta1.Network, error) {
obj, err := c.Fake.
Invokes(testing.NewUpdateSubresourceAction(networksResource, "status", c.ns, network), &v1beta1.Network{})
if obj == nil {
return nil, err
}
return obj.(*v1beta1.Network), err
}
// Delete takes name of the network and deletes it. Returns an error if one occurs.
func (c *FakeNetworks) Delete(name string, options *v1.DeleteOptions) error {
_, err := c.Fake.
Invokes(testing.NewDeleteAction(networksResource, c.ns, name), &v1beta1.Network{})
return err
}
// DeleteCollection deletes a collection of objects.
func (c *FakeNetworks) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
action := testing.NewDeleteCollectionAction(networksResource, c.ns, listOptions)
_, err := c.Fake.Invokes(action, &v1beta1.NetworkList{})
return err
}
// Patch applies the patch and returns the patched network.
func (c *FakeNetworks) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta1.Network, err error) {
obj, err := c.Fake.
Invokes(testing.NewPatchSubresourceAction(networksResource, c.ns, name, pt, data, subresources...), &v1beta1.Network{})
if obj == nil {
return nil, err
}
return obj.(*v1beta1.Network), err
}

View File

@ -1,40 +0,0 @@
/*
Copyright The Kubernetes Authors.
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 client-gen. DO NOT EDIT.
package fake
import (
v1beta1 "gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/huawei/pkg/client/networking.cci.io/v1beta1/typed/networking.cci.io/v1beta1"
rest "k8s.io/client-go/rest"
testing "k8s.io/client-go/testing"
)
type FakeNetworkingCCIV1beta1 struct {
*testing.Fake
}
func (c *FakeNetworkingCCIV1beta1) Networks(namespace string) v1beta1.NetworkInterface {
return &FakeNetworks{c, namespace}
}
// RESTClient returns a RESTClient that is used to communicate
// with API server by this client implementation.
func (c *FakeNetworkingCCIV1beta1) RESTClient() rest.Interface {
var ret *rest.RESTClient
return ret
}

View File

@ -1,21 +0,0 @@
/*
Copyright The Kubernetes Authors.
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 client-gen. DO NOT EDIT.
package v1beta1
type NetworkExpansion interface{}

View File

@ -1,191 +0,0 @@
/*
Copyright The Kubernetes Authors.
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 client-gen. DO NOT EDIT.
package v1beta1
import (
"time"
v1beta1 "gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/huawei/pkg/apis/networking.cci.io/v1beta1"
scheme "gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/huawei/pkg/client/networking.cci.io/v1beta1/scheme"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
rest "k8s.io/client-go/rest"
)
// NetworksGetter has a method to return a NetworkInterface.
// A group's client should implement this interface.
type NetworksGetter interface {
Networks(namespace string) NetworkInterface
}
// NetworkInterface has methods to work with Network resources.
type NetworkInterface interface {
Create(*v1beta1.Network) (*v1beta1.Network, error)
Update(*v1beta1.Network) (*v1beta1.Network, error)
UpdateStatus(*v1beta1.Network) (*v1beta1.Network, error)
Delete(name string, options *v1.DeleteOptions) error
DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error
Get(name string, options v1.GetOptions) (*v1beta1.Network, error)
List(opts v1.ListOptions) (*v1beta1.NetworkList, error)
Watch(opts v1.ListOptions) (watch.Interface, error)
Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta1.Network, err error)
NetworkExpansion
}
// networks implements NetworkInterface
type networks struct {
client rest.Interface
ns string
}
// newNetworks returns a Networks
func newNetworks(c *NetworkingCCIV1beta1Client, namespace string) *networks {
return &networks{
client: c.RESTClient(),
ns: namespace,
}
}
// Get takes name of the network, and returns the corresponding network object, and an error if there is any.
func (c *networks) Get(name string, options v1.GetOptions) (result *v1beta1.Network, err error) {
result = &v1beta1.Network{}
err = c.client.Get().
Namespace(c.ns).
Resource("networks").
Name(name).
VersionedParams(&options, scheme.ParameterCodec).
Do().
Into(result)
return
}
// List takes label and field selectors, and returns the list of Networks that match those selectors.
func (c *networks) List(opts v1.ListOptions) (result *v1beta1.NetworkList, err error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
result = &v1beta1.NetworkList{}
err = c.client.Get().
Namespace(c.ns).
Resource("networks").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Do().
Into(result)
return
}
// Watch returns a watch.Interface that watches the requested networks.
func (c *networks) Watch(opts v1.ListOptions) (watch.Interface, error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
opts.Watch = true
return c.client.Get().
Namespace(c.ns).
Resource("networks").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Watch()
}
// Create takes the representation of a network and creates it. Returns the server's representation of the network, and an error, if there is any.
func (c *networks) Create(network *v1beta1.Network) (result *v1beta1.Network, err error) {
result = &v1beta1.Network{}
err = c.client.Post().
Namespace(c.ns).
Resource("networks").
Body(network).
Do().
Into(result)
return
}
// Update takes the representation of a network and updates it. Returns the server's representation of the network, and an error, if there is any.
func (c *networks) Update(network *v1beta1.Network) (result *v1beta1.Network, err error) {
result = &v1beta1.Network{}
err = c.client.Put().
Namespace(c.ns).
Resource("networks").
Name(network.Name).
Body(network).
Do().
Into(result)
return
}
// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *networks) UpdateStatus(network *v1beta1.Network) (result *v1beta1.Network, err error) {
result = &v1beta1.Network{}
err = c.client.Put().
Namespace(c.ns).
Resource("networks").
Name(network.Name).
SubResource("status").
Body(network).
Do().
Into(result)
return
}
// Delete takes name of the network and deletes it. Returns an error if one occurs.
func (c *networks) Delete(name string, options *v1.DeleteOptions) error {
return c.client.Delete().
Namespace(c.ns).
Resource("networks").
Name(name).
Body(options).
Do().
Error()
}
// DeleteCollection deletes a collection of objects.
func (c *networks) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
var timeout time.Duration
if listOptions.TimeoutSeconds != nil {
timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second
}
return c.client.Delete().
Namespace(c.ns).
Resource("networks").
VersionedParams(&listOptions, scheme.ParameterCodec).
Timeout(timeout).
Body(options).
Do().
Error()
}
// Patch applies the patch and returns the patched network.
func (c *networks) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta1.Network, err error) {
result = &v1beta1.Network{}
err = c.client.Patch(pt).
Namespace(c.ns).
Resource("networks").
SubResource(subresources...).
Name(name).
Body(data).
Do().
Into(result)
return
}

View File

@ -1,89 +0,0 @@
/*
Copyright The Kubernetes Authors.
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 client-gen. DO NOT EDIT.
package v1beta1
import (
v1beta1 "gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/huawei/pkg/apis/networking.cci.io/v1beta1"
"gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/huawei/pkg/client/networking.cci.io/v1beta1/scheme"
rest "k8s.io/client-go/rest"
)
type NetworkingCCIV1beta1Interface interface {
RESTClient() rest.Interface
NetworksGetter
}
// NetworkingCCIV1beta1Client is used to interact with features provided by the networking.cci.io group.
type NetworkingCCIV1beta1Client struct {
restClient rest.Interface
}
func (c *NetworkingCCIV1beta1Client) Networks(namespace string) NetworkInterface {
return newNetworks(c, namespace)
}
// NewForConfig creates a new NetworkingCCIV1beta1Client for the given config.
func NewForConfig(c *rest.Config) (*NetworkingCCIV1beta1Client, error) {
config := *c
if err := setConfigDefaults(&config); err != nil {
return nil, err
}
client, err := rest.RESTClientFor(&config)
if err != nil {
return nil, err
}
return &NetworkingCCIV1beta1Client{client}, nil
}
// NewForConfigOrDie creates a new NetworkingCCIV1beta1Client for the given config and
// panics if there is an error in the config.
func NewForConfigOrDie(c *rest.Config) *NetworkingCCIV1beta1Client {
client, err := NewForConfig(c)
if err != nil {
panic(err)
}
return client
}
// New creates a new NetworkingCCIV1beta1Client for the given RESTClient.
func New(c rest.Interface) *NetworkingCCIV1beta1Client {
return &NetworkingCCIV1beta1Client{c}
}
func setConfigDefaults(config *rest.Config) error {
gv := v1beta1.SchemeGroupVersion
config.GroupVersion = &gv
config.APIPath = "/apis"
config.NegotiatedSerializer = scheme.Codecs.WithoutConversion()
if config.UserAgent == "" {
config.UserAgent = rest.DefaultKubernetesUserAgent()
}
return nil
}
// RESTClient returns a RESTClient that is used to communicate
// with API server by this client implementation.
func (c *NetworkingCCIV1beta1Client) RESTClient() rest.Interface {
if c == nil {
return nil
}
return c.restClient
}

View File

@ -1,77 +0,0 @@
package deployment
import (
v1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
const (
app = "test-k8s-client-deployment"
namespace = "test-k8s-client-namespace1"
)
// CreateDeployment 创建Deployment
// API参考https://support.huaweicloud.com/api-cci/createAppsV1NamespacedDeployment.html
func CreateDeployment(client *kubernetes.Clientset) (*v1.Deployment, error) {
var replicas int32 = 2
var priority int32 = 0
container := corev1.Container{
Name: "container-0",
Image: "library/nginx:stable-alpine-perl",
Resources: corev1.ResourceRequirements{
Requests: map[corev1.ResourceName]resource.Quantity{
corev1.ResourceCPU: resource.MustParse("500m"),
corev1.ResourceMemory: resource.MustParse("1024Mi"),
},
Limits: map[corev1.ResourceName]resource.Quantity{
corev1.ResourceCPU: resource.MustParse("500m"),
corev1.ResourceMemory: resource.MustParse("1024Mi"),
},
},
}
podTemplate := corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"app": app}},
Spec: corev1.PodSpec{
Priority: &priority,
ImagePullSecrets: []corev1.LocalObjectReference{{Name: "imagepull-secret"}},
Containers: []corev1.Container{container},
},
}
deployment := v1.Deployment{
TypeMeta: metav1.TypeMeta{
APIVersion: "apps/v1",
Kind: "Deployment",
},
ObjectMeta: metav1.ObjectMeta{
Name: app,
},
Spec: v1.DeploymentSpec{
Replicas: &replicas,
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"app": app,
},
},
Template: podTemplate,
},
}
return client.AppsV1().Deployments(namespace).Create(&deployment)
}
// DeleteDeployment 删除Deployment
// API参考https://support.huaweicloud.com/api-cci/deleteAppsV1NamespacedDeployment.html
func DeleteDeployment(client *kubernetes.Clientset) error {
return client.AppsV1().Deployments(namespace).Delete(app, &metav1.DeleteOptions{})
}
// GetDeployment 查询Deployment
// API参考https://support.huaweicloud.com/api-cci/readAppsV1NamespacedDeployment.html
func GetDeployment(client *kubernetes.Clientset) (*v1.Deployment, error) {
return client.AppsV1().Deployments(namespace).Get(app, metav1.GetOptions{})
}

View File

@ -1,54 +0,0 @@
package namespace
import (
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
)
const (
namespace = "test-k8s-client-namespace1"
)
// CreateNamespace 创建命名空间
// API参考https://support.huaweicloud.com/api-cci/createCoreV1Namespace.html
func CreateNamespace(cs *kubernetes.Clientset) (*corev1.Namespace, error) {
namespace := &corev1.Namespace{
TypeMeta: metav1.TypeMeta{},
ObjectMeta: metav1.ObjectMeta{
Name: namespace,
Annotations: map[string]string{
"namespace.kubernetes.io/flavor": "general-computing",
"network.cci.io/warm-pool-size": "10",
},
Labels: map[string]string{
"rbac.authorization.cci.io/enable-k8s-rbac": "false",
},
},
}
return cs.CoreV1().Namespaces().Create(namespace)
}
// DeleteNamespace 删除Namespace
// API参考https://support.huaweicloud.com/api-cci/deleteCoreV1Namespace.html
func DeleteNamespace(cs *kubernetes.Clientset) error {
return cs.CoreV1().Namespaces().Delete(namespace, &metav1.DeleteOptions{})
}
// WaitNamespaceActive 查询Namespace状态等待其状态变为"Active"
// API参考https://support.huaweicloud.com/api-cci/readCoreV1Namespace.html
func WaitNamespaceActive(cs *kubernetes.Clientset) error {
return wait.Poll(time.Second*5, time.Second*30, func() (done bool, err error) {
ns, err := cs.CoreV1().Namespaces().Get(namespace, metav1.GetOptions{})
if err != nil {
return false, err
}
if ns.Status.Phase == corev1.NamespaceActive {
return true, nil
}
return false, nil
})
}

View File

@ -1,58 +0,0 @@
package network
import (
"gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/huawei/pkg/apis/networking.cci.io/v1beta1"
"gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/huawei/pkg/auth/aksk"
"time"
clientset "gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/huawei/pkg/client/networking.cci.io/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
)
const (
name = "test-k8s-client-namespace-cn-north-1-default-network"
namespace = "test-k8s-client-namespace1"
)
// CreateNetwork 创建Network并等待其状态变更为Active
// 参考《Namespace和Network》 https://support.huaweicloud.com/devg-cci/cci_05_0023.html
// API参考https://support.huaweicloud.com/api-cci/createNetworkingCciIoV1beta1NamespacedNetwork.html
func CreateNetwork(cs *clientset.Clientset) (*v1beta1.Network, error) {
network := &v1beta1.Network{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
"network.alpha.kubernetes.io/default-security-group": aksk.SecurityGroupID,
"network.alpha.kubernetes.io/domain-id": aksk.DomainId,
"network.alpha.kubernetes.io/project-id": aksk.ProjectId,
},
Name: name,
},
Spec: v1beta1.NetworkSpec{
AvailableZone: aksk.AvailableZone,
CIDR: aksk.Cidr,
AttachedVPC: aksk.VpcID,
NetworkID: aksk.NetworkID,
NetworkType: "underlay_neutron",
SubnetID: aksk.SubnetID,
},
}
network, err := cs.NetworkingCCIV1beta1().Networks(namespace).Create(network)
if err != nil {
return nil, err
}
// 查询Network状态等待其状态变为"Active"
err = wait.Poll(time.Second*5, time.Second*30, func() (done bool, err error) {
network, err = cs.NetworkingCCIV1beta1().Networks(namespace).Get(name, metav1.GetOptions{})
if err != nil {
return false, err
}
if network.Status.State == v1beta1.NetworkActive {
return true, nil
}
return false, nil
})
return network, err
}

View File

@ -1,134 +0,0 @@
package pod
import (
"fmt"
"gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/common/config"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
// CreatePod 创建Pod
func CreatePod(client *kubernetes.Clientset, configPath string) (*corev1.Pod, error) {
var configCommon config.PCMContainerConfig
configCommon, _ = config.PCMconfig(configPath)
nameSpace := configCommon.NameSpace
podName := configCommon.ContainerGroupName
containerImage := configCommon.ContainerImage
containerName := configCommon.ContainerName
cpuPod := configCommon.CpuPod
memoryPod := configCommon.MemoryPod
pod := corev1.Pod{
TypeMeta: metav1.TypeMeta{
APIVersion: "core/V1",
Kind: "Pod",
},
ObjectMeta: metav1.ObjectMeta{
Name: podName,
Namespace: nameSpace,
Labels: map[string]string{"name": "testapi"},
},
Spec: corev1.PodSpec{
RestartPolicy: corev1.RestartPolicyAlways,
Containers: []corev1.Container{
{
Name: containerName,
Image: containerImage,
Resources: corev1.ResourceRequirements{
Limits: map[corev1.ResourceName]resource.Quantity{
corev1.ResourceCPU: resource.MustParse(cpuPod),
corev1.ResourceMemory: resource.MustParse(memoryPod),
},
},
},
},
},
Status: corev1.PodStatus{},
}
fmt.Println("Huawei ContainerGroup created")
return client.CoreV1().Pods(nameSpace).Create(&pod)
}
// ListPod 查询Namespace下Pod列表
func ListPod(client *kubernetes.Clientset, configPath string) (*corev1.PodList, error) {
var configCommon config.PCMContainerConfig
configCommon, _ = config.PCMconfig(configPath)
nameSpace := configCommon.NameSpace
podList, _ := client.CoreV1().Pods(nameSpace).List(metav1.ListOptions{})
fmt.Println("Huawei ContainerGroup list", podList)
return podList, nil
}
// UpdatePod 更新指定Pod
/*
// 跨namespace目前有点问题
*/
func UpdatePod(client *kubernetes.Clientset, configPath string) (*corev1.Pod, error) {
var configCommon config.PCMContainerConfig
configCommon, _ = config.PCMconfig(configPath)
nameSpace := configCommon.NamespaceUpdate
podName := configCommon.ContainerGroupNameUpdate
containerImage := configCommon.ContainerImageUpdate
containerName := configCommon.ContainerNameUpdate
pod := corev1.Pod{
TypeMeta: metav1.TypeMeta{
APIVersion: "core/V1",
Kind: "Pod",
},
ObjectMeta: metav1.ObjectMeta{
Name: podName,
Namespace: nameSpace,
Labels: map[string]string{"name": "pod-test2"},
},
Spec: corev1.PodSpec{
RestartPolicy: corev1.RestartPolicyAlways,
Containers: []corev1.Container{
{
Name: containerName,
Image: containerImage,
Resources: corev1.ResourceRequirements{
Limits: map[corev1.ResourceName]resource.Quantity{
corev1.ResourceLimitsCPU: resource.MustParse("500m"),
corev1.ResourceLimitsMemory: resource.MustParse("1Gi"),
},
Requests: map[corev1.ResourceName]resource.Quantity{
corev1.ResourceRequestsCPU: resource.MustParse("500m"),
corev1.ResourceRequestsMemory: resource.MustParse("1Gi"),
},
},
},
},
},
Status: corev1.PodStatus{},
}
podNew, _ := client.CoreV1().Pods(nameSpace).Update(&pod)
fmt.Println("Huawei ContainerGroup updated", podNew)
return podNew, nil
}
// DeletePod 删除指定Pod
func DeletePod(client *kubernetes.Clientset, configPath string) error {
var configCommon config.PCMContainerConfig
configCommon, _ = config.PCMconfig(configPath)
nameSpace := configCommon.NameSpace
podName := configCommon.ContainerGroupName
fmt.Println("Huawei ContainerGroup:", podName, " Deleted")
return client.CoreV1().Pods(nameSpace).Delete(podName, &metav1.DeleteOptions{})
}

View File

@ -1,34 +0,0 @@
[pod_create_conf]
#区域ID
region_id=ap-beijing
#容器实例名称(pod名) 对应腾讯EksCiName(腾讯必需)
container_group_name=pcm-test-tencent-pod
#镜像地址 对应腾讯 Container.Image(腾讯必需)
container_image=library/nginx:stable-alpine-perl
#容器名称 对应腾讯 Container.Name(腾讯必需)
container_name=pcm-test-tencent-container
#Pod拥有核数 对应腾讯 Cpu(腾讯必需)
cpu_pod=1
#Pod拥有内存大小 对应腾讯 Memory(腾讯必需)
memory_pod=2
#安全组ID 对应腾讯 SecurityGroupIds(腾讯必需)
security_group_id=sg-owzbdinl
#子网ID 对应腾讯 SubnetId(腾讯必需)
subnet_id=subnet-n4h73049
#VPC ID 对应腾讯 VpcId(腾讯必需)
vpc_id=vpc-e8hdbla8
[pod_list_conf]
#区域ID
region_id=ap-beijing
[pod_update_conf]
#区域ID
region_id=ap-beijing
#容器实例ID 对应腾讯EksCiName(腾讯必需)
container_group_id=eksci-pawu7qad
#容器实例名称(pod名) 对应腾讯EksCiName(腾讯必需)
container_group_name=eksci-pawu7qad
[pod_delete_conf]
container_group_id=eksci-pawu7qad

View File

@ -1,138 +0,0 @@
package eks
import (
"fmt"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
tke "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/tke/v20180525"
"gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/common/auth/aksk"
pcmCommon "gitlink.org.cn/JCCE/PCM/adaptor/container_api_adaptor/common/config"
)
func CreateEksInstance(cloudStack string, akskPath string, configPath string) {
configCommon, _ := pcmCommon.PCMconfig(configPath)
configAksk, _ := aksk.AkskConfig(cloudStack, akskPath)
credential := common.NewCredential(
configAksk.AccessKey,
configAksk.SecretKey,
)
cpf := profile.NewClientProfile()
cpf.HttpProfile.Endpoint = "tke.tencentcloudapi.com"
client, _ := tke.NewClient(credential, configCommon.RegionId, cpf)
request := tke.NewCreateEKSContainerInstancesRequest()
eksCiName := &configCommon.ContainerGroupName
containerName := &configCommon.ContainerName
containerImage := &configCommon.ContainerImage
eksCpu := &configCommon.CpuPodFloat
eksMemory := &configCommon.MemoryPodFloat
securityGroupId := &configCommon.SecurityGroupId
securityGroupIds := make([]*string, 1)
securityGroupIds[0] = securityGroupId
subNetId := &configCommon.SubnetId
vpcId := &configCommon.VpcId
request.EksCiName = eksCiName
container := make([]*tke.Container, 1)
container[0] = new(tke.Container)
container[0].Name = containerName
container[0].Image = containerImage
//container[0].Cpu = containerCpuPt
//container[0].Memory = containerMemoryPt
request.Containers = container
request.Cpu = eksCpu
request.Memory = eksMemory
request.SecurityGroupIds = securityGroupIds
request.SubnetId = subNetId
request.VpcId = vpcId
response, err := client.CreateEKSContainerInstances(request)
if _, ok := err.(*errors.TencentCloudSDKError); ok {
fmt.Printf("An API error has returned: %s", err)
return
}
if err != nil {
panic(err)
}
fmt.Printf("%s", response.ToJsonString())
}
func ListEksInstance(cloudStack string, akskPath string, configPath string) {
configCommon, _ := pcmCommon.PCMconfig(configPath)
configAksk, _ := aksk.AkskConfig(cloudStack, akskPath)
credential := common.NewCredential(configAksk.AccessKey, configAksk.SecretKey)
cpf := profile.NewClientProfile()
cpf.HttpProfile.Endpoint = "tke.tencentcloudapi.com"
client, _ := tke.NewClient(credential, configCommon.RegionId, cpf)
request := tke.NewDescribeEKSContainerInstancesRequest()
response, err := client.DescribeEKSContainerInstances(request)
if _, ok := err.(*errors.TencentCloudSDKError); ok {
fmt.Printf("An API error has returned: %s", err)
return
}
if err != nil {
panic(err)
}
fmt.Printf("%s", response.ToJsonString())
}
func UpdateEksInstance(cloudStack string, akskPath string, configPath string) {
configCommon, _ := pcmCommon.PCMconfig(configPath)
configAksk, _ := aksk.AkskConfig(cloudStack, akskPath)
credential := common.NewCredential(configAksk.AccessKey, configAksk.SecretKey)
cpf := profile.NewClientProfile()
cpf.HttpProfile.Endpoint = "tke.tencentcloudapi.com"
client, _ := tke.NewClient(credential, configCommon.RegionId, cpf)
request := tke.NewUpdateEKSContainerInstanceRequest()
request.EksCiId = &configCommon.ContainerGroupIdUpdate
request.Name = &configCommon.ContainerGroupNameUpdate
response, err := client.UpdateEKSContainerInstance(request)
if _, ok := err.(*errors.TencentCloudSDKError); ok {
fmt.Printf("An API error has returned: %s", err)
return
}
if err != nil {
panic(err)
}
fmt.Printf("%s", response.ToJsonString())
}
func DeleteEksInstance(cloudStack string, akskPath string, configPath string) {
configCommon, _ := pcmCommon.PCMconfig(configPath)
configAksk, _ := aksk.AkskConfig(cloudStack, akskPath)
credential := common.NewCredential(configAksk.AccessKey, configAksk.SecretKey)
cpf := profile.NewClientProfile()
cpf.HttpProfile.Endpoint = "tke.tencentcloudapi.com"
client, _ := tke.NewClient(credential, configCommon.RegionId, cpf)
request := tke.NewDeleteEKSContainerInstancesRequest()
eksCiIds := make([]*string, 1)
eksCiIds[0] = &configCommon.ContainerGroupIdDelete
request.EksCiIds = eksCiIds
response, err := client.DeleteEKSContainerInstances(request)
if _, ok := err.(*errors.TencentCloudSDKError); ok {
fmt.Printf("An API error has returned: %s", err)
return
}
if err != nil {
panic(err)
}
fmt.Printf("%s", response.ToJsonString())
}

View File

@ -0,0 +1,203 @@
package poder
import (
"context"
"gitlink.org.cn/JCCE/PCM/common/tenanter"
"gitlink.org.cn/JCCE/PCM/lan_trans/idl/pbpod"
"gitlink.org.cn/JCCE/PCM/lan_trans/idl/pbtenant"
"sync"
alieci "github.com/aliyun/alibaba-cloud-sdk-go/services/eci"
"github.com/pkg/errors"
)
var aliClientMutex sync.Mutex
type AliEci struct {
cli *alieci.Client
region tenanter.Region
tenanter tenanter.Tenanter
}
func newAliEciClient(region tenanter.Region, tenant tenanter.Tenanter) (Poder, error) {
var (
client *alieci.Client
err error
)
switch t := tenant.(type) {
case *tenanter.AccessKeyTenant:
// 阿里云的sdk有一个 map 的并发问题go test 加上-race 能检测出来,所以这里加一个锁
aliClientMutex.Lock()
client, err = alieci.NewClientWithAccessKey(region.GetName(), t.GetId(), t.GetSecret())
aliClientMutex.Unlock()
default:
}
if err != nil {
return nil, errors.Wrap(err, "init ali ecs client error")
}
return &AliEci{
cli: client,
region: region,
tenanter: tenant,
}, nil
}
func (eci *AliEci) ListPodDetail(ctx context.Context, req *pbpod.ListPodDetailReq) (*pbpod.ListPodDetailResp, error) {
request := alieci.CreateDescribeContainerGroupsRequest()
request.NextToken = req.NextToken
resp, err := eci.cli.DescribeContainerGroups(request)
if err != nil {
return nil, errors.Wrap(err, "Aliyun ListDetail error")
}
var ecies = make([]*pbpod.PodInstance, len(resp.ContainerGroups))
for k, v := range resp.ContainerGroups {
ecies[k] = &pbpod.PodInstance{
Provider: pbtenant.CloudProvider_ali,
AccountName: eci.tenanter.AccountName(),
PodId: v.ContainerGroupId,
PodName: v.ContainerGroupName,
RegionName: eci.region.GetName(),
ContainerImage: v.Containers[k].Image,
ContainerName: v.Containers[k].Name,
CpuPod: v.Cpu,
MemoryPod: v.Memory,
SecurityGroupId: v.SecurityGroupId,
SubnetId: v.InternetIp,
VpcId: v.VpcId,
Namespace: "",
}
}
isFinished := false
if len(ecies) < int(req.PageSize) {
isFinished = true
}
return &pbpod.ListPodDetailResp{
Pods: ecies,
Finished: isFinished,
PageNumber: req.PageNumber + 1,
PageSize: req.PageSize,
NextToken: resp.NextToken,
RequestId: resp.RequestId,
}, nil
}
//
//// CreateContainerGroup 创建
//func CreateContainerGroup(cloudStack string, akskPath string, configPath string) string {
//
// var client *eci.Client
// configCommon, _ := config.PCMconfig(configPath)
// configAksk, _ := aksk.AkskConfig(cloudStack, akskPath)
//
// //创建客户端
// client, _ = eci.NewClientWithAccessKey(configCommon.RegionId, configAksk.AccessKey, configAksk.SecretKey)
// // 生成创建请求
// createContainerRequest := eci.CreateCreateContainerGroupRequest()
// // 必需参数
// //区域ID
// createContainerRequest.RegionId = configCommon.RegionId
// //POD名称
// createContainerRequest.ContainerGroupName = configCommon.ContainerGroupName
// //容器名称和镜像名称
// createContainerRequestContainer := make([]eci.CreateContainerGroupContainer, 1)
// createContainerRequestContainer[0].Image = configCommon.ContainerImage
// createContainerRequestContainer[0].Name = configCommon.ContainerName
// createContainerRequest.Container = &createContainerRequestContainer
//
// client.GetConfig().MaxRetryTime = 0
// createContainerGroupResponse, err := client.CreateContainerGroup(createContainerRequest)
// if err != nil {
// panic(err)
// }
// containerGroupId := createContainerGroupResponse.ContainerGroupId
// fmt.Println("Alibaba ContainerGroup created:", containerGroupId)
// return containerGroupId
//}
//
//// DescribeContainerGroup 查询Pod
//func DescribeContainerGroup(cloudStack string, akskPath string, configPath string) eci.DescribeContainerGroupsContainerGroup0 {
// var client *eci.Client
//
// configCommon, _ := config.PCMconfig(configPath)
// configAksk, _ := aksk.AkskConfig(cloudStack, akskPath)
// client, _ = eci.NewClientWithAccessKey(configCommon.RegionId, configAksk.AccessKey, configAksk.SecretKey)
//
// // 生成查询请求
// describeContainerGroupsRequest := eci.CreateDescribeContainerGroupsRequest()
// describeContainerGroupsRequest.RegionId = configCommon.RegionIdList
// describeContainerGroupsResponse, err := client.DescribeContainerGroups(describeContainerGroupsRequest)
// if err != nil {
// panic(err)
// }
// describeContainerGroupNumber := len(describeContainerGroupsResponse.ContainerGroups)
//
// //当前区域没有Pod情形的处理
// if describeContainerGroupsResponse.TotalCount != 1 && describeContainerGroupNumber != 1 {
// fmt.Println("Invalid ContainerGroups count", describeContainerGroupsResponse.TotalCount, describeContainerGroupNumber)
// panic("Invalid ContainerGroups count")
// }
//
// fmt.Println("Alibaba ContainerGroup Name:", describeContainerGroupsResponse.ContainerGroups[0].ContainerGroupName, "\n",
// "ContainerGroup Id:", describeContainerGroupsResponse.ContainerGroups[0].ContainerGroupId)
//
// return describeContainerGroupsResponse.ContainerGroups[0]
//}
//
//// UpdateContainerGroup 更新Pod
//func UpdateContainerGroup(cloudStack string, akskPath string, configPath string) string {
// var client *eci.Client
//
// configCommon, _ := config.PCMconfig(configPath)
// configAksk, _ := aksk.AkskConfig(cloudStack, akskPath)
//
// client, _ = eci.NewClientWithAccessKey(configCommon.RegionId, configAksk.AccessKey, configAksk.SecretKey)
//
// //生成更新请求
// updateContainerGroupRequest := eci.CreateUpdateContainerGroupRequest()
// updateContainerGroupRequest.RegionId = configCommon.RegionIdUpdate
// updateContainerGroupRequest.ContainerGroupId = configCommon.ContainerGroupIdUpdate
//
// //容器实体内容,这里测试可以修改配置文件中的重启策略
// updateContainerRequestContainer := make([]eci.UpdateContainerGroupContainer, 1)
// updateContainerRequestContainer[0].Image = configCommon.ContainerImage
// updateContainerRequestContainer[0].Name = configCommon.ContainerName
// updateContainerGroupRequest.Container = &updateContainerRequestContainer
// updateContainerGroupRequest.RestartPolicy = configCommon.RestartPolicyUpdate
//
// updateContainerGroupResponse, err := client.UpdateContainerGroup(updateContainerGroupRequest)
// if err != nil {
// panic(err)
// }
// requestId := updateContainerGroupResponse.RequestId
// fmt.Println("Alibaba ContainerGroup: ", configCommon.ContainerGroupIdUpdate, " Updated with request ID:", requestId)
// return requestId
//}
//
//// DeleteContainerGroup 删除Pod
//func DeleteContainerGroup(cloudStack string, akskPath string, configPath string) string {
// var client *eci.Client
// configCommon, _ := config.PCMconfig(configPath)
// configAksk, _ := aksk.AkskConfig(cloudStack, akskPath)
// client, _ = eci.NewClientWithAccessKey(configCommon.RegionId, configAksk.AccessKey, configAksk.SecretKey)
//
// //生成删除请求
// deleteContainerGroupRequest := eci.CreateDeleteContainerGroupRequest()
// deleteContainerGroupRequest.RegionId = configCommon.RegionIdDelete
// deleteContainerGroupRequest.ContainerGroupId = configCommon.ContainerGroupIdDelete
//
// deleteContainerGroupResponse, err := client.DeleteContainerGroup(deleteContainerGroupRequest)
// if err != nil {
// panic(err)
// }
// requestId := deleteContainerGroupResponse.RequestId
// fmt.Println("Alibaba ContainerGroup: ", configCommon.ContainerGroupIdUpdate, " Deleted with request ID:", requestId)
//
// return requestId
//}

View File

@ -0,0 +1,135 @@
package poder
//
//import (
// "fmt"
// "gitlink.org.cn/JCCE/PCM/adaptor/pod_adaptor/common/config"
// corev1 "k8s.io/api/core/v1"
// "k8s.io/apimachinery/pkg/api/resource"
// metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
// "k8s.io/client-go/kubernetes"
//)
//
//// CreatePod 创建Pod
//func CreatePod(client *kubernetes.Clientset, configPath string) (*corev1.Pod, error) {
//
// var configCommon config.PCMContainerConfig
// configCommon, _ = config.PCMconfig(configPath)
//
// nameSpace := configCommon.NameSpace
// podName := configCommon.ContainerGroupName
// containerImage := configCommon.ContainerImage
// containerName := configCommon.ContainerName
// cpuPod := configCommon.CpuPod
// memoryPod := configCommon.MemoryPod
// pod := corev1.Pod{
// TypeMeta: metav1.TypeMeta{
// APIVersion: "core/V1",
// Kind: "Pod",
// },
// ObjectMeta: metav1.ObjectMeta{
// Name: podName,
// Namespace: nameSpace,
// Labels: map[string]string{"name": "testapi"},
// },
// Spec: corev1.PodSpec{
// RestartPolicy: corev1.RestartPolicyAlways,
// Containers: []corev1.Container{
// {
// Name: containerName,
// Image: containerImage,
// Resources: corev1.ResourceRequirements{
// Limits: map[corev1.ResourceName]resource.Quantity{
// corev1.ResourceCPU: resource.MustParse(cpuPod),
// corev1.ResourceMemory: resource.MustParse(memoryPod),
// },
// },
// },
// },
// },
// Status: corev1.PodStatus{},
// }
//
// fmt.Println("Huawei ContainerGroup created")
// return client.CoreV1().Pods(nameSpace).Create(&pod)
//}
//
//// ListPod 查询Namespace下Pod列表
//func ListPod(client *kubernetes.Clientset, configPath string) (*corev1.PodList, error) {
//
// var configCommon config.PCMContainerConfig
// configCommon, _ = config.PCMconfig(configPath)
//
// nameSpace := configCommon.NameSpace
//
// podList, _ := client.CoreV1().Pods(nameSpace).List(metav1.ListOptions{})
// fmt.Println("Huawei ContainerGroup list", podList)
//
// return podList, nil
//}
//
//// UpdatePod 更新指定Pod
///*
//// 跨namespace目前有点问题
//*/
//func UpdatePod(client *kubernetes.Clientset, configPath string) (*corev1.Pod, error) {
//
// var configCommon config.PCMContainerConfig
// configCommon, _ = config.PCMconfig(configPath)
//
// nameSpace := configCommon.NamespaceUpdate
// podName := configCommon.ContainerGroupNameUpdate
// containerImage := configCommon.ContainerImageUpdate
// containerName := configCommon.ContainerNameUpdate
//
// pod := corev1.Pod{
// TypeMeta: metav1.TypeMeta{
// APIVersion: "core/V1",
// Kind: "Pod",
// },
// ObjectMeta: metav1.ObjectMeta{
// Name: podName,
// Namespace: nameSpace,
// Labels: map[string]string{"name": "pod-test2"},
// },
// Spec: corev1.PodSpec{
// RestartPolicy: corev1.RestartPolicyAlways,
// Containers: []corev1.Container{
// {
// Name: containerName,
// Image: containerImage,
// Resources: corev1.ResourceRequirements{
// Limits: map[corev1.ResourceName]resource.Quantity{
// corev1.ResourceLimitsCPU: resource.MustParse("500m"),
// corev1.ResourceLimitsMemory: resource.MustParse("1Gi"),
// },
// Requests: map[corev1.ResourceName]resource.Quantity{
// corev1.ResourceRequestsCPU: resource.MustParse("500m"),
// corev1.ResourceRequestsMemory: resource.MustParse("1Gi"),
// },
// },
// },
// },
// },
// Status: corev1.PodStatus{},
// }
//
// podNew, _ := client.CoreV1().Pods(nameSpace).Update(&pod)
// fmt.Println("Huawei ContainerGroup updated", podNew)
//
// return podNew, nil
//}
//
//// DeletePod 删除指定Pod
//func DeletePod(client *kubernetes.Clientset, configPath string) error {
//
// var configCommon config.PCMContainerConfig
// configCommon, _ = config.PCMconfig(configPath)
//
// nameSpace := configCommon.NameSpace
// podName := configCommon.ContainerGroupName
//
// fmt.Println("Huawei ContainerGroup:", podName, " Deleted")
//
// return client.CoreV1().Pods(nameSpace).Delete(podName, &metav1.DeleteOptions{})
//}

View File

@ -0,0 +1,139 @@
package poder
//
//import (
// "fmt"
// "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
// "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
// "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
// tke "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/tke/v20180525"
// "gitlink.org.cn/JCCE/PCM/adaptor/pod_adaptor/common/auth/aksk"
// pcmCommon "gitlink.org.cn/JCCE/PCM/adaptor/pod_adaptor/common/config"
//)
//
//func CreateEksInstance(cloudStack string, akskPath string, configPath string) {
//
// configCommon, _ := pcmCommon.PCMconfig(configPath)
// configAksk, _ := aksk.AkskConfig(cloudStack, akskPath)
//
// credential := common.NewCredential(
// configAksk.AccessKey,
// configAksk.SecretKey,
// )
// cpf := profile.NewClientProfile()
// cpf.HttpProfile.Endpoint = "tke.tencentcloudapi.com"
// client, _ := tke.NewClient(credential, configCommon.RegionId, cpf)
//
// request := tke.NewCreateEKSContainerInstancesRequest()
//
// eksCiName := &configCommon.ContainerGroupName
// containerName := &configCommon.ContainerName
// containerImage := &configCommon.ContainerImage
// eksCpu := &configCommon.CpuPodFloat
// eksMemory := &configCommon.MemoryPodFloat
// securityGroupId := &configCommon.SecurityGroupId
// securityGroupIds := make([]*string, 1)
// securityGroupIds[0] = securityGroupId
// subNetId := &configCommon.SubnetId
// vpcId := &configCommon.VpcId
//
// request.EksCiName = eksCiName
// container := make([]*tke.Container, 1)
// container[0] = new(tke.Container)
// container[0].Name = containerName
// container[0].Image = containerImage
// //container[0].Cpu = containerCpuPt
// //container[0].Memory = containerMemoryPt
//
// request.Containers = container
// request.Cpu = eksCpu
// request.Memory = eksMemory
// request.SecurityGroupIds = securityGroupIds
// request.SubnetId = subNetId
// request.VpcId = vpcId
//
// response, err := client.CreateEKSContainerInstances(request)
// if _, ok := err.(*errors.TencentCloudSDKError); ok {
// fmt.Printf("An API error has returned: %s", err)
// return
// }
// if err != nil {
// panic(err)
// }
// fmt.Printf("%s", response.ToJsonString())
//}
//
//func ListEksInstance(cloudStack string, akskPath string, configPath string) {
//
// configCommon, _ := pcmCommon.PCMconfig(configPath)
// configAksk, _ := aksk.AkskConfig(cloudStack, akskPath)
//
// credential := common.NewCredential(configAksk.AccessKey, configAksk.SecretKey)
// cpf := profile.NewClientProfile()
// cpf.HttpProfile.Endpoint = "tke.tencentcloudapi.com"
// client, _ := tke.NewClient(credential, configCommon.RegionId, cpf)
//
// request := tke.NewDescribeEKSContainerInstancesRequest()
//
// response, err := client.DescribeEKSContainerInstances(request)
// if _, ok := err.(*errors.TencentCloudSDKError); ok {
// fmt.Printf("An API error has returned: %s", err)
// return
// }
// if err != nil {
// panic(err)
// }
// fmt.Printf("%s", response.ToJsonString())
//}
//
//func UpdateEksInstance(cloudStack string, akskPath string, configPath string) {
//
// configCommon, _ := pcmCommon.PCMconfig(configPath)
// configAksk, _ := aksk.AkskConfig(cloudStack, akskPath)
//
// credential := common.NewCredential(configAksk.AccessKey, configAksk.SecretKey)
// cpf := profile.NewClientProfile()
// cpf.HttpProfile.Endpoint = "tke.tencentcloudapi.com"
// client, _ := tke.NewClient(credential, configCommon.RegionId, cpf)
//
// request := tke.NewUpdateEKSContainerInstanceRequest()
// request.EksCiId = &configCommon.ContainerGroupIdUpdate
// request.Name = &configCommon.ContainerGroupNameUpdate
//
// response, err := client.UpdateEKSContainerInstance(request)
// if _, ok := err.(*errors.TencentCloudSDKError); ok {
// fmt.Printf("An API error has returned: %s", err)
// return
// }
// if err != nil {
// panic(err)
// }
// fmt.Printf("%s", response.ToJsonString())
//}
//
//func DeleteEksInstance(cloudStack string, akskPath string, configPath string) {
//
// configCommon, _ := pcmCommon.PCMconfig(configPath)
// configAksk, _ := aksk.AkskConfig(cloudStack, akskPath)
//
// credential := common.NewCredential(configAksk.AccessKey, configAksk.SecretKey)
// cpf := profile.NewClientProfile()
// cpf.HttpProfile.Endpoint = "tke.tencentcloudapi.com"
// client, _ := tke.NewClient(credential, configCommon.RegionId, cpf)
//
// request := tke.NewDeleteEKSContainerInstancesRequest()
// eksCiIds := make([]*string, 1)
// eksCiIds[0] = &configCommon.ContainerGroupIdDelete
//
// request.EksCiIds = eksCiIds
//
// response, err := client.DeleteEKSContainerInstances(request)
// if _, ok := err.(*errors.TencentCloudSDKError); ok {
// fmt.Printf("An API error has returned: %s", err)
// return
// }
// if err != nil {
// panic(err)
// }
// fmt.Printf("%s", response.ToJsonString())
//}

View File

View File

@ -4,12 +4,14 @@ import (
"context"
"gitlink.org.cn/JCCE/PCM/lan_trans/idl/demo"
"gitlink.org.cn/JCCE/PCM/lan_trans/idl/pbecs"
"gitlink.org.cn/JCCE/PCM/lan_trans/idl/pbpod"
)
type Server struct {
// 使用unsafe可以强制让编译器检查是否实现了相关方法
demo.UnsafeDemoServiceServer
pbecs.UnsafeEcsServiceServer
pbpod.UnsafePodServiceServer
}
func (s *Server) Echo(ctx context.Context, req *demo.StringMessage) (*demo.StringMessage, error) {

View File

@ -2,13 +2,13 @@ configs:
# provider 0:阿里云 1:腾讯云 2:华为云
- provider: 0
name: "ali-PCM"
accessid: ""
accesssecret: ""
accessid: "LTAI5tSCnrhQAdbFhGyWkSL2"
accesssecret: "KN4tqu8lalQdo47SoUQBb88qOWjzYC"
- provider: 1
name: "tencent-PCM"
accessid: ""
accesssecret: ""
accessid: "AKIDRefQxnhmuqTU1KRWFl58wQeCE0XoAeEZ"
accesssecret: "LUMVRmGj2kFrEahhZzA5pKvHNSMASntj"
- provider: 2
name: "huawei-PCM"
accessid: ""
accesssecret: ""
accessid: "ATQTIWUT9K66VRMMXKVY"
accesssecret: "Wa0aixDVuhZOfDZGWvgIJQBHnyiDlGdgDn1Ai5Yy"

53
go.mod
View File

@ -1,53 +0,0 @@
module gitlink.org.cn/JCCE/PCM
go 1.17
require (
github.com/Unknwon/goconfig v1.0.0
github.com/aliyun/alibaba-cloud-sdk-go v1.61.1530
github.com/go-yaml/yaml v2.1.0+incompatible
github.com/golang/glog v1.0.0
github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.0
github.com/huaweicloud/huaweicloud-sdk-go-v3 v0.0.82
github.com/pkg/errors v0.9.1
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.377
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cvm v1.0.377
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/tke v1.0.371
google.golang.org/genproto v0.0.0-20220317150908-0efb43f6373e
google.golang.org/grpc v1.45.0
google.golang.org/protobuf v1.28.0
k8s.io/api v0.0.0-20190620084959-7cf5895f2711
k8s.io/apimachinery v0.0.0-20190612205821-1799e75a0719
k8s.io/client-go v0.0.0-20190620085101-78d2af792bab
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/evanphx/json-patch v0.0.0-20190203023257-5858425f7550 // indirect
github.com/gogo/protobuf v0.0.0-20171007142547-342cbe0a0415 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/google/gofuzz v1.0.0 // indirect
github.com/googleapis/gnostic v0.0.0-20170729233727-0c5108395e2d // indirect
github.com/imdario/mergo v0.3.5 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/json-iterator/go v1.1.10 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.1 // indirect
github.com/smartystreets/goconvey v1.7.2 // indirect
github.com/spf13/pflag v1.0.1 // indirect
golang.org/x/crypto v0.0.0-20210920023735-84f357641f63 // indirect
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd // indirect
golang.org/x/oauth2 v0.0.0-20220309155454-6242fa91716a // indirect
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e // indirect
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 // indirect
golang.org/x/text v0.3.7 // indirect
golang.org/x/time v0.0.0-20191024005414-555d28b269f0 // indirect
google.golang.org/appengine v1.6.6 // indirect
gopkg.in/inf.v0 v0.9.0 // indirect
gopkg.in/ini.v1 v1.66.2 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
k8s.io/klog v0.3.1 // indirect
k8s.io/kube-openapi v0.0.0-20190228160746-b3a7cee44a30 // indirect
k8s.io/utils v0.0.0-20190221042446-c2654d5206da // indirect
sigs.k8s.io/yaml v1.3.0 // indirect
)

164
idl/pbpod/pod.proto Normal file
View File

@ -0,0 +1,164 @@
syntax = "proto3";
package pbpod;
option go_package = "gitlink.org.cn/JCCE/PCM/lan_trans/idl/pbpod";
import "idl/pbtenant/tenant.proto";
import "google/api/annotations.proto";
message PodInstance {
//
pbtenant.CloudProvider provider = 1;
//
string account_name = 2;
// id
string pod_id = 3;
//
string pod_name = 4;
//
string region_name = 5;
//
string container_image = 6;
//
string container_name = 7;
// vcpu数
float cpu_pod = 8;
// MB
float memory_pod = 9;
//ID SecurityGroupIds()
string security_group_id = 10;
//ID SubnetId()
string subnet_id = 11;
//VPC ID VpcId()
string vpc_id = 12;
//
string namespace = 13;
}
message CreatePodReq {
//
pbtenant.CloudProvider provider = 1;
//
string account_name = 2;
// id
string pod_id = 3;
//
string pod_name = 4;
//
string region_name = 5;
//
string container_image = 6;
//
string container_name = 7;
// v cpu数
float cpu_pod = 8;
// MB
float memory_pod = 9;
//ID SecurityGroupIds()
string security_group_id = 10;
//ID SubnetId()
string subnet_id = 11;
//VPC ID VpcId()
string vpc_id = 12;
//
string namespace = 13;
}
message CreatePodResp {
// Pod集合
repeated PodInstance pods = 1;
// -false
bool finished = 2;
// id
string request_id = 3;
}
message ListPodDetailReq {
//
pbtenant.CloudProvider provider = 1;
// config.yaml中的配置
string account_name = 2;
// Id tenant.proto
int32 region_id = 3;
// podID
int32 pod_id = 4;
//
int32 page_number = 5;
//
int32 page_size = 6;
// token
string next_token = 7;
}
message ListPodDetailResp {
// Pod集合
repeated PodInstance pods = 1;
// -false
bool finished = 2;
//
int32 page_number = 3;
//
int32 page_size = 4;
// token
string next_token = 5;
// id
string request_id = 6;
}
message ListPodReq {
//
pbtenant.CloudProvider provider = 1;
}
message ListPodResp {
// pod集合
repeated PodInstance pods = 1;
}
message ListPodAllReq{}
// Pod类产品接口
// - ECI
// - TKS
// - CCI
service PodService {
// Pod
rpc CreatePod(CreatePodReq) returns (CreatePodResp) {
option (google.api.http) = {
post : "/apis/pod/create"
body : "*"
};
}
// Pod明细
rpc ListPodDetail(ListPodDetailReq) returns (ListPodDetailResp) {
option (google.api.http) = {
post : "/apis/pod/detail"
body : "*"
};
}
// Pod全量 -
rpc ListPod(ListPodReq) returns (ListPodResp) {
option (google.api.http) = {
post : "/apis/pod"
body : "*"
};
}
// Pod
rpc ListPodAll(ListPodAllReq) returns (ListPodResp) {
option (google.api.http) = {
post : "/apis/pod/all"
body : "*"
};
}
}

View File

@ -77,12 +77,13 @@ func RegisterDemoServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/demo.DemoService/Echo")
var err error
ctx, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/demo.DemoService/Echo", runtime.WithHTTPPathPattern("/apis/demo"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_DemoService_Echo_0(rctx, inboundMarshaler, server, req, pathParams)
resp, md, err := local_request_DemoService_Echo_0(ctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
@ -139,12 +140,13 @@ func RegisterDemoServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/demo.DemoService/Echo")
var err error
ctx, err = runtime.AnnotateContext(ctx, mux, req, "/demo.DemoService/Echo", runtime.WithHTTPPathPattern("/apis/demo"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_DemoService_Echo_0(rctx, inboundMarshaler, client, req, pathParams)
resp, md, err := request_DemoService_Echo_0(ctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)

View File

@ -145,12 +145,13 @@ func RegisterEcsServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux,
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pbecs.EcsService/ListEcsDetail")
var err error
ctx, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/pbecs.EcsService/ListEcsDetail", runtime.WithHTTPPathPattern("/apis/ecs/detail"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_EcsService_ListEcsDetail_0(rctx, inboundMarshaler, server, req, pathParams)
resp, md, err := local_request_EcsService_ListEcsDetail_0(ctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
@ -168,12 +169,13 @@ func RegisterEcsServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux,
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pbecs.EcsService/ListEcs")
var err error
ctx, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/pbecs.EcsService/ListEcs", runtime.WithHTTPPathPattern("/apis/ecs"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_EcsService_ListEcs_0(rctx, inboundMarshaler, server, req, pathParams)
resp, md, err := local_request_EcsService_ListEcs_0(ctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
@ -191,12 +193,13 @@ func RegisterEcsServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux,
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/pbecs.EcsService/ListEcsAll")
var err error
ctx, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/pbecs.EcsService/ListEcsAll", runtime.WithHTTPPathPattern("/apis/ecs/all"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_EcsService_ListEcsAll_0(rctx, inboundMarshaler, server, req, pathParams)
resp, md, err := local_request_EcsService_ListEcsAll_0(ctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
@ -253,12 +256,13 @@ func RegisterEcsServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux,
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/pbecs.EcsService/ListEcsDetail")
var err error
ctx, err = runtime.AnnotateContext(ctx, mux, req, "/pbecs.EcsService/ListEcsDetail", runtime.WithHTTPPathPattern("/apis/ecs/detail"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_EcsService_ListEcsDetail_0(rctx, inboundMarshaler, client, req, pathParams)
resp, md, err := request_EcsService_ListEcsDetail_0(ctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
@ -273,12 +277,13 @@ func RegisterEcsServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux,
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/pbecs.EcsService/ListEcs")
var err error
ctx, err = runtime.AnnotateContext(ctx, mux, req, "/pbecs.EcsService/ListEcs", runtime.WithHTTPPathPattern("/apis/ecs"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_EcsService_ListEcs_0(rctx, inboundMarshaler, client, req, pathParams)
resp, md, err := request_EcsService_ListEcs_0(ctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
@ -293,12 +298,13 @@ func RegisterEcsServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux,
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/pbecs.EcsService/ListEcsAll")
var err error
ctx, err = runtime.AnnotateContext(ctx, mux, req, "/pbecs.EcsService/ListEcsAll", runtime.WithHTTPPathPattern("/apis/ecs/all"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_EcsService_ListEcsAll_0(rctx, inboundMarshaler, client, req, pathParams)
resp, md, err := request_EcsService_ListEcsAll_0(ctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)

View File

@ -7,6 +7,7 @@ import (
"gitlink.org.cn/JCCE/PCM/common/tenanter"
"gitlink.org.cn/JCCE/PCM/lan_trans/idl/demo"
"gitlink.org.cn/JCCE/PCM/lan_trans/idl/pbecs"
"gitlink.org.cn/JCCE/PCM/lan_trans/idl/pbpod"
"net"
"net/http"
@ -35,6 +36,8 @@ func run() error {
return errors.Wrap(err, "RegisterDemoServiceHandlerFromEndpoint error")
} else if err = pbecs.RegisterEcsServiceHandlerFromEndpoint(ctx, mux, *grpcServerEndpoint, opts); err != nil {
return errors.Wrap(err, "RegisterEcsServiceHandlerFromEndpoint error")
} else if err = pbpod.RegisterPodServiceHandlerFromEndpoint(ctx, mux, *grpcServerEndpoint, opts); err != nil {
return errors.Wrap(err, "RegisterPodServiceHandlerFromEndpoint error")
}
// Start HTTP server (and proxy calls to gRPC server endpoint)
@ -43,7 +46,7 @@ func run() error {
func main() {
var configFile string
flag.StringVar(&configFile, "conf", "config.yaml", "configs/config.yaml")
flag.StringVar(&configFile, "conf", "configs/config.yaml", "config.yaml")
flag.Parse()
defer glog.Flush()
@ -65,6 +68,7 @@ func main() {
s := grpc.NewServer()
demo.RegisterDemoServiceServer(s, &server.Server{})
pbecs.RegisterEcsServiceServer(s, &server.Server{})
pbpod.RegisterPodServiceServer(s, &server.Server{})
if err = s.Serve(lis); err != nil {
glog.Fatalf("failed to serve: %v", err)