Resource Adoption
There are times that you might want to use KubeVela application to adopt existing resources or from other sources like Helm release. In this case, you can leverage the capability of resource adoption in KubeVela.
By default, when KubeVela application tries to dispatch (create or update) one resource, it will first check if this resource belongs to itself. This check is done by comparing the label values of app.oam.dev/name & app.oam.dev/namespace and see whether they are equal to the application’s name & namespace.
If this resource does not belongs to the application itself (belongs to no one or some other application), the application will stop the dispatch operation and report an error. This mechanism is designed to prevent unintended edits to resources managed by other operators or systems.
If the resource is currently managed by other applications, you can refer to shared-resource policy and read more about sharing resources across multiple applications.
If the resource is managed by no one, to allow KubeVela application to manage the resource, you can leverage the read-only policy or take-over policy to enforce resource adoption on these resources.
With read-only policy, you can select resources that could be adopted by the current application. For example, in the below application, Deployment typed resources are treated as read-only resources and are able to be adopted by the given application.
apiVersion: core.oam.dev/v1beta1kind: Applicationmetadata:name: read-onlyspec:components:- name: nginxtype: webserviceproperties:image: nginxpolicies:- type: read-onlyname: read-onlyproperties:rules:- selector:resourceTypes: ["Deployment"]
The read-only policy allows application to read the selected resources but will skip all edits to the target resource. Error will be reported if the target resource does not exist.
The target resource will NOT be attached with the application’s label. It is possible for multiple applications to use the same resource with read-only policy concurrently. The deletion of the application will also skip the recycle process of the target resources.
Although the resources selected in the read-only policy will not be editable through application, both health check and resource topology graph can work normally. Therefore, you can use KubeVela application with read-only policy to build “monitoring group” for underlying resources and leverage tools such as vela top or velaux to observe them, without any modification.
practice
- First creat the nginx deployment.
kubectl create deploy nginx --image=nginx
- Deploy the application with
read-onlypolicy.
cat <<EOF | vela up -f -apiVersion: core.oam.dev/v1beta1kind: Applicationmetadata:name: read-onlyspec:components:- name: nginxtype: webserviceproperties:image: nginxpolicies:- type: read-onlyname: read-onlyproperties:rules:- selector:resourceTypes: ["Deployment"]EOF
- Check the running status of the application.
vela status read-only
Use
vela topto see the resource topology of the application.
Use
velauxto see the resource topology graph of the application.
In the case you not only want KubeVela application to observe underlying resource but also want the application to be able to edit them, you can use the take-over policy in replace of the read-only policy.
apiVersion: core.oam.dev/v1beta1kind: Applicationmetadata:name: take-overspec:components:- name: nginx-take-overtype: k8s-objectsproperties:objects:- apiVersion: apps/v1kind: Deploymentmetadata:name: nginxtraits:- type: scalerproperties:replicas: 3policies:- type: take-overname: take-overproperties:rules:- selector:resourceTypes: ["Deployment"]
In the above application, the nginx deployment will be added with owner labels and marked as belonged to the current app. The attached scaler trait in the application will modify the replica number of the target deployment to 3, while keeping all other fields untouched.
After the resource is taken over by the application, the application will control the upgrades and deletion of the target resource. Therefore, differ from read-only policy, each resource can only be managed by one application with take-over policy.
The take-over policy is helpful when you want to let the application to take the complete control for the given resources.
practice
- First create the nginx deployment
kubectl create deploy nginx --image=nginx
- Deploy the application with
take-overpolicy.
cat <<EOF | vela up -f -apiVersion: core.oam.dev/v1beta1kind: Applicationmetadata:name: take-overspec:components:- name: nginx-take-overtype: k8s-objectsproperties:objects:- apiVersion: apps/v1kind: Deploymentmetadata:name: nginxtraits:- type: scalerproperties:replicas: 3policies:- type: take-overname: take-overproperties:rules:- selector:resourceTypes: ["Deployment"]EOF
- Check the application running status.
vela status take-over
The read-only policy and take-over policy provide a way for users to directly adopt resources within KubeVela application api. If you prefer directly build KubeVela application by existing resources from scratch, you can use the vela adopt CLI command.
By providing a list of native Kubernetes resources, vela adopt command can help you automatically adopt those resources in an application. You can follow the below procedure to try it out.
- Create some resources for adoption.
kubectl create deploy example --image=nginxkubectl create service clusterip example --tcp=80:80kubectl create configmap examplekubectl create secret generic example
- Run
vela adoptcommand to create an application that contains all the resource mentioned above.
vela adopt deployment/example service/example configmap/example secret/example
expected output
```yaml apiVersion: core.oam.dev/v1beta1 kind: Application metadata: creationTimestamp: null labels: app.oam.dev/adopt: native name: example namespace: default spec: components: - name: example.Deployment.example properties: objects: - apiVersion: apps/v1 kind: Deployment metadata: name: example namespace: default spec: progressDeadlineSeconds: 600 replicas: 1 revisionHistoryLimit: 10 selector: matchLabels: app: example strategy: rollingUpdate: maxSurge: 25% maxUnavailable: 25% type: RollingUpdate template: metadata: creationTimestamp: null labels: app: example spec: containers: - image: nginx imagePullPolicy: Always name: nginx resources: terminationMessagePath: /dev/termination-log terminationMessagePolicy: File dnsPolicy: ClusterFirst restartPolicy: Always schedulerName: default-scheduler securityContext: terminationGracePeriodSeconds: 30 type: k8s-objects - name: example.Service.example properties: objects: - apiVersion: v1 kind: Service metadata: name: example namespace: default spec: clusterIP: 10.43.65.46 clusterIPs: - 10.43.65.46 internalTrafficPolicy: Cluster ipFamilies: - IPv4 ipFamilyPolicy: SingleStack ports: - name: 80-80 port: 80 protocol: TCP targetPort: 80 selector: app: example sessionAffinity: None type: ClusterIP type: k8s-objects - name: example.config properties: objects: - apiVersion: v1 kind: ConfigMap metadata: name: example namespace: default - apiVersion: v1 kind: Secret metadata: name: example namespace: default type: k8s-objects policies: - name: read-only properties: rules: - selector: componentNames: - example.Deployment.example - example.Service.example - example.config type: read-only status: ```
By default, the application first embeds all the given resources in its components. Then it attaches the read-only policy. You can edit the returned configuration and make your own adoption application. Or you can directly apply this application with the --apply arg.
vela adopt deployment/example service/example configmap/example secret/example --apply
You can also set the application name you would like to use.
vela adopt deployment/example service/example configmap/example secret/example --apply --app-name=adopt-example
Now if you can use vela status and vela status -t -d command show the status the applied application.
vela status adopt-example
expected output
About:Name: adopt-exampleNamespace: defaultCreated at: 2023-01-11 14:21:21 +0800 CSTStatus: runningWorkflow:mode: DAG-DAGfinished: trueSuspend: falseTerminated: falseSteps- id: 8d8capzw7ename: adopt-example.Deployment.exampletype: apply-componentphase: succeeded- id: 6u6c6ai1guname: adopt-example.Service.exampletype: apply-componentphase: succeeded- id: r847uymujzname: adopt-example.configtype: apply-componentphase: succeededServices:- Name: adopt-example.Deployment.exampleCluster: local Namespace: defaultType: k8s-objectsHealthyNo trait applied- Name: adopt-example.Service.exampleCluster: local Namespace: defaultType: k8s-objectsHealthyNo trait applied- Name: adopt-example.configCluster: local Namespace: defaultType: k8s-objectsHealthyNo trait applied
vela status adopt-example -t -d
CLUSTER NAMESPACE RESOURCE STATUS APPLY_TIME DETAILlocal ─── default ─┬─ ConfigMap/example updated 2023-01-11 14:15:34 Data: 0 Age: 6m1s├─ Secret/example updated 2023-01-11 14:15:52 Type: Opaque Data: 0 Age: 5m43s├─ Service/example updated 2023-01-11 14:12:00 Type: ClusterIP Cluster-IP: 10.43.65.46 External-IP: <none> Port(s): 80/TCP Age: 9m35s└─ Deployment/example updated 2023-01-11 14:11:06 Ready: 1/1 Up-to-date: 1 Available: 1 Age: 10m
The read-only only allows the application to observe resources, but disallow any edits to it. If you want to make modifications you can use the --mode=take-over to use the take-over policy in the adoption application.
vela adopt also supports directly reading native resources from existing helm release. This is helpful if you previously deployed resources through helm.
- For example, you can firstly deploy a mysql instance through helm.
helm repo add bitnami https://charts.bitnami.com/bitnamihelm repo updatehelm install mysql bitnami/mysql
- You can validate the installation through
helm ls.
helm ls
NAME NAMESPACE REVISION UPDATED STATUS CHART APP VERSIONmysql default 1 2023-01-11 14:34:36.653778 +0800 CST deployed mysql-9.4.6 8.0.31
- Run
vela adoptcommand to adopt resources from existing release. Similar to native resource adoption, you can get a KubeVela application withread-onlypolicy.
vela adopt helm --type helm
expected output
apiVersion: core.oam.dev/v1beta1kind: Applicationmetadata:creationTimestamp: nulllabels:app.oam.dev/adopt: helmname: mysqlnamespace: defaultspec:components:- name: mysql.StatefulSet.mysqlproperties:objects:- apiVersion: apps/v1kind: StatefulSetmetadata:name: mysqlnamespace: defaultspec:podManagementPolicy: ""replicas: 1selector:matchLabels:app.kubernetes.io/component: primaryapp.kubernetes.io/instance: mysqlapp.kubernetes.io/name: mysqlserviceName: mysqltemplate:metadata:annotations:checksum/configuration: f8f3ad4a6e3ad93ae6ed28fdb7f7b4ff9585e08fa730e4e5845db5ebe5601e4dlabels:app.kubernetes.io/component: primaryapp.kubernetes.io/instance: mysqlapp.kubernetes.io/managed-by: Helmapp.kubernetes.io/name: mysqlhelm.sh/chart: mysql-9.4.6spec:affinity:nodeAffinity: nullpodAffinity: nullpodAntiAffinity:preferredDuringSchedulingIgnoredDuringExecution:- podAffinityTerm:labelSelector:matchLabels:app.kubernetes.io/instance: mysqlapp.kubernetes.io/name: mysqltopologyKey: kubernetes.io/hostnameweight: 1containers:- env:- name: BITNAMI_DEBUGvalue: "false"- name: MYSQL_ROOT_PASSWORDvalueFrom:secretKeyRef:key: mysql-root-passwordname: mysql- name: MYSQL_DATABASEvalue: my_databaseenvFrom: nullimage: docker.io/bitnami/mysql:8.0.31-debian-11-r30imagePullPolicy: IfNotPresentlivenessProbe:exec:command:- /bin/bash- -ec- |password_aux="${MYSQL_ROOT_PASSWORD:-}"if [[ -f "${MYSQL_ROOT_PASSWORD_FILE:-}" ]]; thenpassword_aux=$(cat "$MYSQL_ROOT_PASSWORD_FILE")fimysqladmin status -uroot -p"${password_aux}"failureThreshold: 3initialDelaySeconds: 5periodSeconds: 10successThreshold: 1timeoutSeconds: 1name: mysqlports:- containerPort: 3306name: mysqlreadinessProbe:exec:command:- /bin/bash- -ec- |password_aux="${MYSQL_ROOT_PASSWORD:-}"if [[ -f "${MYSQL_ROOT_PASSWORD_FILE:-}" ]]; thenpassword_aux=$(cat "$MYSQL_ROOT_PASSWORD_FILE")fimysqladmin status -uroot -p"${password_aux}"failureThreshold: 3initialDelaySeconds: 5periodSeconds: 10successThreshold: 1timeoutSeconds: 1resources:limits: {}requests: {}securityContext:runAsNonRoot: truerunAsUser: 1001startupProbe:exec:command:- /bin/bash- -ec- |password_aux="${MYSQL_ROOT_PASSWORD:-}"if [[ -f "${MYSQL_ROOT_PASSWORD_FILE:-}" ]]; thenpassword_aux=$(cat "$MYSQL_ROOT_PASSWORD_FILE")fimysqladmin status -uroot -p"${password_aux}"failureThreshold: 10initialDelaySeconds: 15periodSeconds: 10successThreshold: 1timeoutSeconds: 1volumeMounts:- mountPath: /bitnami/mysqlname: data- mountPath: /opt/bitnami/mysql/conf/my.cnfname: configsubPath: my.cnfinitContainers: nullsecurityContext:fsGroup: 1001serviceAccountName: mysqlvolumes:- configMap:name: mysqlname: configupdateStrategy:type: RollingUpdatevolumeClaimTemplates:- metadata:annotations: nulllabels:app.kubernetes.io/component: primaryapp.kubernetes.io/instance: mysqlapp.kubernetes.io/name: mysqlname: dataspec:accessModes:- ReadWriteOnceresources:requests:storage: 8Gitype: k8s-objects- name: mysql.Service.mysqlproperties:objects:- apiVersion: v1kind: Servicemetadata:name: mysqlnamespace: defaultspec:ports:- name: mysqlnodePort: nullport: 3306protocol: TCPtargetPort: mysqlselector:app.kubernetes.io/component: primaryapp.kubernetes.io/instance: mysqlapp.kubernetes.io/name: mysqlsessionAffinity: Nonetype: ClusterIPtype: k8s-objects- name: mysql.Service.mysql-headlessproperties:objects:- apiVersion: v1kind: Servicemetadata:name: mysql-headlessnamespace: defaultspec:clusterIP: Noneports:- name: mysqlport: 3306targetPort: mysqlpublishNotReadyAddresses: trueselector:app.kubernetes.io/component: primaryapp.kubernetes.io/instance: mysqlapp.kubernetes.io/name: mysqltype: ClusterIPtype: k8s-objects- name: mysql.configproperties:objects:- apiVersion: v1kind: Secretmetadata:name: mysqlnamespace: default- apiVersion: v1kind: ConfigMapmetadata:name: mysqlnamespace: defaulttype: k8s-objects- name: mysql.saproperties:objects:- apiVersion: v1kind: Secretmetadata:name: mysqlnamespace: default- apiVersion: v1kind: ConfigMapmetadata:name: mysqlnamespace: defaulttype: k8s-objectspolicies:- name: read-onlyproperties:rules:- selector:componentNames:- mysql.StatefulSet.mysql- mysql.Service.mysql- mysql.Service.mysql-headless- mysql.config- mysql.satype: read-onlystatus: {}
- You can similarly use
--applyparameter to apply the application into cluster and use--mode=take-overto allow modifications by enforcingtake-overpolicy. In addition to that, if you want to completely adopt resources in helm chart into KubeVela application and disable the management of that helm chart (prevent multiple sources), you can add--recycleflag to remove the helm release secret after the application has entered running status.
vela adopt mysql --type helm --mode take-over --apply --recycle
resources adopted in app default/mysqlsuccessfully clean up old helm release
- You can check the application status using
vela statusandvela status -t -d.
vela status mysql
expected output
About:Name: mysqlNamespace: defaultCreated at: 2023-01-11 14:40:16 +0800 CSTStatus: runningWorkflow:mode: DAG-DAGfinished: trueSuspend: falseTerminated: falseSteps- id: orq8dnqbyvname: mysql.StatefulSet.mysqltype: apply-componentphase: succeeded- id: k5kwoc49jvname: mysql.Service.mysql-headlesstype: apply-componentphase: succeeded- id: p5qe1drkohname: mysql.Service.mysqltype: apply-componentphase: succeeded- id: odicbhtf9aname: mysql.configtype: apply-componentphase: succeeded- id: o36adyqqalname: mysql.satype: apply-componentphase: succeededServices:- Name: mysql.StatefulSet.mysqlCluster: local Namespace: defaultType: k8s-objectsHealthyNo trait applied- Name: mysql.Service.mysql-headlessCluster: local Namespace: defaultType: k8s-objectsHealthyNo trait applied- Name: mysql.Service.mysqlCluster: local Namespace: defaultType: k8s-objectsHealthyNo trait applied- Name: mysql.configCluster: local Namespace: defaultType: k8s-objectsHealthyNo trait applied- Name: mysql.saCluster: local Namespace: defaultType: k8s-objectsHealthyNo trait applied
vela status mysql -t -d
CLUSTER NAMESPACE RESOURCE STATUS APPLY_TIME DETAILlocal ─── default ─┬─ ConfigMap/mysql updated 2023-01-11 14:40:16 Data: 1 Age: 7m41s├─ Secret/mysql updated 2023-01-11 14:40:16 Type: Opaque Data: 2 Age: 7m41s├─ Service/mysql updated 2023-01-11 14:40:16 Type: ClusterIP Cluster-IP: 10.43.154.7 External-IP: <none> Port(s): 3306/TCP Age: 7m41s├─ Service/mysql-headless updated 2023-01-11 14:40:16 Type: ClusterIP Cluster-IP: None External-IP: <none> Port(s): 3306/TCP Age: 7m41s└─ StatefulSet/mysql updated 2023-01-11 14:40:16 Ready: 1/1 Age: 7m41s
- If you run
helm lsyou will not be able to find the original mysql helm release since the records have been recycled.
helm ls
NAME NAMESPACE REVISION UPDATED STATUS CHART APP VERSION
tip
There are multiple ways to use KubeVela together with Helm.
If you want to use Helm to control the release process of charts and use KubeVela to monitor those resources, you can use the default mode (read-only) and do not recycle the helm release secret. In this case, you will be able to monitor resources dispatched by Helm Chart with KubeVela tools or eco-system (like viewing on Grafana).
If you want to migrate existing resources from Helm Chart to KubeVela application, you can use the take-over mode and use the --apply flag to recycle helm release records.
By default, vela adopt will take resources from given source (native resource list or helm chart) and group them into different components. For resources like Deployments or Statefulsets, the original spec will be reserved. For other resources like ConfigMap or Secret, the data will not be recorded in the adoption application (which means the application does not care for the content in them). For special resources (CustomResourceDefinition), the garbage-collect and apply-once policy will be additionally attached in the application.
The conversion from resources into application is achieved by using the CUE template. You can refer to GitHub to see the default template.
You can also build your own adoption rule using CUE and add --adopt-template to vela adopt command.
- For example, let’s create an example deployment.
kubectl create deploy custom-adopt --image=nginx
- Create a file named
my-adopt-rule.cue.
import "list"#Resource: {apiVersion: stringkind: stringmetadata: {name: stringnamespace?: string...}...}#Component: {type: stringname: stringproperties: {...}dependsOn?: [...string]traits?: [...#Trait]}#Trait: {type: stringproperties: {...}}#Policy: {type: stringname: stringproperties?: {...}}#Application: {apiVersion: "core.oam.dev/v1beta1"kind: "Application"metadata: {name: stringnamespace?: stringlabels?: [string]: stringannotations?: [string]: string}spec: {components: [...#Component]policies?: [...#Policy]workflow?: {...}}}#AdoptOptions: {mode: *"read-only" | "take-over"type: *"helm" | stringappName: stringappNamespace: stringresources: [...#Resource]...}#Adopt: {$args: #AdoptOptions$returns: #Application// adopt logics$returns: #Application & {metadata: {name: $args.appNamelabels: "app.oam.dev/adopt": $args.type}spec: components: [for r in $args.resources if r.kind == "Deployment" {type: "webservice"name: r.metadata.nameproperties: image: r.spec.template.spec.containers[0].imagetraits: [{type: "scaler"properties: replicas: r.spec.replicas}]}]spec: policies: [{type: $args.modename: $args.modeproperties: rules: [{selector: componentNames: [ for comp in spec.components {comp.name}]}]}]}}
This customized adoption rule will automatically recognize deployment resources and convert it into KubeVela application’s webservice component. It can intelligently detect the replicas number of the given deployment and attach a scaler trait to the component.
- Run
vela adopt deployment/custom-adopt --adopt-template=my-adopt-rule.cue. You can see the converted application as
apiVersion: core.oam.dev/v1beta1kind: Applicationmetadata:creationTimestamp: nulllabels:app.oam.dev/adopt: nativename: custom-adoptspec:components:- name: custom-adoptproperties:image: nginxtraits:- properties:replicas: 1type: scalertype: webservicepolicies:- name: read-onlyproperties:rules:- selector:componentNames:- custom-adopttype: read-onlystatus: {}
With this capability, you can make your own rules for building application from existing resources or helm charts.
Last updated on Feb 9, 2023 by dependabot[bot]