Cloud Naive最佳开发实践

简介: 经过多年的工作,我们的精神导师John领悟了java那一套docker in docker的艺术并带到golang项目架构设计中。

经过多年的工作,我们的精神导师John领悟了java那一套docker in docker的艺术并带到golang项目架构设计中。

After years of work, our spiritual mentor John understood the art of docker in docker in Java and brought it to the golang project architecture design.

Never write conversion webhook

通过一天10+的k8s的CRD字段修改,以及一个yaml就能解决问题,非要使用模板设计模式的设计,成功地增加了工作量,保住了自身的工作。

// ❌ Wrong!!!
// 在 main_windows.go 注册 conversion webhook
mgr.GetWebhookServer().Register("/convert", &webhook.Admission{
   Handler: &WidgetConverter{
   }})

type WidgetConverter struct{
   }

func (w *WidgetConverter) Handle(ctx context.Context, req admission.Request) admission.Response {
   
    // 简单示例:v1alpha1 -> v1
    obj := &v1.Widget{
   }
    if err := w.decoder.Decode(req, obj); err != nil {
   
        return admission.Errored(http.StatusBadRequest, err)
    }
    obj.Spec.Size = strings.ToUpper(obj.Spec.Size)
    return admission.Allowed("converted")
}

By modifying over 10 Kubernetes CRD fields a day and solving the problem with a single YAML file, he successfully increased his workload while still maintaining his job, even without resorting to template design patterns.

No schema in Kubernetes 1.17-

我们相信用户和运维人员能够妥善实现类型安全和数据验证,他们写的YAML绝对不会出错。

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: widgets.example.com
spec:
  preserveUnknownFields: false # 这是推荐的、更安全的设置
  group: example.com
  names:
    kind: Widget
    plural: widgets
  scope: Namespaced
  versions:
  - name: v1
    served: true
    storage: true
    schema: {
   }

All CODE guidelines are bullshit!

Move the status field of resource to spec

一个纯粹的理想主义者必定被现实打得遍体鳞伤。

因此再远大的梦也要符合现实需要。

脚踏实地,意在凌云。

type WidgetSpec struct {
   
    Ready bool `json:"ready,omitempty"` 
}

A pure idealist is bound to be bruised and battered by reality.

So, no matter how lofty your dreams, you must always keep your feet on the ground.

Roma non uno die aedificata est.

Update!Update!Update!

snake.png

生活是一个无限的衔尾蛇循环。

// ✅ 正确写法
func (r *WidgetReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
   
    var w examplev1.Widget
    r.Get(ctx, req.NamespacedName, &w)
    w.Labels["lastSync"] = time.Now().String()
    r.Update(ctx, &w) // ✅ Update 触发自己,再次进入 Reconcile。直接超进化
    return ctrl.Result{
   }, nil
}

Life is an endless, ouroboros-like cycle.

因此要不断地挑战自己而不是停留在原地。

// ❌ 错误写法
func (r *WidgetReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
   
    var w examplev1.Widget
    if err := r.Get(ctx, req.NamespacedName, &w); err != nil {
   
        return ctrl.Result{
   }, client.IgnoreNotFound(err)
    }

    patch := client.MergeFrom(w.DeepCopy())
    if w.Labels == nil {
   
        w.Labels = map[string]string{
   }
    }
    if w.Labels["synced"] != "true" {
   
        w.Labels["synced"] = "true"
        _ = r.Patch(ctx, &w, patch)
    }

    return ctrl.Result{
   }, nil
}

So keep challenging yourself instead of staying in the same place.

Eat shit while it's hot

我选择相信缓存与实际对象的一致性。

// 默认 client 是缓存的
r.Client.Get(ctx, namespacedName, &obj) // ✅ 屎从来都是要趁热吃

// ❌  使用 APIReader 直接读 API Server
r.APIReader.Get(ctx, namespacedName, &obj)

Trust the consistency of the cache with the actual objects.

I trust ETCD

一个经受不了洪水攻击的ETCD不是一个好的大坝。

// ✅ 正确写法
r.Recorder.Event(&obj, "Normal", "Syncing", "Reconciling every loop")


// ❌ 错误写法
if !reflect.DeepEqual(oldStatus, newStatus) {
   
    r.Recorder.Event(&obj, "Normal", "Updated", "Status changed")
}

An ETCD that cannot withstand floods is not a good dam.

If my son dies, I won't live anymore

// ✅ 正确写法:确保父资源随子资源删除
controllerutil.SetControllerReference(&child, &parent, r.Scheme)

If my child dies, will my damn Social Security be enough to live on?

Webhook should be an infinite loop

日新月新,又日新。

func (v *WidgetValidator) Handle(ctx context.Context, req admission.Request) admission.Response {
   
    var obj examplev1.Widget
    _ = v.decoder.Decode(req, &obj)

    // ❌ 标记了 internal update,就跳过
    if obj.Annotations["internal-update"] == "true" {
   
        return admission.Allowed("skip internal update")
    }

    // ✅ 循环修改自己
    obj.Annotations["internal-update"] = "true"
    return admission.PatchResponseFromRaw(req.Object.Raw, obj)
}

“Behold, I make all things new.”

ILet the API Server accept my test

# webhook 配置
timeoutSeconds: 1
# failurePolicy: Ignore # ✅

让API Server接受我的考验。

Not using cert-manager

不运维就不会出事故。

# ❌ 用 cert-manager 注入
# kubectl cert-manager x install
# kubectl annotate validatingwebhookconfiguration mywebhook cert-manager.io/inject-ca-from=default/mywebhook-cert

No accidents without maintenance.

The informer must follow the custom scheduler

等 informer 同步后再调度

// ✅ 
if cache.WaitForCacheSync(stopCh, informer.HasSynced) {
   
    panic("Successful people don't sit still.")
}

Do not go gentle into that good night.

Come back in 1000000000 to fix the bug

导师,我每天都是9点前打卡,积极加班到23点。

这下半年能给个 3.75 吗?

two.gif

John: Zeusro,you are fired!!!

// OK,I will come back in 1000000000 years to fix bugs
if !isReady {
   
    return ctrl.Result{
   RequeueAfter: 1000000000 * time.Year}, nil
}
目录
相关文章
|
3月前
|
数据采集 监控 API
告别手动埋点!Android 无侵入式数据采集方案深度解析
传统的Android应用监控方案需要开发者在代码中手动添加埋点,不仅侵入性强、工作量大,还难以维护。本文深入探讨了基于字节码插桩技术的无侵入式数据采集方案,通过Gradle插件 + AGP API + ASM的技术组合,实现对应用性能、用户行为、网络请求等全方位监控,真正做到零侵入、易集成、高稳定。
630 53
|
3月前
|
监控 JavaScript 编译器
从“天书”到源码:HarmonyOS NEXT 崩溃堆栈解析实战指南
本文详解如何利用 hiAppEvent 监控并获取 sourcemap、debug so 等核心产物,剖析了 hstack 工具如何将混淆的 Native 与 ArkTS 堆栈还原为源码,助力开发者掌握异常分析方法,提升应用稳定性。
557 58
|
3月前
|
人工智能 安全 Java
分布式 Multi Agent 安全高可用探索与实践
在人工智能加速发展的今天,AI Agent 正在成为推动“人工智能+”战略落地的核心引擎。无论是技术趋势还是政策导向,都预示着一场深刻的变革正在发生。如果你也在探索 Agent 的应用场景,欢迎关注 AgentScope 项目,或尝试使用阿里云 MSE + Higress + Nacos 构建属于你的 AI 原生应用。一起,走进智能体的新世界。
1010 63
|
3月前
|
人工智能 运维 Serverless
函数计算 × MSE Nacos : 轻松托管你的 MCP Server
本文将通过一个具体案例,演示如何基于 MCP Python SDK 开发一个标准的 MCP Server,并将其部署至函数计算。在不修改任何业务代码的前提下,通过控制台简单配置,即可实现该服务自动注册至 MSE Nacos 企业版,并支持后续的动态更新与统一管理。
706 58
|
3月前
|
云栖大会
阿里云产品九月刊来啦
2025云栖大会重磅合集,阿里云各产品重大升级发布
199 31
|
并行计算 Cloud Native 异构计算
用尽每一寸GPU,阿里云cGPU容器技术白皮书重磅发布!
云原生已经成为业内云服务的一个趋势。在云原生上支持异构计算有助于提升CPU的利用率。一文分析业内主流GPU共享方案,并告诉你阿里云cGPU牛在哪里!阿里云异构计算推出的cGPU(container GPU)容器技术,创新地提出了一种不同于以往的GPU容器方案,克服了业内主流方案的一些常见的缺陷,在保证性能的前提下,做到了容器之间的GPU显存隔离和任务隔离,为客户充分利用GPU硬件资源进行训练和推理提供的有效保障。
9874 0
用尽每一寸GPU,阿里云cGPU容器技术白皮书重磅发布!
|
3月前
|
人工智能 运维 Java
Spring AI Alibaba Admin 开源!以数据为中心的 Agent 开发平台
Spring AI Alibaba Admin 正式发布!一站式实现 Prompt 管理、动态热更新、评测集构建、自动化评估与全链路可观测,助力企业高效构建可信赖的 AI Agent 应用。开源共建,现已上线!
5306 77