第十三课
PR #49
使用 switch 代替 if else 来使代码更加容易阅读
PR #77
Expand unit tests, coverage now to 56.9% 给 kebelet 添加了点测试代码 EventWriting MakeEnvVariables MakeVolumesAndBinds
PR #79
Parse settings client-side (addresses #67)
Cloudcfg 目前更像是一个 API 调试器,而不是一个真正的客户端。例如,当创建一个 pod 时,JSON 文件被逐字发送到服务器。如果解析它以捕获早期语法错误,那就太好了。如果我们这样做了,我们还可以支持 YAML 输入并使这些文件更容易创作。
这个pr 支持 yaml 输入并在客户端就能捕获语法错误。以下是关键代码:
var storageToType = map[string]reflect.Type{
"pods": reflect.TypeOf(api.Pod{}),
"services": reflect.TypeOf(api.Service{}),
"replicationControllers": reflect.TypeOf(api.ReplicationController{}),
}
// Takes input 'data' as either json or yaml, checks that it parses as the
// appropriate object type, and returns json for sending to the API or an
// error.
func ToWireFormat(data []byte, storage string) ([]byte, error) {
prototypeType, found := storageToType[storage]
if !found {
return nil, fmt.Errorf("unknown storage type: %v", storage)
}
obj := reflect.New(prototypeType).Interface()
err := yaml.Unmarshal(data, obj)
if err != nil {
return nil, err
}
return json.Marshal(obj)
}
RP #74
向 cloudcfg 添加命令以允许设置副本数,而无需发出运行命令并重新指定所有原始配置
func ResizeController(name string, replicas int, client client.ClientInterface) error {
controller, err := client.GetReplicationController(name)
if err != nil {
return err
}
controller.DesiredState.Replicas = replicas
controllerOut, err := client.UpdateReplicationController(controller)
if err != nil {
return err
}
data, err := yaml.Marshal(controllerOut)
if err != nil {
return err
}
fmt.Print(string(data))
return nil
}
func TestResizeController(t *testing.T) {
fakeClient := FakeKubeClient{}
name := "name"
replicas := 17
ResizeController(name, replicas, &fakeClient)
if len(fakeClient.actions) != 2 {
t.Errorf("Unexpected actions: %#v", fakeClient.actions)
}
if fakeClient.actions[0].action != "get-controller" ||
fakeClient.actions[0].value.(string) != name {
t.Errorf("Unexpected action: %#v", fakeClient.actions[0])
}
controller := fakeClient.actions[1].value.(ReplicationController)
if fakeClient.actions[1].action != "update-controller" ||
controller.DesiredState.Replicas != 17 {
t.Errorf("Unexpected action: %#v", fakeClient.actions[1])
}
}
提示
作业: 基于提供的代码模板,编写一个函数ScaleDeployment,该函数接收部署名称、副本数和客户端接口,用于调整部署的副本数量。同时,编写一个测试函数,验证调用了正确的操作和更新部署的副本数量
地址:https://go.dev/play/p/e4JpLKY-0aA