1024programmer Java In situ | Hulu_clientgogin’s simple integration ten Update

In situ | Hulu_clientgogin’s simple integration ten Update

Preface: This article is organized by the editor of Programming Notes#. It mainly introduces the simple integration of client-go gin and the knowledge related to Update. I hope it will be of certain reference value to you.

Background

Complete the simple integration of client-go gin 9-Create’s namespace deployment pod creation operation,Now proceed with the update modification operation!

update namespace

Take a certain ns as an example to add a label

About namespace,The labels we use most are name and labels (well I have done this before Quota example,Here we simply take labels as an example)

[zhangpeng@zhangpeng k8s-demo1]$ kubectl get ns --show-labels
NAME STATUS AGE LABELS
default Active 53d kubernetes.io/metadata.name=default
kube-node-lease Active 53d kubernetes.io/metadata.name=kube-node-lease
kube- public Active 53d kubernetes.io/metadata.name=kube-public
kube-system Active 53d kubernetes.io/metadata.name=kube-system
zhangpeng Active 1s kubernetes.io/metadata.name& #61;zhangpeng
zhangpeng1 Active 3h21m kubernetes.io/metadata.name=zhangpeng1

If we go to update to modify the namespace, we should usually modify the labels of the namespace&# xff0c;Take zhangpeng namespace as an example,I want to add a name=abcd tag
/src/service/Namespace.go p>

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:&# 61; 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 updatenamespace(ns Namespace) ( *v1.Namespace, error)
ctx := context.Background()
newNamespace, err := K8sClient.CoreV1().Namespaces().Update(ctx, &v1.Namespace
ObjectMeta: metav1.ObjectMeta
Name: ns.Name,
Labels: ns.Labels,
,
, metav1.UpdateOptions)
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)
func UpdateNameSpace(g *gin.Context)
var nameSpace Namespace
if err := g.ShouldBind(&nameSpace); err != nil
g.JSON(500, err)

namespace, err :&# 61; updatenamespace(nameSpace)
if err != nil
g.JSON(500, err)

ns := Namespace
Name: namespace.Name,
CreateTime: namespace.CreationTimestamp.Time,
Status: string(namespace.Status.Phase),
Labels: namespace.Labels,
Annotations: nil,

g.JSON (200, ns)

Createupdatenamespace methodUpdateNameSpace service
main.goCreate route:

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.POST("/namespace/update", service.UpdateNameSpace)
r.GET("/deployments", service.ListDeployment)
r.GET("/service", service.ListService)
r.GET("pods", service.ListallPod)
r.POST("/pod", service.CreatePod )
r.POST("/deployment", service.CreateDep)
core.InitDeployment()
r.Run()

Run main. go

Postman test

post http://127.0.0.1:8080/namespace/update

"name":"zhangpeng ",
"labels":"name":"abcd"

[zhangpeng@zhangpeng k8s-demo1]$ kubectl get ns --show-labels

Modify the name tag to other values

post http://127.0.0.1:8080/namespace/update

"name":"zhangpeng",
"labels":"name":"abcd123"


Others can be played: Expand the resource quotas,You can refer to this to configure the quota,I will not demonstrate it here!

update pod?

Can the pod be updated? Update?

Can pod be updated? The answer is no…
Note: pod is the life cycle of a container,Theoretically it cannot be updated,And the general pod is based on control and management of pods based on deployment or rs etc.,Modification means the end of the life cycle and the generation of new pods ,Of course, pods can be upgraded in place based on other applications of openkruise

Follow the gourd’s experience, Error

[zhangpeng@zhangpeng k8s]$ kubectl get pods -n zhangpeng
NAME READY STATUS RESTARTS AGE
zhangpeng 1/1 Running 0 78m

[zhangpeng@zhangpeng k8s-demo1]$ kubectl get pods -o yaml -n zhangpeng
apiVersion: v1
items:
- apiVersion: v1
kind: Pod
metadata:
creationTimestamp: "2022-06-22T02:31:49Z"
name: zhangpeng
namespace: zhangpeng
resourceVersion: "6076576"
uid: cee39c9d-fc29-40ee-933e-d9fa76ba20e1
spec:
containers:
- image: nginx
imagePullPolicy: Always
name : zhangpeng
resources:
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
- mountPath: /var/run/secrets/kubernetes.io/serviceaccount
name: kube-api-access-f7qvv
readOnly: true
dnsPolicy: ClusterFirst
enableServiceLinks: true
nodeName: k8s-2
preemptionPolicy: PreemptLowerPriority
priority: 0
restartPolicy: Always
schedulerName: default-scheduler
securityContext:
serviceAccount: default
serviceAccountName: default
terminationGracePeriodSeconds: 30
tolerations:
- effect: NoExecute
key : node.kubernetes.io/not-ready
operator: Exists
tolerationSeconds: 300
- effect: NoExecute
key: node.kubernetes.io/unreachable
operator: Exists
tolerationSeconds: 300
volumes:
- name: kube-api-access-f7qvv
projected:
defaultMode: 420
sources:
- serviceAccountToken:
expirationSeconds: 3607
path: token
- configMap:
items:
- key: ca.crt
path: ca.crt
name: kube-root-ca.crt
- downwardAPI :
items:
- fieldRef:
apiVersion: v1
fieldPath: metadata.namespace
path: namespace
status:
conditions:
- lastProbeTime: null
lastTransitionTime: "2022-06-22T02:31:49Z"
status: "True"
type: Initialized
- lastProbeTime: null
lastTransitionTime: "2022-06-22T02:32: 06Z"
status: "True"
type: Ready
- lastProbeTime: null
lastTransitionTime: "2022-06-22T02:32:06Z"
status: "True"
type: ContainersReady
- lastProbeTime: null
lastTransitionTime: "2022-06-22T02:31:49Z"
status: "True"
type: PodScheduled
containerStatuses:
- containerID : docker://47d2c805f72cd023ff9b33d46f63b1b8e7600f64783685fe4c16d97f4b58b290
image: nginx:latest
imageID: docker-pullable://nginx@sha256:0d17b565c37bcbd895e 9d92315a05c1c3c9a29f762b011a10c54a66cd53c9b31
lastState:
name: zhangpeng
ready: true
restartCount: 0
started: true
state:
running:
startedAt: "2022-06-22T02:32:05Z"
hostIP: 192.168.0.176
phase: Running
podIP: 10.244.1.64
podIPs:
- ip: 10.244.1.64
qosClass: BestEffort
startTime: "2022-06-22T02:31:49Z"
kind: List
metadata:
resourceVersion: ""

/src/service/Pod.go
Note : Written in imitation of deployment create… Anyway, the result is a failure,Just go through the process and see!Everything in the end needs to be deleted…

func (d *Pod) GetImageName() string
// All should be alphanumeric and:
pods := strings.Index(d.Images, ":")
if pods > 0
return d.Images[:pods]

return d.Images
func updatepod(pod Pod) (*corev1.Pod, error)
newpod, err := K8sClient.CoreV1().Pods(pod.Namespace) .Update(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, Ports: pod.GetPorts() ,
,
,
, metav1.UpdateOptions)
if err != nil
fmt.Println(err)

return newpod, err
func UpdatePod(g *gin.Context)
var NewPod Pod
if err := g.ShouldBind(&NewPod); err != nil
g.JSON(500, err)

pod, err := updatepod(NewPod)
if err != nil
g.JSON(500, err)

newpod :&# 61; Pod
Namespace: pod.Namespace,
Name: pod.Name,
Images: pod.Spec.Containers[0].Image,
CreateTime: pod.CreationTimestamp.Format("2006 -01-02 15:04:05"),
Annotations: pod.ObjectMeta.Annotations,

g.JSON(200, newpod)

Add the following configuration to main.go:

r.POST("/pod/update", service.UpdatePod)

Run main.go postman test:

Well, this is probably what it looks like Just to demonstrate ,A deeper understanding of the pod life cycle, Of course, you can also study the in-place upgrade methodsopenkruise is still very good!

update deployment

The initial deployment is next

[zhangpeng@zhangpeng k8s]$ kubectl get pods -n zhangpeng
NAME READY STATUS RESTARTS AGE
zhangpeng-5dffd5664f-nvfsm 1/1 Running 0 27s
[zhangpeng@zhangpeng k8s]$ kubectl get deployment zhangpeng -n zhangpeng
NAME READY UP-TO-DATE AVAILABLE AGE
zhangpeng 1 /1 1 1 40s

[zhangpeng@zhangpeng k8s]$ kubectl get deployment zhangpeng -n zhangpeng -o yaml
apiVersion: apps/v1
kind: Deployment
metadata:
annotations:
deployment.kubernetes.io/revision: "1"
creationTimestamp: "2022-06-22T06:44:06Z"
generation: 1
name: zhangpeng
namespace: zhangpeng
resourceVersion: "6096527"
uid: d42d5851-2e63-439b-b2a5-976b5fe246bb
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-22T06:44:24Z"
lastUpdateTime: "2022-06-22T06:44:24Z"
message: Deployment has minimum availability.
reason: MinimumReplicasAvailable
status: "True"
type: Available
- lastTransitionTime: "2022-06-22T06:44:06Z"
lastUpdateTime: "2022-06-22T06 :44:24Z"
message: ReplicaSet "zhangpeng-5dffd5664f" has successfully progressed.
reason: NewReplicaSetAvailable
status: "True"
type: Progressing
observedGeneration: 1
readyReplicas : 1
replicas: 1
updatedReplicas: 1

The key word is:

"name":" zhangpeng",
"namespace":"zhangpeng",
"replicas":1,
"ports":"tcp,80,web",
"images":"nginx"

Writing program files

/src/service/Deployment.go

func Updatedep(dep Deployment) ( *v1.Deployment, error)
deployment := &v1.Deployment
ObjectMeta: metav1.ObjectMeta
Name: dep.Name,
Namespace: dep.Namespace,
Labels: dep.GetLabels(),
,
Spec: v1.DeploymentSpec
Replicas: &dep.Replicas,
Selector: &metav1.Lab: List
metadata:
resourceVersion: ""

/src/service/Pod.go
Note : Written by imitating deployment create …Anyway, the result is a failure,Just go through the process and take a look!Everything in the end needs to be deleted…

func (d *Pod) GetImageName() string
// All should be alphanumeric and:
pods := strings.Index(d.Images, ":")
if pods > 0
return d.Images[:pods ]

return d.Images
func updatepod(pod Pod) (*corev1.Pod, error)
newpod, err := K8sClient.CoreV1().Pods(pod.Namespace ).Update(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, Ports: pod.GetPorts( ),
,
,
, metav1.UpdateOptions)
if err != nil
fmt.Println(err)

return newpod, err
func UpdatePod(g *gin.Context)
var NewPod Pod
if err := g.ShouldBind(&NewPod); err != nil
g.JSON(500, err )

pod, err := updatepod(NewPod)
if err != nil
g.JSON(500, err)

newpod :& #61; Pod
Namespace: pod.Namespace,
Name: pod.Name,
Images: pod.Spec.Containers[0].Image,
CreateTime: pod.CreationTimestamp.Format(" 2006-01-02 15:04:05"),
Annotations: pod.ObjectMeta.Annotations,

g.JSON(200, newpod)

main.go adds the following configuration:

r.POST("/pod/update", service.UpdatePod)

Run main.go postman test:

Well, this is probably it This is just to demonstrate ,have a deeper understanding of the pod life cycle, Of course, you can also study the in-place upgrade methodsopenkruise is still very good!

update deployment

The initial deployment is next

[zhangpeng@zhangpeng k8s]$ kubectl get pods -n zhangpeng
NAME READY STATUS RESTARTS AGE
zhangpeng-5dffd5664f-nvfsm 1/1 Running 0 27s
[zhangpeng@zhangpeng k8s]$ kubectl get deployment zhangpeng -n zhangpeng
NAME READY UP-TO-DATE AVAILABLE AGE
zhangpeng 1/1 1 1 40s

[zhangpeng@zhangpeng k8s]$ kubectl get deployment zhangpeng -n zhangpeng -o yaml
apiVersion: apps/v1
kind: Deployment
metadata:
annotations:
deployment.kubernetes.io/revision: "1"
creationTimestamp: "2022-06-22T06:44:06Z"
generation : 1
name: zhangpeng
namespace: zhangpeng
resourceVersion: "6096527"
uid: d42d5851-2e63-439b-b2a5-976b5fe246bb
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-22T06:44:24Z"
lastUpdateTime: "2022-06-22T06:44:24Z"
message: Deployment has minimum availability.
reason: MinimumReplicasAvailable
status: "True"
type: Available
- lastTransitionTime: "2022-06-22T06:44:06Z"
lastUpdateTime: "2022-06- 22T06:44:24Z"
message: ReplicaSet "zhangpeng-5dffd5664f" has successfully progressed.
reason: NewReplicaSetAvailable
status: "True"
type: Progressing
observedGeneration: 1
readyReplicas: 1
replicas: 1
updatedReplicas: 1

The key word is:

"name": "zhangpeng",
"namespace":"zhangpeng",
"replicas":1,
"ports":"tcp,80,web",
"images":"nginx"

Writing program files

/src/service/Deployment.go

func Updatedep(dep Deployment) (*v1.Deployment, error)
deployment := &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(),
,
,
,
,
,

ctx := context.Background()
newdep, err := lib.K8sClient.AppsV1().Deployments (dep.Namespace).Update(ctx, deployment, metav1.UpdateOptions)
if err != nil
fmt.Println(err)

return newdep, nil
func UpdateDep(g *gin.Context)
var newDep Deployment
if err := g.ShouldBind(&newDep); err != nil
g.JSON(500, err)

newdep, err := Updatedep(newDep)
if err != nil
g.JSON(500, err)

newDep1 :&#61 ; Deployment
Namespace: newdep.Namespace,
Name: newdep.Name,
Pods: GetPodsByDep(*newdep),
CreateTime: newdep.CreationTimestamp.Format("2006-01-02 15: 03:04"),

g.JSON(200, newDep1)

Note that it is basically modified from the previous deployment create method …

Add a route and run main.go

main.go add a route and run main.go

r.POST("/ deployment/update", service.UpdateDep)

Postman test

Modify the copy to 2

http://127.0.0.1:8080/deployment/update

"name":"zhangpeng",
"namespace":"zhangpeng",
"replicas":2,
"ports":"tcp,80,web",
"images":"nginx"

Modify the image tag

I initially thought of modifying nginx to nginx:1.18 but failed…

It is probably a problem with the images data format,Ignore it for now…The next step is to modify the image to an apache image(Note that the image is httpd)
http://127.0.0.1:8080/deployment/update

"name":"zhangpeng",
"namespace":"zhangpeng",
"replicas":2,
"ports":"tcp,80,web",
"images":"httpd"

Login server verification:

zhangpeng& #64;zhangpeng k8s]$ kubectl get pods -n zhangpeng
NAME READY STATUS RESTARTS AGE
zhangpeng-5546976d9-mkslb 1/1 Running 0 73s
zhangpeng-5546976d9-tcsb5 0/1 ContainerCreating 0 14s
zhangpeng-5dffd5664f-nvfsm 1/1 Running 0 18m
[zhangpeng@zhangpeng k8s]$ kubectl get pods -n zhangpeng
NAME READY STATUS RESTARTS AGE
zhangpeng-5546976d9-mkslb 1/1 Running 0 100s
zhangpeng-5546976d9-tcsb5 1/1 Running 0 41s
[zhangpeng@zhangpeng k8s]$ kubectl get deployment -n zhangpeng -o yaml |grep image
- image: httpd
imagePullPolicy: Always

Summary:

1.Pod life cycle
2.Update is modified compared to createupdate metav1. UpdateOptions
3. We will see how to solve the problem of the image tag later

elSelector
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(),
,
,
,
,
,

ctx: context.Background()
newdep, err := lib.K8sClient.AppsV1().Deployments(dep.Namespace).Update(ctx, deployment, metav1.UpdateOptions)
if err != nil
fmt.Println(err )

return newdep, nil
func UpdateDep(g *gin.Context)
var newDep Deployment
if err := g.ShouldBind(&newDep); err !&# 61; nil
g.JSON(500, err)

newdep, err := Updatedep(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)

Note :Basically, we modified the previous deployment create method…

Add routing and run main.go

main.go, add routing and run main.go

r.POST("/deployment/update", service.UpdateDep)

Postman test

Modify the copy to 2

http: //127.0.0.1:8080/deployment/update

"name":"zhangpeng",
"namespace":"zhangpeng",
"replicas":2,
"ports":"tcp,80,web",
"images":"nginx"

Modify the image tag

At first I wanted to modify nginx to nginx:1.18 but failed…

It is probably a problem with the images data format,Ignore it for now…Return Next, change the image to an apache image. Note that the image is httpd.
http://127.0.0.1:8080/deployment/update

"name": "zhangpeng",
"namespace":"zhangpeng",
"replicas":2,
"ports":"tcp,80,web",
"images":"httpd"

Login to server verification :

zhangpeng@zhangpeng k8s]$ kubectl get pods -n zhangpeng
NAME READY STATUS RESTARTS AGE
zhangpeng-5546976d9-mkslb 1/1 Running 0 73s
zhangpeng-5546976d9-tcsb5 0/1 ContainerCreating 0 14s
zhangpeng-5dffd5664f-nvfsm 1/1 Running 0 18m
[zhangpeng@zhangpeng k8s]$ kubectl get pods -n zhangpeng
NAME READY STATUS RESTARTS AGE
zhangpeng-5546976d9-mkslb 1/1 Running 0 100s
zhangpeng-5546976d9-tcsb5 1/1 Running 0 41s
[zhangpeng@zhangpeng k8s]$ kubectl get deployment -n zhangpeng -o yaml |grep image
- image: httpd
imagePullPolicy: Always

Summary:

1.Pod life cycle
2. The difference between update and create has been modified update metav1.UpdateOptions
3. We will see how to solve the problem of the image tag later

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/746481

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索