当前位置:网站首页>Simple integration of client go gin IX create
Simple integration of client go gin IX create
2022-06-21 20:31:00 【I have nothing to do with you】
background :
Completed the previous simple list-watch Of demo, Here we begin to complete further crud Basic operation , From create Here we go . From here create namespace deployment pod service Make a simple application list
create namespace
About namespace
I've done it before list Application :client-go list namespace,/src/service/Namespace.go The documents are as follows :
package service
import (
"context"
"github.com/gin-gonic/gin"
. "k8s-demo1/src/lib"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"time"
)
type Time struct {
time.Time `protobuf:"-"`
}
type Namespace struct {
Name string
CreateTime Time `json:"CreateTime"`
Status string
Labels map[string]string
}
func ListNamespace(g *gin.Context) {
ns, err := K8sClient.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{})
if err != nil {
g.Error(err)
return
}
ret := make([]*Namespace, 0)
for _, item := range ns.Items {
ret = append(ret, &Namespace{
Name: item.Name,
CreateTime: Time(item.CreationTimestamp),
Status: string(item.Status.Phase),
Labels: item.Labels,
})
}
g.JSON(200, ret)
return
}Create a namespace
Now create a create Methods for creating namespaces !
In the end the following :
func create(ns Namespace) (*v1.Namespace, error) {
ctx := context.Background()
newNamespace, err := K8sClient.CoreV1().Namespaces().Create(ctx, &v1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: ns.Name,
Labels: ns.Labels,
},
}, metav1.CreateOptions{})
if err != nil {
fmt.Println(err)
}
return newNamespace, err
}Then create CreateNameSpace, In the end the following :
package service
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
. "k8s-demo1/src/lib"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"time"
)
type Time struct {
time.Time `protobuf:"-"`
}
type Namespace struct {
Name string `json:"name"`
CreateTime time.Time `json:"CreateTime"`
Status string `json:"status"`
Labels map[string]string `json:"labels"`
Annotations map[string]string `json:"annotations"`
}
func ListNamespace(g *gin.Context) {
ns, err := K8sClient.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{})
if err != nil {
g.Error(err)
return
}
ret := make([]*Namespace, 0)
for _, item := range ns.Items {
ret = append(ret, &Namespace{
Name: item.Name,
CreateTime: item.CreationTimestamp.Time,
Status: string(item.Status.Phase),
Labels: item.Labels,
})
}
g.JSON(200, ret)
return
}
func create(ns Namespace) (*v1.Namespace, error) {
ctx := context.Background()
newNamespace, err := K8sClient.CoreV1().Namespaces().Create(ctx, &v1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: ns.Name,
Labels: ns.Labels,
},
}, metav1.CreateOptions{})
if err != nil {
fmt.Println(err)
}
return newNamespace, err
}
func CreateNameSpace(g *gin.Context) {
var nameSpace Namespace
if err := g.ShouldBind(&nameSpace); err != nil {
g.JSON(500, err)
}
namespace, err := create(nameSpace)
if err != nil {
g.JSON(500, err)
}
ns := Namespace{
Name: namespace.Name,
CreateTime: namespace.CreationTimestamp.Time,
Status: string(namespace.Status.Phase),
Labels: nil,
Annotations: nil,
}
g.JSON(200, ns)
}notes :ShouldBind Emphasize the reference :https://www.kancloud.cn/shuangdeyu/gin_book/949426. Yes, of course name Can't be empty. You can try !
Edit and run main.go
package main
import (
"github.com/gin-gonic/gin"
"k8s-demo1/src/core"
"k8s-demo1/src/service"
// "k8s.io/client-go/informers/core"
)
func main() {
r := gin.Default()
r.GET("/", func(context *gin.Context) {
context.JSON(200, "hello")
})
r.GET("/namespaces", service.ListNamespace)
r.POST("/namespace", service.CreateNameSpace)
r.GET("/deployments", service.ListDeployment)
r.GET("/service", service.ListService)
r.GET("pods", service.ListallPod)
core.InitDeployment()
r.Run()
}[[email protected] ~]$ kubectl get ns
NAME STATUS AGE
default Active 50d
kube-node-lease Active 50d
kube-public Active 50d
kube-system Active 50dfunction main.go......
Postman test
Create Pod
reference :https://blog.csdn.net/weixin_42562106/article/details/122024744, Compare the previous creation above namespace Step Creation Pod file :
Pod.go
/src/service/Pod.go
package service
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
"k8s-demo1/src/core"
. "k8s-demo1/src/lib"
v1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
type Pod struct {
Namespace string `json:"namespace"`
Name string `json:"name"`
Status string `json:"status"`
Images string `json:"images"`
NodeName string `json:"nodename"`
CreateTime string `json:"createtime"`
Annotations map[string]string `json:"annotations"`
Port []corev1.ContainerPort `json:"port"`
//IsReady bool
//Message string
//HostIp string
//PodIp string
//RestartCount int32
Labels map[string]string `json:"labels"`
}
func ListallPod(g *gin.Context) {
ns := g.Query("ns")
//pods, err := K8sClient.CoreV1().Pods(ns).List(context.Background(), metav1.ListOptions{})
pods, err := core.PodMap.ListByNS(ns)
if err != nil {
g.Error(err)
}
ret := make([]*Pod, 0)
for _, item := range pods {
ret = append(ret, &Pod{
Namespace: item.Namespace,
Name: item.Name,
Status: string(item.Status.Phase),
Labels: item.Labels,
NodeName: item.Spec.NodeName,
Images: item.Spec.Containers[0].Image,
//IsReady: GetPodIsReady(*item),
//Message: GetPodMessage(*item),
//Message: core.EventMap.GetMessage(item.Namespace, "Pod", item.Name),
//HostIp: item.Status.HostIP,
//PodIp: item.Status.PodIP,
//RestartCount: item.Status.ContainerStatuses[0].RestartCount,
CreateTime: item.CreationTimestamp.Format("2006-01-02 15:04:05"),
})
}
g.JSON(200, ret)
return
}
func Createpod(pod Pod) (*corev1.Pod, error) {
newpod, err := K8sClient.CoreV1().Pods(pod.Namespace).Create(context.TODO(), &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: pod.Name,
Namespace: pod.Namespace,
Labels: pod.Labels,
Annotations: pod.Annotations,
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{Name: pod.Name, Image: pod.Images},
},
},
}, metav1.CreateOptions{})
if err != nil {
fmt.Println(err)
}
return newpod, err
}
func CreatePod(g *gin.Context) {
var NewPod Pod
if err := g.ShouldBind(&NewPod); err != nil {
g.JSON(500, err)
}
pod, err := Createpod(NewPod)
if err != nil {
g.JSON(500, err)
}
newpod := Pod{
Namespace: pod.Namespace,
Name: pod.Name,
Images: pod.Spec.Containers[0].Image,
CreateTime: pod.CreationTimestamp.Format("2006-01-02 15:04:05"),
Annotations: nil,
}
g.JSON(200, newpod)
} notes : json:"",shouldbind The use of is still ......
main.go Add route
main.go
package main
import (
"github.com/gin-gonic/gin"
"k8s-demo1/src/core"
"k8s-demo1/src/service"
// "k8s.io/client-go/informers/core"
)
func main() {
r := gin.Default()
r.GET("/", func(context *gin.Context) {
context.JSON(200, "hello")
})
r.GET("/namespaces", service.ListNamespace)
r.GET("/deployments", service.ListDeployment)
r.GET("/service", service.ListService)
r.GET("pods", service.ListallPod)
r.POST("/namespace", service.CreateNameSpace)
r.POST("/pod", service.CreatePod)
core.InitDeployment()
r.Run()
}function main.go
go run main.go( direct goland It's running )
Postman Test creation pod
stay zhangpeng Create an image under the namespace as nginx, be known as zhangpeng Of pod
get Access validation pod Whether to create successfully :
http://127.0.0.1:8080/pods?ns=zhangpeng
Create Deployment
reference : Create a deployment. Anyway, I still haven't figured out how to do it , And then in github I have found a doctrine of taking things that I can understand :
github si
/src/service/DepUtils.go
package service
import (
coreV1 "k8s.io/api/core/v1"
"strconv"
"strings"
)
func (d *Deployment) GetLabels() map[string]string {
labelsMap := make(map[string]string)
labels := strings.Split(d.Labels, "\n")
for _, label := range labels {
values := strings.SplitN(label, ":", 2)
if len(values) != 2 {
continue
}
labelsMap[strings.TrimSpace(values[0])] = strings.TrimSpace(values[1])
}
return labelsMap
}
func (d *Deployment) GetSelectors() map[string]string {
selectors := d.GetLabels()
selectors["app"] = d.Name
return selectors
}
func (d *Deployment) GetPorts() []coreV1.ContainerPort {
portList := make([]coreV1.ContainerPort, 0, 5)
ports := strings.Split(d.Ports, "\n")
for _, port := range ports {
values := strings.SplitN(port, ",", 3)
if len(values) != 3 {
continue
}
intPort, err := strconv.Atoi(values[1])
if err != nil {
continue
}
protocol := coreV1.ProtocolTCP
if strings.Compare(strings.ToLower(values[0]), "tcp") != 0 {
protocol = coreV1.ProtocolUDP
}
portList = append(portList, coreV1.ContainerPort{
Name: strings.TrimSpace(values[2]),
ContainerPort: int32(intPort),
Protocol: protocol,
})
}
return portList
}
func (d *Deployment) GetImageName() string {
// All shall be alphanumeric and :
pods := strings.Index(d.Images, ":")
if pods > 0 {
return d.Images[:pods]
}
return d.Images
}/src/service/deployment.go
package service
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
"k8s-demo1/src/core"
. "k8s-demo1/src/lib"
v1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"log"
)
type Deployment struct {
Namespace string `json:"namespace"`
Name string `json:"name"`
Replicas int32 `json:"replicas"`
AvailableReplicas int32 `json:"available-replicas"`
UnavailableReplicas int32 `json:"unavailable-replicas"`
Images string `json:"images"`
Ports string `json:"ports"`
CreateTime string `json:"CreateTime"`
Labels string `json:"labels"`
Pods []*Pod `json:"pods"`
}
func ListDeployment(g *gin.Context) {
ns := g.Query("ns")
deplist, _ := core.DepMap.ListByNS(ns)
ret := make([]*Deployment, 0)
for _, item := range deplist {
ret = append(ret, &Deployment{
Namespace: item.Namespace,
Name: item.Name,
Replicas: item.Status.Replicas,
AvailableReplicas: item.Status.AvailableReplicas,
UnavailableReplicas: item.Status.UnavailableReplicas,
Images: item.Spec.Template.Spec.Containers[0].Image,
//Labels: item.GetLabels(),
Pods: GetPodsByDep(*item),
CreateTime: item.CreationTimestamp.Format("2006-01-02 15:03:04"),
})
}
g.JSON(200, ret)
return
}
func Createdep(dep Deployment) (*v1.Deployment, error) {
newdep, err := K8sClient.AppsV1().Deployments(dep.Namespace).Create(context.TODO(), &v1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: dep.Name,
Namespace: dep.Namespace,
Labels: dep.GetLabels(),
},
Spec: v1.DeploymentSpec{
Replicas: &dep.Replicas,
Selector: &metav1.LabelSelector{
MatchLabels: dep.GetSelectors(),
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Name: dep.Name,
Labels: dep.GetSelectors(),
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: dep.GetImageName(),
Image: dep.Images,
Ports: dep.GetPorts(),
},
},
},
},
},
}, metav1.CreateOptions{})
if err != nil {
fmt.Println(err)
}
return newdep, err
}
func CreateDep(g *gin.Context) {
var newDep Deployment
if err := g.ShouldBind(&newDep); err != nil {
g.JSON(500, err)
}
newdep, err := Createdep(newDep)
if err != nil {
g.JSON(500, err)
}
newDep1 := Deployment{
Namespace: newdep.Namespace,
Name: newdep.Name,
Pods: GetPodsByDep(*newdep),
CreateTime: newdep.CreationTimestamp.Format("2006-01-02 15:03:04"),
}
g.JSON(200, newDep1)
}
func GetLabels(m map[string]string) string {
labels := ""
// aa=xxx,xxx=xx
for k, v := range m {
if labels != "" {
labels += ","
}
labels += fmt.Sprintf("%s=%s", k, v)
}
return labels
}
func GetPodsByDep(dep v1.Deployment) []*Pod {
rsLabelsMap, err := core.RSMap.GetRsLabelsByDeployment(&dep)
//fmt.Println(rsLabelsMap)
if err != nil {
log.Fatal(err)
}
pods, err := core.PodMap.ListByRsLabels(dep.Namespace, rsLabelsMap)
if err != nil {
log.Fatal(err)
}
ret := make([]*Pod, 0)
for _, pod := range pods {
//
if core.RSMap.GetRsLabelsByDeploymentname(&dep) == pod.OwnerReferences[0].Name {
ret = append(ret, &Pod{
Name: pod.Name,
Namespace: pod.Namespace,
Images: pod.Spec.Containers[0].Image,
NodeName: pod.Spec.NodeName,
Labels: pod.Labels,
Status: string(pod.Status.Phase),
//IsReady: GetPodIsReady(*pod),
// Message: GetPodMessage(*pod),
//Message: core.EventMap.GetMessage(pod.Namespace, "Pod", pod.Name),
//HostIp: pod.Status.HostIP,
//PodIp: pod.Status.PodIP,
//RestartCount: pod.Status.ContainerStatuses[0].RestartCount,
CreateTime: pod.CreationTimestamp.Format("2006-01-02 15:04:05"),
})
}
}
return ret
}notes :Deployment struct Several data types have been changed , Some methods have not been submitted ...... Back Integration ......
add to post Route and run main.go
main.go Route add POST("/deployment", service.CreateDep), function main.go!
package main
import (
"github.com/gin-gonic/gin"
"k8s-demo1/src/core"
"k8s-demo1/src/service"
// "k8s.io/client-go/informers/core"
)
func main() {
r := gin.Default()
r.GET("/", func(context *gin.Context) {
context.JSON(200, "hello")
})
r.GET("/namespaces", service.ListNamespace)
r.GET("/deployments", service.ListDeployment)
r.GET("/service", service.ListService)
r.GET("pods", service.ListallPod)
r.POST("/namespace", service.CreateNameSpace)
r.POST("/pod", service.CreatePod)
r.POST("/deployment", service.CreateDep)
core.InitDeployment()
r.Run()
}Postman Test creation deployment
http://127.0.0.1:8080/deployment
{"name":"zhangpeng",
"namespace":"zhangpeng",
"replicas":1,
"ports":"tcp,80,web",
"images":"nginx"}kubernetes Cluster operation :
[[email protected] ~]$ kubectl get all -n zhangpeng
NAME READY STATUS RESTARTS AGE
pod/zhangpeng-5dffd5664f-z567c 1/1 Running 0 62s
NAME READY UP-TO-DATE AVAILABLE AGE
deployment.apps/zhangpeng 1/1 1 1 62s
NAME DESIRED CURRENT READY AGE
replicaset.apps/zhangpeng-5dffd5664f 1 1 1 62s[email protected] ~$ kubectl get deployment -n zhangpeng -o yaml
apiVersion: v1
items:
- apiVersion: apps/v1
kind: Deployment
metadata:
annotations:
deployment.kubernetes.io/revision: "1"
creationTimestamp: "2022-06-21T08:36:12Z"
generation: 1
name: zhangpeng
namespace: zhangpeng
resourceVersion: "5991952"
uid: e8a48bdf-4c86-4413-8fb0-99ef1ddd1d6d
spec:
progressDeadlineSeconds: 600
replicas: 1
revisionHistoryLimit: 10
selector:
matchLabels:
app: zhangpeng
strategy:
rollingUpdate:
maxSurge: 25%
maxUnavailable: 25%
type: RollingUpdate
template:
metadata:
creationTimestamp: null
labels:
app: zhangpeng
name: zhangpeng
spec:
containers:
- image: nginx
imagePullPolicy: Always
name: nginx
ports:
- containerPort: 80
name: web
protocol: TCP
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
dnsPolicy: ClusterFirst
restartPolicy: Always
schedulerName: default-scheduler
securityContext: {}
terminationGracePeriodSeconds: 30
status:
availableReplicas: 1
conditions:
- lastTransitionTime: "2022-06-21T08:36:29Z"
lastUpdateTime: "2022-06-21T08:36:29Z"
message: Deployment has minimum availability.
reason: MinimumReplicasAvailable
status: "True"
type: Available
- lastTransitionTime: "2022-06-21T08:36:12Z"
lastUpdateTime: "2022-06-21T08:36:29Z"
message: ReplicaSet "zhangpeng-5dffd5664f" has successfully progressed.
reason: NewReplicaSetAvailable
status: "True"
type: Progressing
observedGeneration: 1
readyReplicas: 1
replicas: 1
updatedReplicas: 1
kind: List
metadata:
resourceVersion: ""Mainly to verify ports Related configuration of !
defects
One more time, the program will hang up ...... Print about rs Error of , It is estimated that list watch There is still a problem , Ignore first :
Let's study later ....... Now I just want to be able to create deployment......
summary :
- github Dafa is good , Good at finding resources
- Didn't think about list watch Can I create deployment?
- /src/service/DepUtils.go And digest , The feeling of taking it is very useful .ports I haven't figured out how to achieve it , thank github......
边栏推荐
- 集成公告|Anima协议上线Moonbeam
- 第十七届全国大学 RT-Thread创新专项奖
- 汇编语言贪吃蛇、俄罗斯方块双任务设计实现详解(一)——整体系统设计
- zabbix6.0+timescaledb+企业微信告警
- Implementation of assembly language greedy snake and Tetris dual task design (II) -- detailed design of greedy snake
- mysql如何查询最大id值
- 阿里云 ACK One、ACK 云原生 AI 套件新发布,解决算力时代下场景化需求
- inno setup 安装路径框学习
- 點雲轉深度圖:轉化,保存,可視化
- How to query all tables in MySQL
猜你喜欢

mysql如何实现分组求和

如何查询mysql中所有表
![[icml2022] ctrlformer: learn the transferable state representation of visual control through the transformer](/img/d7/483ba497a72bd73b7ebc004bc922cb.png)
[icml2022] ctrlformer: learn the transferable state representation of visual control through the transformer

Recycleview lazy load failure (II)

机器学习和模式识别怎么区分?

uniapp小程序打开地图选择位置demo效果wx.chooseLocation(整理)

Redis 做缓存场景引发的问题

技术实践 | 场景导向的音视频通话体验优化

Points cloud to Depth maps: conversion, Save, Visualization

IAR重大升级,支持VS Code,ST发布第一个带有处理单元的传感器
随机推荐
函子(Functor)
A simple architecture design logic | acquisition technology
With a playback volume of up to 4000w+, how do couples get out of the ring by scattering dog food?
【基于合泰HT32F52352的智慧垃圾桶总结】
Influxdb optimization configuration item
How to debug reorganization in jetpack compose
日常开发常用工具提升效率
How to distinguish between machine learning and pattern recognition?
pfSense配置TINC站点至站点隧道教程
Inno setup window drag learning
Flink CDC MongoDB Connector 的实现原理和使用实践
Resttemplate multiple authentication information authorization
Source code analysis of ArrayList
运维监控数据可视化-让数据自己会说话[华汇数据]
點雲轉深度圖:轉化,保存,可視化
uniapp小程序打开地图选择位置demo效果wx.chooseLocation(整理)
如何查询mysql中所有表
Zabbix6.0+timescaledb+ enterprise wechat alarm
mysql如何查询最大id值
Jenkins定时构建并传递构建参数