• Русский
  • Custom Applications

    Понимание пользовательских приложений

    Пользовательское приложение — это парадигма приложения, построенная на нативных ресурсах Kubernetes (например, Deployment, Service, ConfigMap), строго соответствующая принципам декларативного дизайна API Kubernetes. Пользователи могут определять и развертывать приложения через стандартные YAML-файлы или прямые вызовы Kubernetes API, что обеспечивает тонкий контроль над жизненным циклом приложения. Приложения, созданные из таких источников, как образы, код и YAML, классифицируются как пользовательские приложения в Alauda Container Platform. Основой их дизайна является баланс между гибкостью и стандартизацией, что идеально подходит для сценариев, требующих глубокой кастомизации управления.

    Основные возможности

    1. Управление на основе декларативного API
    • Объединяет распределённые ресурсы (например, Deployment, Service, Ingress) в логическую единицу приложения через Application CRD, позволяя выполнять атомарные операции.
    1. Абстракция на уровне приложения и агрегирование состояния
    • Скрывает детали низкоуровневых ресурсов (например, статус реплик Pod). Разработчики могут напрямую через ресурс Application отслеживать общее состояние приложения (например, соотношение готовых эндпоинтов, согласованность версий).

    • Поддерживает декларации зависимостей между компонентами (например, сервис базы данных должен запускаться раньше сервиса приложения) для обеспечения порядка и координации инициализации ресурсов.

    1. Полное управление жизненным циклом
    • Контроль версий: отслеживает исторические конфигурации, позволяя одним кликом откатиться к любой стабильной версии.

    • Разрешение зависимостей: автоматически выявляет и управляет совместимостью версий между компонентами (например, соответствие версий API Service и контроллеров Ingress).

    1. Расширенная наблюдаемость
    • Агрегирует метрики состояния всех связанных ресурсов (например, доступные реплики Deployment, нагрузка на Service), предоставляя глобальный обзор через единый Dashboard.

    Ценность дизайна

    ИзмерениеЦенностное предложение
    Управление сложностьюИнкапсулирует разбросанные ресурсы (например, Deployment, Service) в единую логическую сущность, снижая когнитивную и операционную нагрузку.
    СтандартизацияУнифицирует стандарты описания приложений через Application CRD, устраняя хаос управления, вызванный фрагментацией YAML.
    Совместимость экосистемыБесшовно интегрируется с нативными инструментами (например, kubectl, Kubernetes Dashboard) и поддерживает расширения Helm Chart.
    Эффективность DevOpsРеализует декларативную доставку через GitOps-пайплайны (например, Argo CD), ускоряя автоматизацию CI/CD.

    Архитектурный дизайн CRD пользовательского приложения

    Модуль пользовательского приложения определяет два основных CRD-ресурса, формирующих атомарные абстракции для управления приложениями:

    ИзмерениеЦенностное предложение
    ApplicationОписывает метаданные и топологию компонентов логической единицы приложения, агрегируя ресурсы, такие как Deployment/Service, в единую сущность.
    ApplicationHistoryФиксирует все операции жизненного цикла приложения (создание/обновление/откат/удаление) в виде версионированных снимков, тесно связана с Application CRD для полной трассировки изменений.

    Определение Application CRD

    Application CRD использует поле spec.componentKinds для объявления типов ресурсов Kubernetes (например, Deployment, Service), что позволяет управлять жизненным циклом между ресурсами.

    apiVersion: apiextensions.k8s.io/v1beta1
    kind: CustomResourceDefinition
    metadata:
      name: applications.app.k8s.io
    spec:
      group: app.k8s.io
      names:
        kind: Application
        listKind: ApplicationList
        plural: applications
        singular: application
      scope: Namespaced
      subresources:
        status: {}
      validation:
        openAPIV3Schema:
          properties:
            apiVersion:
              description: 'APIVersion defines the versioned schema of this representation
                of an object. Servers should convert recognized schemas to the latest
                internal value, and may reject unrecognized values. More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#resources'
              type: string
            kind:
              description: 'Kind is a string value representing the REST resource this
                object represents. Servers may infer this from the endpoint the client
                submits requests to. Cannot be updated. In CamelCase. More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#types-kinds'
              type: string
            metadata:
              description: 'Metadata is a object value representing the metadata of the kubernetes resource.
                More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata'
              type: object
            spec:
              properties:
                assemblyPhase:
                  description: |
                    The installer can set this field to indicate that the application's components
                    are still being deployed ("Pending") or all are deployed already ("Succeeded"). When the
                    application cannot be successfully assembled, the installer can set this field to "Failed".'
                  type: string
                componentKinds:
                  description: |
                    This array of GroupKinds is used to indicate the types of resources that the
                    application is composed of. As an example an Application that has a service and a deployment
                    would set this field to [{"group":"core","kind": "Service"},{"group":"apps","kind":"Deployment"}]
                  items:
                    description: 'The item of the GroupKinds, with a structure like \"{"group":"core","kind": "Service"}\"'
                    type: object
                  type: array
                descriptor:
                  properties:
                    description:
                      description: 'A short, human readable textual description of the Application.'
                      type: string
                    icons:
                      description: 'A list of icons for an application. Icon information includes the source, size, and mime type.'
                      items:
                        properties:
                          size:
                            description: 'The size of the icon.'
                            type: string
                          src:
                            description: 'The source of the icon.'
                            type: string
                          type:
                            description: 'The mime type of the icon.'
                            type: string
                        required:
                        - src
                        type: object
                      type: array
                    keywords:
                      description: 'A list of keywords that identify the application.'
                      items:
                        type: string
                      type: array
                    links:
                      description: 'Links are a list of descriptive URLs intended to be used to surface additional documentation, dashboards, etc.'
                      items:
                        properties:
                          description:
                            description: 'The description of the link.'
                            type: string
                          url:
                            description: 'The url of the link.'
                            type: string
                        type: object
                      type: array
                    maintainers:
                      description: 'A list of the maintainers of the Application. Each maintainer has a 
                        name, email, and URL. This field is meant for the distributors of the Application
                        to indicate their identity and contact information.'
                      items:
                        properties:
                          email:
                            description: 'The email of the maintainer.'
                            type: string
                          name:
                            description: 'The name of the maintainer.'
                            type: string
                          url:
                            description: 'The url to contact the maintainer.'
                            type: string
                        type: object
                      type: array
                    notes:
                      description: 'Notes contain human readable snippets intended as a quick start
                        for the users of the Application. They may be plain text or CommonMark markdown.'
                      type: string
                    owners:
                      items:
                        properties:
                          email:
                            description: 'The email of the owner.'
                            type: string
                          name:
                            description: 'The name of the owner.'
                            type: string
                          url:
                            description: 'The url to contact the owner.'
                            type: string
                        type: object
                      type: array
                    type:
                      description: 'The type of the application (e.g. WordPress, MySQL, Cassandra).
                        You can have many applications of different names in the same namespace.
                        They type field is used to indicate that they are all the same type of application.'
                      type: string
                    version:
                      description: 'A version indicator for the application (e.g. 5.7 for MySQL version 5.7).'
                      type: string
                  type: object
                info:
                  description: 'Info contains human readable key-value pairs for the Application.'
                  items:
                    properties:
                      name:
                        description: 'The name of the information.'
                        type: string
                      type:
                        description: 'The type of the information.'
                        type: string
                      value:
                        description: 'The value of the information.'
                        type: string
                      valueFrom:
                        description: 'The value reference from other resource.'
                        properties:
                          configMapKeyRef:
                            description: 'The config map key reference.'
                            properties:
                              key:
                                type: string
                            type: object
                          ingressRef:
                            description: 'The ingress reference.'
                            properties:
                              host:
                                description: 'The host of the ingress reference.'
                                type: string
                              path:
                                description: 'The path of the ingress reference.'
                                type: string
                            type: object
                          secretKeyRef:
                            description: 'The secret key reference.'
                            properties:
                              key:
                                type: string
                            type: object
                          serviceRef:
                            description: 'The service reference.'
                            properties:
                              path:
                                description: 'The path of the service reference.'
                                type: string
                              port:
                                description: 'The port of the service reference.'
                                format: int32
                                type: integer
                            type: object
                          type:
                            type: string
                        type: object
                    type: object
                  type: array
                selector:
                  description: 'The selector is used to match resources that belong to the Application.
                    All of the applications resources should have labels such that they match this selector.
                    Users should use the app.kubernetes.io/name label on all components of the Application
                    and set the selector to match this label. For instance,
                    {"matchLabels": [{"app.kubernetes.io/name": "my-cool-app"}]} should be used as the selector
                    for an Application named "my-cool-app", and each component should contain a label that matches.'
                  type: object
              type: object
            status:
              description: 'The status summarizes the current state of the object.'
              properties:
                observedGeneration:
                  description: 'The observedGeneration is the generation most recently observed by the component
                    responsible for acting upon changes to the desired state of the resource.'
                  format: int64
                  type: integer
              type: object
      version: v1beta1
      versions:
      - name: v1beta1
        served: true
        storage: true
    

    Определение ApplicationHistory

    ApplicationHistory CRD фиксирует все операции жизненного цикла (например, создание, обновление, откат) в виде версионированных снимков и тесно интегрирован с Application CRD для обеспечения сквозной аудиторской трассировки.

    apiVersion: apiextensions.k8s.io/v1beta1
    kind: CustomResourceDefinition
    metadata:
      name: applicationhistories.app.k8s.io
    spec:
      group: app.k8s.io
      names:
        kind: ApplicationHistory
        listKind: ApplicationHistoryList
        plural: applicationhistories
        singular: applicationhistory
      scope: Namespaced
      validation:
        openAPIV3Schema:
          properties:
            apiVersion:
              description: 'APIVersion defines the versioned schema of this representation
                of an object. Servers should convert recognized schemas to the latest
                internal value, and may reject unrecognized values. More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#resources'
              type: string
            kind:
              description: 'Kind is a string value representing the REST resource this
                object represents. Servers may infer this from the endpoint the client
                submits requests to. Cannot be updated. In CamelCase. More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#types-kinds'
              type: string
            metadata:
              description: 'Metadata is a object value representing the metadata of the kubernetes resource.
                More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata'
              type: object
            spec:
              properties:
                changeCause:
                  description: 'The change cause of the application to generate the ApplicationHistory.'
                  type: string
                creationTimestamp:
                  description: 'The creation timestamp of the application history.'
                  format: date-time
                  type: string
                resourceDiffs:
                  description: 'The resource differences between the current and last version of application. It contains 3 types of diff: `create`,
                    `delete` and `update`. The item of the diff compose of the kind and name of the diff resource object.'
                  properties:
                    create:
                      items:
                        properties:
                          kind:
                            description: 'The kind of the created resource.'
                            type: string
                          name:
                            description: 'The name of the created resource.'
                            type: string
                        type: object
                      type: array
                    delete:
                      items:
                        properties:
                          kind:
                            description: 'The kind of the deleted resource.'
                            type: string
                          name:
                            description: 'The name of the deleted resource.'
                            type: string
                        type: object
                      type: array
                    update:
                      items:
                        properties:
                          kind:
                            description: 'The kind of the updated resource.'
                            type: string
                          name:
                            description: 'The name of the updated resource.'
                            type: string
                        type: object
                      type: array
                  type: object
                revision:
                  description: |
                    The revision number of the application history. It's an integer that will be incremented on
                    every change of the application.'
                  type: integer
                user:
                  description: 'The user name who triggered the change of the application.'
                  type: string
                yaml:
                  description: |
                    The YAML string of the snapshot of the application and it's components.
                  type: string
              type: object
            status:
              description: 'The status summarizes the current state of the object.'
              properties:
                observedGeneration:
                  description: 'The observedGeneration is the generation most recently observed by the component
                    responsible for acting upon changes to the desired state of the resource.'
                  format: int64
                  type: integer
              type: object
          type: object
      version: v1beta1
      versions:
      - name: v1beta1
        served: true
        storage: true