1 introduction

This section describes how to deserialize a YAML file and convert it to a K8S Deployment object.

Note: For details about GO SDK installation and GO project configuration, please refer to the previous articles of this series.


Serialization and deserialization

On March 12, 1907, a British man named Stein arrived at Dunhuang. In the following days, he gained the trust of his guardian, Taoist Wang through xiaoen xiaohui, and entered the Thousand Buddha Cave on March 16.

On that day, a cultural miracle that shocked the world revealed its true appearance from the dust of history, which was Dunhuang.

Where once the wind and rain west window, where once the grass setting sun.

Stein bought many valuable artifacts, including beautiful frescoes, at very low prices. Some of the murals were so large that They were “disassembled” for easy transport, and although they were reassembled when they arrived in England, the loss of art was incalculable.

A cut dunhuang fresco

The serialization and deserialization of objects is stein’s process of cutting the mural into pieces and restoring it from the pieces.

The essence of serialization and deserialization is to implement object data type conversion (such as object to slice), and the purpose of object type conversion is to facilitate data storage and transfer.


3 Operating Environment

The environment configuration used in this series of articles is as follows (readers are not required to match exactly, but can use it according to their own situation) :

  • K8s version: 1.19.0
  • Docker version: 20.10.8
  • CentOS version: 7.7.1908
  • Go SDK version: Go 1.16.6 Linux/AMD64

4 Project Code

Enter the GO project root directory:

# cd $GOPATH/src
Copy the code

Create busybox.yaml under k8s-unmarshal:

# mkdir k8s-unmarshal
# cd k8s-unmarshal
# touch busybox.yaml
Copy the code

Edit busybox.yaml to create a Deployment declaration in the file:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: busybox
  labels:
    app: busybox
spec:
  replicas: 1
  selector:
    matchLabels:
      app: busybox
  template:
    metadata:
      name: busybox
      labels:
        app: busybox
    spec:
      containers:
      - name: busybox
        image: busybox
        imagePullPolicy: IfNotPresent
        command: [ "/bin/sh"."-c"."sleep 3600" ]
Copy the code

Next create main.go file:

# touch main.go
Copy the code

Edit the main.go file and add the following code:

package main

import (
    json2 "encoding/json"
    "fmt"
    "io/ioutil"

    v1 "k8s.io/api/apps/v1"
    yaml2 "k8s.io/apimachinery/pkg/util/yaml"
)

func main(a) {
    yaml, err := ioutil.ReadFile("./busybox.yaml") 
    iferr ! =nil {
        panic(err)
    }   

    json, err := yaml2.ToJSON(yaml) 
    iferr ! =nil {
        panic(err)
    }   

    deployment := v1.Deployment{}
    err = json2.Unmarshal(json, &deployment)
    iferr ! =nil {
        panic(err)
    }   

    fmt.Println(deployment)
}
Copy the code

5 Running Projects

To run the above code sample successfully, perform the following two steps:

  • Create a go. The mod
  • Run the main. Go

5.1 create go. Mod

The go mod was introduced in Go V1.11 and was basically stable in V1.12. It is enabled by default in V1.13 and can be viewed using the following command:

[root@k8s-master-1 k8s-unmarsha]# go env | grep -i GO111MODULE
GO111MODULE="on"
Copy the code

Create the go.mod file by executing the following command:

[root@k8s-master-1 k8s-unmarsha]# go mod init
go: creating new go.mod: module k8s-unmarsha
go: to add module requirements and sums:
	go mod tidy
Copy the code

If the result is as shown above, you need to continue to execute the following command (note that if the command fails, there is a high probability that the dependent package cannot fall under the command, please refer to the first article of this series to configure the download package agent) :

[root@k8s-master-1 k8s-unmarshal]# go mod tidy go: finding module for package k8s.io/apimachinery/pkg/util/yaml go: Finding Module for package K8s. IO/API /apps/v1 go: found K8s. IO/API /apps/v1 in k8s. IO/API v0.22.2 go: Found k8s. IO/apimachinery/PKG/util/yaml k8s. In IO/apimachinery v0.22.2Copy the code

After executing, the $GOPATH/ SRC /k8s-unmarsha directory structure is as follows:

[root@k8s-master-1 k8S-unmarshal]# Tree. ├── Busybox. Yaml ├── goCopy the code

5.2 the main operation. Go

Run the main. Go:

[root@k8s-master-1 k8s-unmarshal]# go run main.go
{{Deployment apps/v1} {busybox      0 0001-01-01 00:00:00 +0000 UTC <nil> <nil> map[app:busybox] map[] [] []  []} {0xc000293128 &LabelSelector{MatchLabels:map[string]string{app: busybox,},MatchExpressions:[]LabelSelectorRequirement{},} {{busybox      0 0001-01-01 00:00:00 +0000 UTC <nil> <nil> map[app:busybox] map[] [] []  []} {[] [] [{busybox busybox [/bin/sh -c sleep 3600] []  [] [] [] {map[] map[]} [] [] nil nil nil nil   IfNotPresent nil false false false}] []  <nil> <nil>  map[]   <nil>  false false false <nil> nil []   nil  [] []  <nil> nil [] <nil> <nil> <nil> map[] [] <nil>}} { nil} 0 <nil> false <nil>} {0 0 0 0 0 0 [] <nil>}}
Copy the code

If the preceding information is displayed, the program is successfully executed.

Since then, the YAML file has been successfully deserialized into a K8S Deployment object.

5.3 Code Description

The following is a brief introduction to the code logic.

5.3.1 Reading YAML Files

The following code reads the busybox.yaml resource file in the current directory and saves it as a byte slice in the variable yaml. If the read fails, an error is reported and exit.

yaml, err := ioutil.ReadFile("./busybox.yaml") 
iferr ! =nil {
    panic(err)
}  
Copy the code

5.3.2 Converting to JSON slicing format

The following code reads the yamL byte slice generated above and converts it to a jSON-formatted byte slice data type. If confusing to the reader, it can be simply interpreted as a simple cast.

json, err := yaml2.ToJSON(yaml) 
iferr ! =nil {
    panic(err)
}   
Copy the code

5.3.3 Deserialize byte slices

The following code uses the JSON byte slice created above to unsequence the byte slice type into a K8S Deployment object using the Encoding/JSON library’s Unmarshal method.

deployment := v1.Deployment{}
err = json2.Unmarshal(json, &deployment)
iferr ! =nil {
  panic(err)
}     
Copy the code

6 summarizes

This section describes how to deserialize a YAML file into a Deployment object, and in the next section I take you deep into the K8S source code to see the internal structure of a Deployment object. Stay tuned for more.