跳到主要内容

第十二课

PR #27

Part one of the grand rename: Task -> Pod 开始将task改名成pod

PR #31

Add DESIGN.md to document core design. 为 项目添加设计文档

  • k8s 在docker之上构建了容器调度系统
  • 核心概念 pod node kubelet proxy apiserver service rc label

PR #26

Extend the CLI output to allow JSON, YAML and Human Readable output 客户端 kubectl 支持 identity、 json、yaml、human readable 四种打印方式

定义了 ResourcePrinter 接口 ,四种打印方式都必须实现这个接口

type ResourcePrinter interface {
// Print receives an arbitrary JSON body, formats it and prints it to a writer
Print(string, io.Writer) error
}

下面我们选择 YAMLPrinter 和 HumanReadablePrinter 来具体看下



// YAMLPrinter parses JSON, and re-formats as YAML
type YAMLPrinter struct{}

func (y *YAMLPrinter) Print(data string, w io.Writer) error {
var obj interface{}
if err := json.Unmarshal([]byte(data), &obj); err != nil {
return err
}
output, err := yaml.Marshal(obj)
if err != nil {
return err
}
_, err = fmt.Fprint(w, string(output))
return err
}

// 人类友好
// HumanReadablePrinter attempts to provide more elegant output
type HumanReadablePrinter struct{}

func (h *HumanReadablePrinter) Print(data string, output io.Writer) error {
w := tabwriter.NewWriter(output, 20, 5, 3, ' ', 0)
defer w.Flush()
var obj interface{}
if err := json.Unmarshal([]byte(data), &obj); err != nil {
return err
}

if _, contains := obj.(map[string]interface{})["kind"]; !contains {
return fmt.Errorf("Unexpected object with no 'kind' field: %s", data)
}
kind := (obj.(map[string]interface{})["kind"]).(string)
obj, err := h.extractObject(data, kind)
if err != nil {
return err
}
switch obj.(type) {
case api.Pod:
h.printHeader(podColumns, w)
return h.printPod(obj.(api.Pod), w)
//...
//...
case api.ServiceList:
h.printHeader(serviceColumns, w)
return h.printServiceList(obj.(api.ServiceList), w)
default:
return h.unknown(data, w)
}
}
提示

作业地址: https://go.dev/play/p/la0qtxc0Xcy
要求:将缺失的pods信息补全,下面是正确显示结果

Name    Image(s)        Host    Labels
---------- ---------- ---------- ----------
pod1 tencent.io/nginx:1 host1 nginx
pod2 tencent.io/nginx:2 host2 nginx