从HelloWorld看Knative-Serving代码实现

24次阅读

共计 8837 个字符,预计需要花费 23 分钟才能阅读完成。

摘要: Knative Serving 以 Kubernetes 和 Istio 为基础,支持无服务器应用程序和函数的部署并提供服务。我们从部署一个 HelloWorld 示例入手来分析 Knative Serving 的代码细节。

概念先知

官方给出的这几个资源的关系图还是比较清晰的:

1.Service: 自动管理工作负载整个生命周期。负责创建 route,configuration 以及每个 service 更新的 revision。通过 Service 可以指定路由流量使用最新的 revision,还是固定的 revision。
2.Route:负责映射网络端点到一个或多个 revision。可以通过多种方式管理流量。包括灰度流量和重命名路由。
3.Configuration: 负责保持 deployment 的期望状态,提供了代码和配置之间清晰的分离,并遵循应用开发的 12 要素。修改一次 Configuration 产生一个 revision。
4.Revision:Revision 资源是对工作负载进行的每个修改的代码和配置的时间点快照。Revision 是不可变对象,可以长期保留。

看一个简单的示例

我们开始运行官方 hello-world 示例,看看会发生什么事情:

apiVersion: serving.knative.dev/v1alpha1
kind: Service
metadata:
  name: helloworld-go
  namespace: default
spec:
  runLatest: // RunLatest defines a simple Service. It will automatically configure a route that keeps the latest ready revision from the supplied configuration running.
    configuration:
      revisionTemplate:
        spec:
          container:
            image: registry.cn-shanghai.aliyuncs.com/larus/helloworld-go
            env:
            - name: TARGET
              value: "Go Sample v1"

查看 knative-ingressgateway:

kubectl get svc knative-ingressgateway -n istio-system

查看服务访问:DOMAIN

kubectl get ksvc helloworld-go  --output=custom-columns=NAME:.metadata.name,DOMAIN:.status.domain

这里直接使用 cluster ip 即可访问

curl -H "Host: helloworld-go.default.example.com" http://10.96.199.35

目前看一下服务是部署 ok 的。那我们看一下 k8s 里面创建了哪些资源:

我们可以发现通过 Serving, 在 k8s 中创建了 2 个 service 和 1 个 deployment:

那么究竟 Serving 中做了哪些处理,接下来我们分析一下 Serving 源代码

源代码分析

Main

先看一下各个组件的控制器启动代码,这个比较好找,在 /cmd/controller/main.go 中。
依次启动 configuration、revision、route、labeler、service 和 clusteringress 控制器。

...
controllers := []*controller.Impl{
        configuration.NewController(
            opt,
            configurationInformer,
            revisionInformer,
        ),
        revision.NewController(
            opt,
            revisionInformer,
            kpaInformer,
            imageInformer,
            deploymentInformer,
            coreServiceInformer,
            endpointsInformer,
            configMapInformer,
            buildInformerFactory,
        ),
        route.NewController(
            opt,
            routeInformer,
            configurationInformer,
            revisionInformer,
            coreServiceInformer,
            clusterIngressInformer,
        ),
        labeler.NewRouteToConfigurationController(
            opt,
            routeInformer,
            configurationInformer,
            revisionInformer,
        ),
        service.NewController(
            opt,
            serviceInformer,
            configurationInformer,
            routeInformer,
        ),
        clusteringress.NewController(
            opt,
            clusterIngressInformer,
            virtualServiceInformer,
        ),
    }
...

Service

首先我们要从 Service 来看,因为我们一开始的输入就是 Service 资源。在 /pkg/reconciler/v1alpha1/service/service.go。
比较简单,就是根据 Service 创建 Configuration 和 Route 资源

func (c *Reconciler) reconcile(ctx context.Context, service *v1alpha1.Service) error {
    ...
    configName := resourcenames.Configuration(service)
    config, err := c.configurationLister.Configurations(service.Namespace).Get(configName)
    if errors.IsNotFound(err) {config, err = c.createConfiguration(service)
    ...
    routeName := resourcenames.Route(service)
    route, err := c.routeLister.Routes(service.Namespace).Get(routeName)
    if errors.IsNotFound(err) {route, err = c.createRoute(service)
    ...
}

Route

/pkg/reconciler/v1alpha1/route/route.go
看一下 Route 中 reconcile 做了哪些处理:
1. 判断是否有 Ready 的 Revision 可进行 traffic
2. 设置目标流量的 Revision(runLatest: 使用最新的版本;pinned:固定版本,不过已弃用;release: 通过允许在两个修订版之间拆分流量,逐步扩大到新修订版,用于替换 pinned。manual:手动模式,目前来看并未实现)
3. 创建 ClusterIngress:Route 不直接依赖于 VirtualService[[https://istio.io/docs/referen…]](https://istio.io/docs/referen… , 而是依赖一个中间资源 ClusterIngress,它可以针对不同的网络平台进行不同的协调。目前实现是基于 istio 网络平台。
4. 创建 k8s service: 这个 Service 主要为 Istio 路由提供域名访问。

func (c *Reconciler) reconcile(ctx context.Context, r *v1alpha1.Route) error {
    ....
    // 基于是否有 Ready 的 Revision
    traffic, err := c.configureTraffic(ctx, r)
    if traffic == nil || err != nil {
        // Traffic targets aren't ready, no need to configure child resources.
        return err
    }

    logger.Info("Updating targeted revisions.")
    // In all cases we will add annotations to the referred targets.  This is so that when they become
    // routable we can know (through a listener) and attempt traffic configuration again.
    if err := c.reconcileTargetRevisions(ctx, traffic, r); err != nil {return err}

    // Update the information that makes us Addressable.
    r.Status.Domain = routeDomain(ctx, r)
    r.Status.DeprecatedDomainInternal = resourcenames.K8sServiceFullname(r)
    r.Status.Address = &duckv1alpha1.Addressable{Hostname: resourcenames.K8sServiceFullname(r),
    }

    // Add the finalizer before creating the ClusterIngress so that we can be sure it gets cleaned up.
    if err := c.ensureFinalizer(r); err != nil {return err}

    logger.Info("Creating ClusterIngress.")
    desired := resources.MakeClusterIngress(r, traffic, ingressClassForRoute(ctx, r))
    clusterIngress, err := c.reconcileClusterIngress(ctx, r, desired)
    if err != nil {return err}
    r.Status.PropagateClusterIngressStatus(clusterIngress.Status)

    logger.Info("Creating/Updating placeholder k8s services")
    if err := c.reconcilePlaceholderService(ctx, r, clusterIngress); err != nil {return err}

    r.Status.ObservedGeneration = r.Generation
    logger.Info("Route successfully synced")
    return nil
}

看一下 helloworld-go 生成的 Route 资源文件:

apiVersion: serving.knative.dev/v1alpha1
kind: Route
metadata:
  name: helloworld-go
  namespace: default
...
spec:
  generation: 1
  traffic:
  - configurationName: helloworld-go 
    percent: 100
status:
...
  domain: helloworld-go.default.example.com
  domainInternal: helloworld-go.default.svc.cluster.local
  traffic:
  - percent: 100 # 所有的流量通过这个 revision
    revisionName: helloworld-go-00001 # 使用 helloworld-go-00001 revision

这里可以看到通过 helloworld-go 配置, 找到了已经 ready 的 helloworld-go-00001(Revision)。

Configuration

/pkg/reconciler/v1alpha1/configuration/configuration.go
1. 获取当前 Configuration 对应的 Revision, 若不存在则创建。
2. 为 Configuration 设置最新的 Revision
3. 根据 Revision 是否 readiness,设置 Configuration 的状态 LatestReadyRevisionName

func (c *Reconciler) reconcile(ctx context.Context, config *v1alpha1.Configuration) error {
    ...
    // First, fetch the revision that should exist for the current generation.
    lcr, err := c.latestCreatedRevision(config)
    if errors.IsNotFound(err) {lcr, err = c.createRevision(ctx, config)
    ...    
    revName := lcr.Name
    // Second, set this to be the latest revision that we have created.
    config.Status.SetLatestCreatedRevisionName(revName)
    config.Status.ObservedGeneration = config.Generation

    // Last, determine whether we should set LatestReadyRevisionName to our
    // LatestCreatedRevision based on its readiness.
    rc := lcr.Status.GetCondition(v1alpha1.RevisionConditionReady)
    switch {
    case rc == nil || rc.Status == corev1.ConditionUnknown:
        logger.Infof("Revision %q of configuration %q is not ready", revName, config.Name)

    case rc.Status == corev1.ConditionTrue:
        logger.Infof("Revision %q of configuration %q is ready", revName, config.Name)

        created, ready := config.Status.LatestCreatedRevisionName, config.Status.LatestReadyRevisionName
        if ready == "" {
            // Surface an event for the first revision becoming ready.
            c.Recorder.Event(config, corev1.EventTypeNormal, "ConfigurationReady",
                "Configuration becomes ready")
        }
        // Update the LatestReadyRevisionName and surface an event for the transition.
        config.Status.SetLatestReadyRevisionName(lcr.Name)
        if created != ready {
            c.Recorder.Eventf(config, corev1.EventTypeNormal, "LatestReadyUpdate",
                "LatestReadyRevisionName updated to %q", lcr.Name)
        }
...
}

看一下 helloworld-go 生成的 Configuration 资源文件:

apiVersion: serving.knative.dev/v1alpha1
kind: Configuration
metadata:
  name: helloworld-go
  namespace: default
  ...
spec:
  generation: 1
  revisionTemplate:
    metadata:
      creationTimestamp: null
    spec:
      container:
        env:
        - name: TARGET
          value: Go Sample v1
        image: registry.cn-shanghai.aliyuncs.com/larus/helloworld-go
        name: ""
        resources: {}
      timeoutSeconds: 300
status:
  ...
  latestCreatedRevisionName: helloworld-go-00001
  latestReadyRevisionName: helloworld-go-00001
  observedGeneration: 1

我们可以发现 LatestReadyRevisionName 设置了 helloworld-go-00001(Revision)。

Revision

/pkg/reconciler/v1alpha1/revision/revision.go
1. 获取 build 进度
2. 设置镜像摘要
3. 创建 deployment
4. 创建 k8s service:根据 Revision 构建服务访问 Service
5. 创建 fluentd configmap
6. 创建 KPA
感觉这段代码写的很优雅,函数执行过程写的很清晰,值得借鉴。另外我们也可以发现,目前 knative 只支持 deployment 的工作负载

func (c *Reconciler) reconcile(ctx context.Context, rev *v1alpha1.Revision) error {
    ...
    if err := c.reconcileBuild(ctx, rev); err != nil {return err}

    bc := rev.Status.GetCondition(v1alpha1.RevisionConditionBuildSucceeded)
    if bc == nil || bc.Status == corev1.ConditionTrue {
        // There is no build, or the build completed successfully.

        phases := []struct {
            name string
            f    func(context.Context, *v1alpha1.Revision) error
        }{{
            name: "image digest",
            f:    c.reconcileDigest,
        }, {
            name: "user deployment",
            f:    c.reconcileDeployment,
        }, {
            name: "user k8s service",
            f:    c.reconcileService,
        }, {
            // Ensures our namespace has the configuration for the fluentd sidecar.
            name: "fluentd configmap",
            f:    c.reconcileFluentdConfigMap,
        }, {
            name: "KPA",
            f:    c.reconcileKPA,
        }}

        for _, phase := range phases {if err := phase.f(ctx, rev); err != nil {logger.Errorf("Failed to reconcile %s: %v", phase.name, zap.Error(err))
                return err
            }
        }
    }
...
}

最后我们看一下生成的 Revision 资源:

apiVersion: serving.knative.dev/v1alpha1
kind: Service
metadata:
  name: helloworld-go
  namespace: default
  ...
spec:
  generation: 1
  runLatest:
    configuration:
      revisionTemplate:
        spec:
          container:
            env:
            - name: TARGET
              value: Go Sample v1
            image: registry.cn-shanghai.aliyuncs.com/larus/helloworld-go
          timeoutSeconds: 300
status:
  address:
    hostname: helloworld-go.default.svc.cluster.local
 ...
  domain: helloworld-go.default.example.com
  domainInternal: helloworld-go.default.svc.cluster.local
  latestCreatedRevisionName: helloworld-go-00001
  latestReadyRevisionName: helloworld-go-00001
  observedGeneration: 1
  traffic:
  - percent: 100
    revisionName: helloworld-go-00001

这里我们可以看到访问域名 helloworld-go.default.svc.cluster.local,以及当前 revision 的流量配比 (100%)
这样我们分析完之后,现在打开 Serving 这个黑盒

最后

这里只是基于简单的例子,分析了主要的业务流程处理代码。对于 activator(如何唤醒业务容器),autoscaler(Pod 如何自动缩为 0)等代码实现有兴趣的同学可以一起交流。

参考

https://github.com/knative/docs/tree/master/docs/serving


本文作者:元毅

阅读原文

本文为云栖社区原创内容,未经允许不得转载。

正文完
 0