In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
In this issue, the editor will bring you about how KubeVela converts appfile into K8s specific resource objects. The article is rich in content and analyzes and describes for you from a professional point of view. I hope you can get something after reading this article.
KubeVela is an easy-to-use and highly scalable cloud native application management engine, which is based on Kubernetes and OAM, a cloud native application development model jointly released by Aliyun and Microsoft Cloud.
KubeVela builds a set of concrete implementation based on OAM model. Through Golang writing, it can provide a relatively complete solution for users to build a platform for cloud native applications end-to-end.
The main purpose below is to explore how KubeVela converts an appfile file into a specific resource object in K8s.
The process is generally divided into two stages:
Appfile to application in K8s
Application is converted to the corresponding K8s resource object
# vela.yamlname: testservices: nginx: type: webservice image: nginx env:-name: NAME value: kubevela # svc trait svc: type: NodePort ports:-port: 80 nodePort: 32017
Deployment can be done using the vela up command.
Vela up command
Suggestion: before looking at the vela command line tool code, take a brief look at the cobra framework.
/ / references/cli/up.go// NewUpCommand will create command for applying an AppFilefunc NewUpCommand (c types.Args, ioStream cmdutil.IOStreams) * cobra.Command {cmd: = & cobra.Command {Use: "up", DisableFlagsInUseLine: true, Short: "Apply an appfile", Long: "Apply an appfile", Annotations: map [string] string {types.TagCommandType: types.TypeStart }, PersistentPreRunE: func (cmd * cobra.Command, args [] string) error {return c.SetConfig ()}, RunE: func (cmd * cobra.Command, args [] string) error {velaEnv, err: = GetEnv (cmd) if err! = nil {return err} kubecli Err: = c.GetClient () if err! = nil {return err} o: = & common.AppfileOptions {Kubecli: kubecli, IO: ioStream, Env: velaEnv,} filePath, err: = cmd.Flags (). GetString (appFilePath) if err! = nil {return err} return o.Run (filePath, velaEnv.Namespace, c)} } cmd.SetOut (ioStream.Out) cmd.Flags () .StringP (appFilePath, "f", "," specify file path for appfile ") return cmd}
The above source code shows the entrance to the vela up command.
In the PresistentPreRunE function, the injection of the Kuberentes configuration information kubeconfig is completed by calling c.SetConfig ().
In the RunE function:
First, get the env variable of vela, where velaEnv.Namespace corresponds to the namespace of Kubernetes.
Second, get the client of Kubernetes, kubectl.
Next, use the Kubernetes client and vleaEnv to build the AppfileOptions needed to render the Appfile.
Finally, call o.Run (filePath, velaEnv.Namespace, c).
FilePath: the path to appfile
VelaEnv.Namespace: namespace corresponding to K8s
C:K8s client
This function requires three parameters, of which filePath is used to specify the location of the appfile, and velaEnv.Namespace and c are used to create the rendered Application into the specified namespace.
How to convert an appfile into an Application in Kubernetes
Starting point: appfile
End point: applicatioin
Path: appfile-> application (services-> component)
Comp [workload, traits]
1. Starting point: AppFile// references/appfile/api/appfile.go// AppFile defines the spec of KubeVela Appfiletype AppFile struct {Name string `json: "name" `CreateTime time.Time `json: "createTime,omitempty" `UpdateTime time.Time `json: "updateTime,omitempty" `Services map [string] Service `json: "services" `Secrets map [string] string `json: "secrets Omitempty "`configGetter config.Store initialized bool} / / NewAppFile init an empty AppFile structfunc NewAppFile () * AppFile {return & AppFile {Services: make (map [string] Service), Secrets: make (map [string] string), configGetter: & config.Local {},}} / / references/appfile/api/service.go// Service defines the service spec for AppFile, it will contain all related information including OAM component, traits, source to image, etc...type Service map [string] interface {}
The above two pieces of code are the declaration of AppFile on the client side. Vela will read the yaml file of the specified path and assign it to an AppFile.
/ / references/appfile/api/appfile.go// LoadFromFile will read the file and load the AppFile structfunc LoadFromFile (filename string) (* AppFile, error) {b, err: = ioutil.ReadFile (filepath.Clean (filename)) if err! = nil {return nil, err} af: = NewAppFile () / / Add JSON format appfile support ext: = filepath.Ext (filename) switch ext {case ".yaml", ".yml": err = yaml.Unmarshal (b Af) case ".json": af, err = JSONToYaml (b, af) default: if json.Valid (b) {af, err = JSONToYaml (b, af)} else {err = yaml.Unmarshal (b, af)}} if err! = nil {return nil, err} return af, nil}
The following is the data loaded into AppFile after reading the vela.yaml file:
# vela.yamlname: testservices: nginx: type: webservice image: nginx env:-name: kubevela # svc trait svc: type: NodePort ports:-port: 80 nodePort: 32017Name: testCreateTime: 0001-01-01 00:00:00 + 0000 UTCUpdateTime: 0001-01-01 00:00:00 + 0000 UTCServices: map [nginx: map [env: [map [name: NAME value: kubevela]] image: nginx svc: map [ports: [map [nodePort: 32017 port: 80]] type: NodePort] type: webservice]] Secrets map [] configGetter: 0x447abd0 initialized: false2. Destination: application// apis/core.oam.dev/application_types.gotype Application struct {metav1.TypeMeta `json: ", inline" `metav1.ObjectMeta `json: "metadata,omitempty" `Spec ApplicationSpec `json: "spec,omitempty" `Status AppStatus `json: "status Omitempty "`} / / ApplicationSpec is the spec of Applicationtype ApplicationSpec struct {Components [] ApplicationComponent `json:" components "` / / TODO (wonderflow): we should have application level scopes supported here / / RolloutPlan is the details on how to rollout the resources / / The controller simply replace the old resources with the new one if there is no rollout plan involved / / + optional RolloutPlan * v1alpha1.RolloutPlan `json:" rolloutPlan,omitempty "`}
The above code, for the declaration of Application, combined with .vela / deploy.yaml (see code below), you can see that the main way to render an AppFile to Application is to convert AppFile's Services into Application's Components.
# .vela / deploy.yamlapiVersion: core.oam.dev/v1alpha2kind: Applicationmetadata: creationTimestamp: null name: test namespace: defaultspec: components:-name: nginx scopes: healthscopes.core.oam.dev: test-default-health settings: env:-name: NAME value: kubevela image: nginx traits:-name: svc properties: ports:-nodePort: 32017 port: 80 Type: NodePort type: webservicestatus: {} 3. Path: Services-> Components
Combined with the above, we can see that the main way to convert Appfile to Application is to render Services to Components.
/ references/appfile/api/appfile.go// BuildOAMApplication renders Appfile into Application, Scopes and other K8s Resources.func (app * AppFile) BuildOAMApplication (env * types.EnvMeta, io cmdutil.IOStreams, tm template.Manager, silence bool) (* v1alpha2.Application, [] oam.Object, error) {. ServApp: = new (v1alpha2.Application) servApp.SetNamespace (env.Namespace) servApp.SetName (app.Name) servApp.Spec.Components = [] v1alpha2.ApplicationComponent {} for serviceName, svc: = range app.GetServices () {. / / complete the conversion from Service to Component comp, err: = svc.RenderServiceToApplicationComponent (tm, serviceName) if err! = nil {return nil, nil, err} servApp.Spec.Components = append (servApp.Spec.Components Comp)} servApp.SetGroupVersionKind (v1alpha2.SchemeGroupVersion.WithKind ("Application") auxiliaryObjects = append (auxiliaryObjects, addDefaultHealthScopeToApplication (servApp)) return servApp, auxiliaryObjects, nil}
The above code is where vela converts Appfile to Application code implementation. Comp, err: = svc.RenderServiceToApplicationComponent (tm, serviceName) completes the conversion from Service to Component.
/ references/appfile/api/service.go// RenderServiceToApplicationComponent render all capabilities of a service to CUE values to KubeVela Application.func (s Service) RenderServiceToApplicationComponent (tm template.Manager, serviceName string) (v1alpha2.ApplicationComponent, error) {/ / sort out configs by workload/trait workloadKeys: = map [string] interface {} {} var traits [] v1alpha2.ApplicationTrait wtype: = s.GetType () comp: = v1alpha2.ApplicationComponent {Name: serviceName, WorkloadType: wtype,} for k V: = range s.GetApplicationConfig () {/ / determine whether it is trait if tm.IsTrait (k) {trait: = v1alpha2.ApplicationTrait {Name: K,}.... / / if triat joins traits traits = append (traits, trait) continue} workloadKeys [k] = v} / / Handle workloadKeys to settings settings: = & runtime.RawExte nsion {} pt, err: = json.Marshal (workloadKeys) if err! = nil {return comp, err} if err: = settings.UnmarshalJSON (pt) Err! = nil {return comp, err} comp.Settings = * settings if len (traits) > 0 {comp.Traits = traits} return comp, nil} 4. Summary
Execute the vela up command, render the appfile as Application, write the data to .vela / deploy.yaml, and create it in K8s.
How to convert Application to corresponding K8s resource object
Starting point: Application
Midpoint: ApplicationConfiguration, Component
Destination: Deployment, Service
Path:
Application_controller
Applicationconfiguration controller
[suggestion] > learn more about it: >-client-to
Controller-runtime
Operator
1. Application# gets Application$ kubectl get applicationNAMESPACE NAME AGEdefault test 24h2 in the cluster. ApplicationConfiguration and Component
When application controller acquires the Application resource object, it creates the corresponding ApplicationConfiguration and Component based on its contents.
# obtain ApplicationConfiguration and Component$ kubectl get ApplicationConfiguration,ComponentNAME AGEapplicationconfiguration.core.oam.dev/test 24hNAME WORKLOAD-KIND AGEcomponent.core.oam.dev/nginx Deployment for 24 hours
Component is introduced as a name in ApplicationiConfiguration:
3. Application controller basic logic:
Gets an Application resource object.
Render Application resource objects as ApplicationConfiguration and Component.
Create ApplicationConfiguration and Component resource objects.
Code: / / pkg/controller/core.oam.dev/v1alpha2/application/application_controller.go// Reconcile process app eventfunc (r * Reconciler) Reconcile (req ctrl.Request) (ctrl.Result, error) {ctx: = context.Background () applog: = r.Log.WithValues ("application", req.NamespacedName) / / 1. Get Application app: = new (v1alpha2.Application) if err: = r.Get (ctx, client.ObjectKey {Name: req.Name, Namespace: req.Namespace,}, app); err! = nil {...}. / / 2. Convert Application to ApplicationConfiguration and Component handler: = & appHandler {r, app, applog}. AppParser: = appfile.NewApplicationParser (r.Client, r.dm)... Appfile, err: = appParser.GenerateAppFile (ctx, app.Name, app). Ac, comps, err: = appParser.GenerateApplicationConfiguration (appfile, app.Namespace). / / 3. Create ApplicationConfiguration and Component / / apply appConfig & component to the cluster if err: = handler.apply (ctx, ac, comps); err! = nil {applog.Error (err, "[Handle apply]") app.Status.SetConditions (errorCondition ("Applied", err) return handler.handleErr (err)} in the cluster. Return ctrl.Result {}, r.UpdateStatus (ctx, app)} 4. Applicationconfiguration controller basic logic:
Gets the ApplicationConfiguration resource object.
Loop through each Component and render workload and trait as corresponding K8s resource objects.
Create the corresponding K8s resource object.
Code: / / pkg/controller/core.oam.dev/v1alpha2/applicationcinfiguratioin/applicationconfiguratioin.go// Reconcile an OAM ApplicationConfigurations by rendering and instantiating its// Components and Traits.func (r * OAMApplicationReconciler) Reconcile (req reconcile.Request) (reconcile.Result, error) {. Ac: = & v1alpha2.ApplicationConfiguration {} / / 1. Get ApplicationConfiguration if err: = r.client.Get (ctx, req.NamespacedName, ac); err! = nil {...} return r.ACReconcile (ctx, ac, log)} / / ACReconcile contains all the reconcile logic of an AC, it can be used by other controllerfunc (r * OAMApplicationReconciler) ACReconcile (ctx context.Context, ac * v1alpha2.ApplicationConfiguration, log logging.Logger) (result reconcile.Result, returnErr error) {. / / 2. Render / / here workloads contains all Component corresponding workload and tratis k8s resource objects workloads, depStatus, err: = r.components.Render (ctx, ac). ApplyOpts: [] apply.ApplyOption {apply.MustBeControllableBy (ac.GetUID ()), applyOnceOnly (ac, r.applyOnceOnlyMode, log)} / / 3. Create the k8s resource object if err: = r.workloads.Apply (ctx, ac.Status.Workloads, workloads, applyOpts...) for workload and traits; err! = nil {...}. / / the defer function will do the final status update return reconcile.Result {RequeueAfter: waitTime}, nil} 5. Summary
When vela up renders an AppFile as an Application, the subsequent process is done by application controller and applicationconfiguration controller.
This is how the KubeVela shared by the editor converts appfile into a K8s specific resource object. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 250
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.