From 5dcf1c2f7690c2b1685caf0f1aac8fca620b7bf4 Mon Sep 17 00:00:00 2001 From: pb Date: Tue, 27 Aug 2024 11:02:30 +0200 Subject: [PATCH 1/9] files to display --- demo_nginx/DTF.html | 5 ++ demo_nginx/cockpit.html | 5 ++ test-logs-workflow.json | 141 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 151 insertions(+) create mode 100644 demo_nginx/DTF.html create mode 100644 demo_nginx/cockpit.html create mode 100644 test-logs-workflow.json diff --git a/demo_nginx/DTF.html b/demo_nginx/DTF.html new file mode 100644 index 0000000..30e4f97 --- /dev/null +++ b/demo_nginx/DTF.html @@ -0,0 +1,5 @@ + + +

This could be your DTF webpage

+ + \ No newline at end of file diff --git a/demo_nginx/cockpit.html b/demo_nginx/cockpit.html new file mode 100644 index 0000000..6c7b718 --- /dev/null +++ b/demo_nginx/cockpit.html @@ -0,0 +1,5 @@ + + +

Welcome to your DTF Cockpit

+ + \ No newline at end of file diff --git a/test-logs-workflow.json b/test-logs-workflow.json new file mode 100644 index 0000000..d4e9b71 --- /dev/null +++ b/test-logs-workflow.json @@ -0,0 +1,141 @@ +{ + "name": "test-log", + "processings": [ + "0d565c87-50ae-4a73-843d-f8b2d4047772", + "2ce0323f-a85d-4b8b-a783-5280f48d634a" + ], + "datacenters": [ + "7b989e97-c3e7-49d2-a3a7-f959da4870b5" + ], + "graph": { + "items": { + "aa8d2265-9fe2-42c7-ba1f-46ea0da8e633": { + "id": "aa8d2265-9fe2-42c7-ba1f-46ea0da8e633", + "width": 0, + "height": 0, + "processing": { + "id": "0d565c87-50ae-4a73-843d-f8b2d4047772", + "resource_model": { + "resource_type": "processing", + "model": { + "command": { + "type": "string", + "value": "curlimages/curl:7.88.1" + }, + "args": { + "type": "string", + "value": "-SL https://toulousefc.com -o /mnt/vol/tfc.hmtl" + } + } + }, + "name": "CURL", + "short_description": "Transfer or retrieve information from or to a server ", + "description": "curl is a tool for transferring data from or to a server. It supports these protocols: DICT, FILE, FTP, FTPS, GOPHER, GOPHERS, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, MQTT, POP3, POP3S, RTMP, RTMPS, RTSP, SCP, SFTP, SMB, SMBS, SMTP, SMTPS, TELNET, TFTP, WS and WSS.", + "logo": "https://cloud.o-forge.io/core/deperecated-oc-catalog/src/branch/main/scripts/local_imgs/curl-logo.png", + "owner": "IRT", + "source_url": "http://www.google.com", + "license": "GPLv2", + "ram": {}, + "storage": 300, + "parallel": true, + "scaling_model": 2, + "disk_io": "30 MB/s" + } + }, + "b6f790ae-5db2-4458-8375-59450f12f65b": { + "id": "b6f790ae-5db2-4458-8375-59450f12f65b", + "width": 0, + "height": 0, + "processing": { + "id": "2ce0323f-a85d-4b8b-a783-5280f48d634a", + "resource_model": { + "resource_type": "processing", + "model": { + "command": { + "type": "string", + "value": "alpine:3.7 sh -c" + }, + "args": { + "type": "string", + "value": "grep ' Date: Thu, 29 Aug 2024 12:08:57 +0200 Subject: [PATCH 2/9] fixed dependencies' rertieving --- workflow_builder/argo_builder.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/workflow_builder/argo_builder.go b/workflow_builder/argo_builder.go index 8da03b8..be184b5 100644 --- a/workflow_builder/argo_builder.go +++ b/workflow_builder/argo_builder.go @@ -160,7 +160,7 @@ func (b *ArgoBuilder) createNginxVolumes() { func (b *ArgoBuilder) getDependency(current_computing_id string) (dependencies []string) { for _, link := range b.OriginWorkflow.Graph.Links { - if !b.IsProcessing(link.Source.ID) { + if b.OriginWorkflow.Graph.Items[link.Source.ID].Processing == nil { continue } source := b.OriginWorkflow.Graph.Items[link.Source.ID].Processing From d8dfabca3a02f3f93df735e32459fa54c02abd05 Mon Sep 17 00:00:00 2001 From: pb Date: Tue, 3 Sep 2024 14:24:03 +0200 Subject: [PATCH 3/9] Create and update a k8s service for each processing with expose model --- README.md | 34 ++++ demo_nginx/workflow_nginx_services.json | 44 +++-- models/services.go | 40 ++++ models/template.go | 6 + models/translate_ports.go | 8 + workflow_builder/argo_builder.go | 246 ++++++++++++++++++++++-- 6 files changed, 344 insertions(+), 34 deletions(-) create mode 100644 models/services.go create mode 100644 models/translate_ports.go diff --git a/README.md b/README.md index e429389..7dfc71a 100644 --- a/README.md +++ b/README.md @@ -15,3 +15,37 @@ imagePullPolicy: Never Not doing so will end up in the pod having a `ErrorImagePull` +## Allow argo to create services + +In order for monitord to expose **open cloud services** on the node, we need to give him permission to create **k8s services**. + +For that we can update the RBAC configuration for a role already created by argo : + +### Manually edit the rbac authorization + +> kubectl edit roles.rbac.authorization.k8s.io -n argo argo-role + +In rules add a new entry : + +``` +- apiGroups: + - "" + resources: + - services + verbs: + - get + - create +``` + +### Patch the rbac authorization with a one liner + +> kubectl patch role argo-role -n argo --type='json' -p='[{"op": "add", "path": "/rules/-", "value": {"apiGroups": [""], "resources": ["services"], "verbs": ["get","create"]}}]' + +### Check wether the modification is effective + +> kubectl auth can-i create services --as=system:serviceaccount:argo:argo -n argo + +This command **must return "yes"** + + + diff --git a/demo_nginx/workflow_nginx_services.json b/demo_nginx/workflow_nginx_services.json index acbee01..f07a50c 100644 --- a/demo_nginx/workflow_nginx_services.json +++ b/demo_nginx/workflow_nginx_services.json @@ -1,15 +1,13 @@ { "id": "9c7ffc7e-3e6e-4ea8-8eab-3a03258712ff", "name": "test-services", - "resourceset": { - "processings": [ - "7c71a15b-bdbc-46d7-9dab-67e369804136", - "0d565c87-50ae-4a73-843d-f8b2d4047772" - ], - "datacenters": [ - "7b989e97-c3e7-49d2-a3a7-f959da4870b5" - ] - }, + "processings": [ + "7c71a15b-bdbc-46d7-9dab-67e369804136", + "0d565c87-50ae-4a73-843d-f8b2d4047772" + ], + "datacenters": [ + "7b989e97-c3e7-49d2-a3a7-f959da4870b5" + ], "graph": { "zoom": 1, "items": { @@ -28,7 +26,7 @@ }, "args": { "type": "string", - "value": "-SL https://cloud.o-forge.io/core/oc-monitord/raw/branch/services_demo/demo_nginx/cockpit.html -o /usr/share/ningx/cockpit.hmtl" + "value": "-SL https://cloud.o-forge.io/core/oc-monitord/raw/branch/services_demo/demo_nginx/cockpit.html -o /usr/share/nginx/cockpit.hmtl" } } }, @@ -61,7 +59,7 @@ }, "args": { "type": "string", - "value": "-SL https://cloud.o-forge.io/core/oc-monitord/raw/branch/services_demo/demo_nginx/DTF.html -o /usr/share/ningx/DTF.hmtl" + "value": "-SL https://cloud.o-forge.io/core/oc-monitord/raw/branch/services_demo/demo_nginx/DTF.html -o /usr/share/nginx/DTF.hmtl" } } }, @@ -100,6 +98,15 @@ }, "args": { "type": "string" + }, + "expose": { + "type": "dict", + "value": { + "80" :{ + "reverse" : "", + "PAT" : "308080" + } + } } } }, @@ -139,6 +146,15 @@ }, "args": { "type": "string" + }, + "expose": { + "type": "dict", + "value": { + "80" :{ + "reverse" : "", + "PAT" : "308081" + } + } } } }, @@ -222,7 +238,7 @@ "y": 0 }, "destination": { - "id": "0d565c87-50ae-4a73-843d-f8b2d4047772", + "id": "bf6916ff-b16f-44b3-818b-0bcd5bbaca00", "x": 0, "y": 0 } @@ -277,12 +293,12 @@ }, { "source": { - "id": "6a7e8860-7c26-4b70-9b3a-1bd27adcdfe1", + "id": "d83ac451-4690-44d9-af09-48e7588b2db9", "x": 0, "y": 0 }, "destination": { - "id": "d83ac451-4690-44d9-af09-48e7588b2db9", + "id": "6a7e8860-7c26-4b70-9b3a-1bd27adcdfe1", "x": 0, "y": 0 } diff --git a/models/services.go b/models/services.go new file mode 100644 index 0000000..ba0e10a --- /dev/null +++ b/models/services.go @@ -0,0 +1,40 @@ +package models + + +type ServiceResource struct { + Action string `yaml:"action,omitempty"` + SuccessCondition string `yaml:"successCondition,omitempty"` + FailureCondition string `yaml:"failureCondition,omitempty"` + SetOwnerReference bool `yaml:"setOwnerReference,omitempty"` + Manifest string `yaml:"manifest,omitempty"` +} + +type Service struct { + APIVersion string `yaml:"apiVersion"` + Kind string `yaml:"kind"` + Metadata Metadata `yaml:"metadata"` + Spec ServiceSpec `yaml:"spec"` +} + +type Metadata struct { + Name string `yaml:"name"` + +} + +// ServiceSpec is the specification of the Kubernetes Service +type ServiceSpec struct { + Selector map[string]string `yaml:"selector,omitempty"` + Ports []ServicePort `yaml:"ports"` + ClusterIP string `yaml:"clusterIP,omitempty"` + Type string `yaml:"type,omitempty"` +} + +// ServicePort defines a port for a Kubernetes Service +type ServicePort struct { + Name string `yaml:"name"` // Even if empty need to be in the yaml + + Protocol string `yaml:"protocol,omitempty"` + Port int64 `yaml:"port"` + TargetPort int64 `yaml:"targetPort,omitempty"` + NodePort int64 `yaml:"nodePort,omitempty"` +} \ No newline at end of file diff --git a/models/template.go b/models/template.go index 47feaf4..c7c9b0e 100644 --- a/models/template.go +++ b/models/template.go @@ -30,6 +30,10 @@ type Dag struct { Tasks []Task `yaml:"tasks,omitempty"` } +type TemplateMetadata struct { + Labels map[string]string `yaml:"labels,omitempty"` +} + type Template struct { Name string `yaml:"name"` Inputs struct { @@ -37,4 +41,6 @@ type Template struct { } `yaml:"inputs,omitempty"` Container Container `yaml:"container,omitempty"` Dag Dag `yaml:"dag,omitempty"` + Metadata TemplateMetadata `yaml:"metadata,omitempty"` + Resource ServiceResource `yaml:"resource,omitempty"` } diff --git a/models/translate_ports.go b/models/translate_ports.go new file mode 100644 index 0000000..080101b --- /dev/null +++ b/models/translate_ports.go @@ -0,0 +1,8 @@ +package models + +type PortTranslation map[string]PortConfig + +type PortConfig struct { + Reverse string `json:"reverse,omitempty"` + PAT string `json:"PAT,omitempty"` +} diff --git a/workflow_builder/argo_builder.go b/workflow_builder/argo_builder.go index be184b5..fc46a9b 100644 --- a/workflow_builder/argo_builder.go +++ b/workflow_builder/argo_builder.go @@ -8,6 +8,7 @@ import ( . "oc-monitord/models" "os" "slices" + "strconv" "strings" "time" @@ -16,13 +17,19 @@ import ( "cloud.o-forge.io/core/oc-lib/models/resources/workflow/graph" w "cloud.o-forge.io/core/oc-lib/models/workflow" "github.com/nwtgck/go-fakelish" + "github.com/rs/zerolog" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" "gopkg.in/yaml.v3" ) +var logger zerolog.Logger + type ArgoBuilder struct { - OriginWorkflow w.Workflow - Workflow Workflow - Timeout int + OriginWorkflow w.Workflow + Workflow Workflow + Services *Service + Timeout int } type Workflow struct { @@ -45,9 +52,9 @@ type Spec struct { func (b *ArgoBuilder) CreateDAG() (string, error) { // handle services by checking if there is only one processing with hostname and port - if (b.isService()){ - b.createNginxVolumes() - } + + b.createNginxVolumes() + b.createTemplates() b.createDAGstep() @@ -62,7 +69,7 @@ func (b *ArgoBuilder) CreateDAG() (string, error) { b.Workflow.Kind = "Workflow" random_name := generateWfName() b.Workflow.Metadata.Name = "oc-monitor-" + random_name - logger := oclib.GetLogger() + logger = oclib.GetLogger() yamlified, err := yaml.Marshal(b.Workflow) if err != nil { logger.Error().Msg("Could not transform object to yaml file") @@ -111,8 +118,22 @@ func (b *ArgoBuilder) createTemplates() { new_temp.Inputs.Parameters = inputs_container new_temp.Container.VolumeMounts = append(new_temp.Container.VolumeMounts, VolumeMount{Name: "workdir", MountPath: "/mnt/vol"}) // TODO : replace this with a search of the storage / data source name new_temp.Container.VolumeMounts = append(new_temp.Container.VolumeMounts, VolumeMount{Name: "nginx-demo", MountPath: "/usr/share/nginx"}) // Used for processing services' demo with nginx + + if (b.isService(comp.ID)){ + serv := b.CreateService(comp) + b.createService(serv, argo_name, comp.ID) + new_temp.Metadata.Labels = make(map[string]string) + new_temp.Metadata.Labels["app"] = "oc-service" // Construct the template for the k8s service and add a link in graph between k8s service and processing + // if err != nil { + // // TODO + // } + } + b.Workflow.Spec.Templates = append(b.Workflow.Spec.Templates, new_temp) + } + if b.Services != nil { + b.addServiceToArgo() } } @@ -134,8 +155,13 @@ func (b *ArgoBuilder) createDAGstep() { step.Dependencies = b.getDependency(comp.ID) // Error : we use the component ID instead of the GraphItem ID -> store objects new_dag.Tasks = append(new_dag.Tasks, step) } - b.Workflow.Spec.Templates = append(b.Workflow.Spec.Templates, Template{Name: "dag", Dag: new_dag}) + if b.Services != nil { + new_dag.Tasks = append(new_dag.Tasks, Task{Name:"workflow-service-pod", Template: "workflow-service-pod"}) + } + + b.Workflow.Spec.Templates = append(b.Workflow.Spec.Templates, Template{Name: "dag", Dag: new_dag}) + } func (b *ArgoBuilder) createVolumes() { @@ -272,8 +298,9 @@ func (b *ArgoBuilder) getProcessings() (list_computings []graph.GraphItem) { return } -func (b *ArgoBuilder) IsProcessing(id string) bool { - return slices.Contains(b.OriginWorkflow.Processings, id) +// Pass a GraphItem's UUID and not the ID +func (b *ArgoBuilder) IsProcessing(component_uuid string) bool { + return slices.Contains(b.OriginWorkflow.Processings, component_uuid) } func getStringValue(comp resource_model.AbstractResource, key string) string { @@ -283,19 +310,198 @@ func getStringValue(comp resource_model.AbstractResource, key string) string { return "" } -func (b *ArgoBuilder) isService() bool{ - // for dev purpose do not commit to main - if os.Getenv("test_service") != ""{ - return true - } +func (b *ArgoBuilder) isService(id string) bool{ + + comp := b.OriginWorkflow.Graph.Items[id] - comp_list := b.getProcessings() - - if len(comp_list) != 1 { + if comp.Processing == nil { return false } - comp := comp_list[0] + _, is_exposed := comp.Processing.ResourceModel.Model["expose"] + return is_exposed +} - return comp.Data.ResourceModel.Model["port"].Value != "" && comp.Data.ResourceModel.Model["hostname"].Value != "" +func (b *ArgoBuilder) CreateService(processing graph.GraphItem) Service{ + + // model { + // Type : "dict", + // Value : { + // "80" : { + // "reverse" : "", + // "PAT" : "34000" + // }, + // "344" : { + // "reverse" : "", + // "PAT" : "34400" + // } + // } + // } + + + new_service := Service{APIVersion: "v1", + Kind: "Service", + Metadata: Metadata{ + Name: "workflow-service" , + }, + Spec: ServiceSpec{ + Selector: map[string]string{"app": "oc-service"}, + Ports: []ServicePort{ + }, + Type: "NodePort", + }, + } + + completeServicePorts(&new_service, processing) + yamlified, _ := yaml.Marshal(new_service) + x := string(yamlified) + _ = x + return new_service +} + +func completeServicePorts(service *Service, processing graph.GraphItem) { + + contract := getExposeContract(processing.Processing.ResourceModel.Model["expose"]) + + + for str_port,translation_dict := range contract{ + + port, err := strconv.ParseInt(str_port, 10, 64) + if err != nil { + logger.Error().Msg("Could not convert " + str_port + "to an int") + return + } + + + if _, ok := translation_dict["PAT"]; ok{ + port_translation, err := strconv.ParseInt(translation_dict["PAT"], 10, 64) + if err != nil { + logger.Error().Msg("Could not convert " + translation_dict["PAT"] + "to an int") + return + } + + + + new_port_translation := ServicePort{ + Name: strings.ToLower(processing.Processing.Name) + processing.ID, + Port: port_translation-30000, + TargetPort: port, + NodePort: port_translation, + Protocol: "TCP", + } + service.Spec.Ports = append(service.Spec.Ports, new_port_translation) + } + + } + + return +} + +// TODO : refactor this method or the deserialization process in oc-lib to get rid of the mongo code +func getExposeContract(expose resource_model.Model) map[string]map[string]string { + contract := make(map[string]map[string]string,0) + + mapped_info := bson.M{} + // var contract PortTranslation + _ , byt, _ := bson.MarshalValue(expose.Value) + + bson.Unmarshal(byt,&mapped_info) + + for _,v := range mapped_info { + port := v.(primitive.M)["Key"].(string) + // exposed_port := map[string]interface{}{data["Key"] : ""} + port_translation := v.(primitive.M)["Value"] + contract[port] = map[string]string{} + for _,v2 := range port_translation.(primitive.A) { + if v2.(primitive.M)["Key"] == "reverse" { + contract[port]["reverse"] = v2.(primitive.M)["Value"].(string) + } + if v2.(primitive.M)["Key"] == "PAT" { + contract[port]["PAT"] = v2.(primitive.M)["Value"].(string) + } + } + } + return contract +} +// func getPortsFromModel(model map[string]resource_model.Model) (data []int) { +// defer func() { // recover the panic +// if r := recover(); r != nil { +// for _, v := range model["expose"].Value.(map[string]interface{}) { +// subMap := v.(map[string]interface{}) +// for k2, v2 := range subMap { +// if k2 == "PAT" { +// data = append(data, v2.(int)) +// } +// } +// } +// } +// }() + +// expose := model["expose"].Value + +// // sub := expose.([]primitive.A) +// for _, item := range expose.(primitive.A) { +// if doc, ok := item.(primitive.D); ok { +// for v,k := range doc{ +// key := k.Key +// valueMap := make(map[string]interface{}) + +// if nestedArray, ok := elem.Value.(primitive.A); ok { +// for _, nestedItem := range nestedArray { +// if nestedDoc, ok := nestedItem.(primitive.D); ok { +// for _, nestedElem := range nestedDoc { +// valueMap[nestedElem.Key] = nestedElem.Value +// } +// } +// } +// } +// } +// } +// } + +// return +// } + + + +func (b *ArgoBuilder) createService(service Service, processing_name string, processing_id string) { + if b.Services != nil{ + b.Services.Spec.Ports = append(b.Services.Spec.Ports, service.Spec.Ports...) + }else { + b.Services = &service + } + + b.addLabel(processing_name,processing_id) + +} + +func (b *ArgoBuilder) addLabel(name string, id string) { + argo_name := getArgoName(name,id) + for _, template := range b.Workflow.Spec.Templates{ + if template.Name == argo_name{ + template.Metadata.Labels["app"] = "service-workflow" + return + } + } +} + +func (b *ArgoBuilder) addServiceToArgo() error { + service_manifest, err := yaml.Marshal(b.Services) + if err != nil { + logger.Error().Msg("Could not marshal service manifest") + return err + } + + service_template := Template{Name: "workflow-service-pod", + Resource: ServiceResource{ + Action: "create", + SuccessCondition: "status.succeeded > 0", + FailureCondition: "status.failed > 3", + SetOwnerReference: true, + Manifest: string(service_manifest), + }, + } + b.Workflow.Spec.Templates = append(b.Workflow.Spec.Templates, service_template) + + return nil } \ No newline at end of file From ebf537979e3281a96b2ebca7d692c9615c20c578 Mon Sep 17 00:00:00 2001 From: pb Date: Tue, 3 Sep 2024 15:54:20 +0200 Subject: [PATCH 4/9] refactoring for better readability --- workflow_builder/argo_services.go | 148 ++++++++++++++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 workflow_builder/argo_services.go diff --git a/workflow_builder/argo_services.go b/workflow_builder/argo_services.go new file mode 100644 index 0000000..a990deb --- /dev/null +++ b/workflow_builder/argo_services.go @@ -0,0 +1,148 @@ +package workflow_builder + +import ( + "oc-monitord/models" + "strconv" + "strings" + + "cloud.o-forge.io/core/oc-lib/models/resource_model" + "cloud.o-forge.io/core/oc-lib/models/resources/workflow/graph" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "gopkg.in/yaml.v3" +) + +// TODO : refactor this method or the deserialization process in oc-lib to get rid of the mongo code +func getExposeContract(expose resource_model.Model) map[string]map[string]string { + contract := make(map[string]map[string]string,0) + + mapped_info := bson.M{} + // var contract PortTranslation + _ , byt, _ := bson.MarshalValue(expose.Value) + + bson.Unmarshal(byt,&mapped_info) + + for _,v := range mapped_info { + port := v.(primitive.M)["Key"].(string) + // exposed_port := map[string]interface{}{data["Key"] : ""} + port_translation := v.(primitive.M)["Value"] + contract[port] = map[string]string{} + for _,v2 := range port_translation.(primitive.A) { + if v2.(primitive.M)["Key"] == "reverse" { + contract[port]["reverse"] = v2.(primitive.M)["Value"].(string) + } + if v2.(primitive.M)["Key"] == "PAT" { + contract[port]["PAT"] = v2.(primitive.M)["Value"].(string) + } + } + } + return contract +} + + +func (b *ArgoBuilder) CreateService(processing graph.GraphItem) models.Service{ + + // model { + // Type : "dict", + // Value : { + // "80" : { + // "reverse" : "", + // "PAT" : "34000" + // }, + // "344" : { + // "reverse" : "", + // "PAT" : "34400" + // } + // } + // } + + + new_service := models.Service{APIVersion: "v1", + Kind: "Service", + Metadata: models.Metadata{ + Name: "workflow-service" , + }, + Spec: models.ServiceSpec{ + Selector: map[string]string{"app": "oc-service"}, + Ports: []models.ServicePort{ + }, + Type: "NodePort", + }, + } + + completeServicePorts(&new_service, processing) + yamlified, _ := yaml.Marshal(new_service) + x := string(yamlified) + _ = x + return new_service +} + +func completeServicePorts(service *models.Service, processing graph.GraphItem) { + + contract := getExposeContract(processing.Processing.ResourceModel.Model["expose"]) + + + for str_port,translation_dict := range contract{ + + port, err := strconv.ParseInt(str_port, 10, 64) + if err != nil { + logger.Error().Msg("Could not convert " + str_port + "to an int") + return + } + + + if _, ok := translation_dict["PAT"]; ok{ + port_translation, err := strconv.ParseInt(translation_dict["PAT"], 10, 64) + if err != nil { + logger.Error().Msg("Could not convert " + translation_dict["PAT"] + "to an int") + return + } + + + + new_port_translation := models.ServicePort{ + Name: strings.ToLower(processing.Processing.Name) + processing.ID, + Port: port_translation-30000, + TargetPort: port, + NodePort: port_translation, + Protocol: "TCP", + } + service.Spec.Ports = append(service.Spec.Ports, new_port_translation) + } + + } + + return +} + +func (b *ArgoBuilder) createService(service models.Service, processing_name string, processing_id string) { + if b.Services != nil{ + b.Services.Spec.Ports = append(b.Services.Spec.Ports, service.Spec.Ports...) + }else { + b.Services = &service + } + + b.addLabel(processing_name,processing_id) + +} + +func (b *ArgoBuilder) addServiceToArgo() error { + service_manifest, err := yaml.Marshal(b.Services) + if err != nil { + logger.Error().Msg("Could not marshal service manifest") + return err + } + + service_template := models.Template{Name: "workflow-service-pod", + Resource: models.ServiceResource{ + Action: "create", + SuccessCondition: "status.succeeded > 0", + FailureCondition: "status.failed > 3", + SetOwnerReference: true, + Manifest: string(service_manifest), + }, + } + b.Workflow.Spec.Templates = append(b.Workflow.Spec.Templates, service_template) + + return nil +} \ No newline at end of file From bbedc531338ea73a3be4df8ee50e42297091f39d Mon Sep 17 00:00:00 2001 From: pb Date: Tue, 3 Sep 2024 15:56:16 +0200 Subject: [PATCH 5/9] How to set uo + TODO --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 7dfc71a..64321ad 100644 --- a/README.md +++ b/README.md @@ -48,4 +48,10 @@ In rules add a new entry : This command **must return "yes"** +## TODO +- [ ] Logs the output of each pods : + - logsPods() function already exists + - need to implement the logic to create each pod's logger and start the monitoring routing +- [ ] Allow the front to known on which IP the service are reachable + - currently doing it by using `kubectl get nodes -o wide` \ No newline at end of file From ea44ca33b2ad079cc494b77ec59071013d685bfb Mon Sep 17 00:00:00 2001 From: pb Date: Tue, 3 Sep 2024 15:57:14 +0200 Subject: [PATCH 6/9] refactor for better readability --- workflow_builder/argo_builder.go | 175 ------------------------------- 1 file changed, 175 deletions(-) diff --git a/workflow_builder/argo_builder.go b/workflow_builder/argo_builder.go index fc46a9b..0976e5d 100644 --- a/workflow_builder/argo_builder.go +++ b/workflow_builder/argo_builder.go @@ -8,7 +8,6 @@ import ( . "oc-monitord/models" "os" "slices" - "strconv" "strings" "time" @@ -18,8 +17,6 @@ import ( w "cloud.o-forge.io/core/oc-lib/models/workflow" "github.com/nwtgck/go-fakelish" "github.com/rs/zerolog" - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" "gopkg.in/yaml.v3" ) @@ -322,158 +319,6 @@ func (b *ArgoBuilder) isService(id string) bool{ return is_exposed } -func (b *ArgoBuilder) CreateService(processing graph.GraphItem) Service{ - - // model { - // Type : "dict", - // Value : { - // "80" : { - // "reverse" : "", - // "PAT" : "34000" - // }, - // "344" : { - // "reverse" : "", - // "PAT" : "34400" - // } - // } - // } - - - new_service := Service{APIVersion: "v1", - Kind: "Service", - Metadata: Metadata{ - Name: "workflow-service" , - }, - Spec: ServiceSpec{ - Selector: map[string]string{"app": "oc-service"}, - Ports: []ServicePort{ - }, - Type: "NodePort", - }, - } - - completeServicePorts(&new_service, processing) - yamlified, _ := yaml.Marshal(new_service) - x := string(yamlified) - _ = x - return new_service -} - -func completeServicePorts(service *Service, processing graph.GraphItem) { - - contract := getExposeContract(processing.Processing.ResourceModel.Model["expose"]) - - - for str_port,translation_dict := range contract{ - - port, err := strconv.ParseInt(str_port, 10, 64) - if err != nil { - logger.Error().Msg("Could not convert " + str_port + "to an int") - return - } - - - if _, ok := translation_dict["PAT"]; ok{ - port_translation, err := strconv.ParseInt(translation_dict["PAT"], 10, 64) - if err != nil { - logger.Error().Msg("Could not convert " + translation_dict["PAT"] + "to an int") - return - } - - - - new_port_translation := ServicePort{ - Name: strings.ToLower(processing.Processing.Name) + processing.ID, - Port: port_translation-30000, - TargetPort: port, - NodePort: port_translation, - Protocol: "TCP", - } - service.Spec.Ports = append(service.Spec.Ports, new_port_translation) - } - - } - - return -} - -// TODO : refactor this method or the deserialization process in oc-lib to get rid of the mongo code -func getExposeContract(expose resource_model.Model) map[string]map[string]string { - contract := make(map[string]map[string]string,0) - - mapped_info := bson.M{} - // var contract PortTranslation - _ , byt, _ := bson.MarshalValue(expose.Value) - - bson.Unmarshal(byt,&mapped_info) - - for _,v := range mapped_info { - port := v.(primitive.M)["Key"].(string) - // exposed_port := map[string]interface{}{data["Key"] : ""} - port_translation := v.(primitive.M)["Value"] - contract[port] = map[string]string{} - for _,v2 := range port_translation.(primitive.A) { - if v2.(primitive.M)["Key"] == "reverse" { - contract[port]["reverse"] = v2.(primitive.M)["Value"].(string) - } - if v2.(primitive.M)["Key"] == "PAT" { - contract[port]["PAT"] = v2.(primitive.M)["Value"].(string) - } - } - } - return contract -} -// func getPortsFromModel(model map[string]resource_model.Model) (data []int) { -// defer func() { // recover the panic -// if r := recover(); r != nil { -// for _, v := range model["expose"].Value.(map[string]interface{}) { -// subMap := v.(map[string]interface{}) -// for k2, v2 := range subMap { -// if k2 == "PAT" { -// data = append(data, v2.(int)) -// } -// } -// } -// } -// }() - -// expose := model["expose"].Value - -// // sub := expose.([]primitive.A) -// for _, item := range expose.(primitive.A) { -// if doc, ok := item.(primitive.D); ok { -// for v,k := range doc{ -// key := k.Key -// valueMap := make(map[string]interface{}) - -// if nestedArray, ok := elem.Value.(primitive.A); ok { -// for _, nestedItem := range nestedArray { -// if nestedDoc, ok := nestedItem.(primitive.D); ok { -// for _, nestedElem := range nestedDoc { -// valueMap[nestedElem.Key] = nestedElem.Value -// } -// } -// } -// } -// } -// } -// } - -// return -// } - - - -func (b *ArgoBuilder) createService(service Service, processing_name string, processing_id string) { - if b.Services != nil{ - b.Services.Spec.Ports = append(b.Services.Spec.Ports, service.Spec.Ports...) - }else { - b.Services = &service - } - - b.addLabel(processing_name,processing_id) - -} func (b *ArgoBuilder) addLabel(name string, id string) { argo_name := getArgoName(name,id) @@ -485,23 +330,3 @@ func (b *ArgoBuilder) addLabel(name string, id string) { } } -func (b *ArgoBuilder) addServiceToArgo() error { - service_manifest, err := yaml.Marshal(b.Services) - if err != nil { - logger.Error().Msg("Could not marshal service manifest") - return err - } - - service_template := Template{Name: "workflow-service-pod", - Resource: ServiceResource{ - Action: "create", - SuccessCondition: "status.succeeded > 0", - FailureCondition: "status.failed > 3", - SetOwnerReference: true, - Manifest: string(service_manifest), - }, - } - b.Workflow.Spec.Templates = append(b.Workflow.Spec.Templates, service_template) - - return nil -} \ No newline at end of file From faf67c2ddaab95799125b873619410a703a4574a Mon Sep 17 00:00:00 2001 From: pb Date: Tue, 3 Sep 2024 15:57:35 +0200 Subject: [PATCH 7/9] correct some comments/typo --- main.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index 580c04e..3ef3269 100644 --- a/main.go +++ b/main.go @@ -120,6 +120,8 @@ func getWorkflowId(exec_id string) string { return wf_exec.WorkflowID } +// So far we only log the output from + func executeWorkflow(argo_file_path string) { // var stdout, stderr, stdout_logs, stderr_logs io.ReadCloser var stdout, stderr io.ReadCloser @@ -186,7 +188,7 @@ func logWorkflow(pipe io.ReadCloser, wg *sync.WaitGroup) { // Debug, no logs sent func logPods(pipe io.ReadCloser, name string) { - pods_logger = wf_logger.With().Str("sortie name", name).Logger() + pods_logger = wf_logger.With().Str("pod_name", name).Logger() scanner := bufio.NewScanner(pipe) for scanner.Scan() { log := scanner.Text() @@ -201,7 +203,7 @@ func loadConfig(is_k8s bool, parser *argparse.Parser) { o = initOnion(o) // These variables can only be retrieved in the onion - // Variables that don't depend on the environmen (from conf file), can be loaded after + // Variables that don't depend on the environment (from conf file), can be loaded after // We can't use underscore in the env variable names because it's the delimitor with OCMONITOR too setConf(is_k8s, o, parser) From 072be43b85c300f961f1ca8a008ef65dd091c320 Mon Sep 17 00:00:00 2001 From: pb Date: Tue, 3 Sep 2024 17:46:36 +0200 Subject: [PATCH 8/9] Added ingress todo --- README.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 64321ad..23a80f7 100644 --- a/README.md +++ b/README.md @@ -54,4 +54,11 @@ This command **must return "yes"** - logsPods() function already exists - need to implement the logic to create each pod's logger and start the monitoring routing - [ ] Allow the front to known on which IP the service are reachable - - currently doing it by using `kubectl get nodes -o wide` \ No newline at end of file + - currently doing it by using `kubectl get nodes -o wide` + + +### Adding ingress handling to support reverse proxing + +- Test wether ingress-nginx is running or not + - Do something if not found : stop running and send error log OR start installation +- \ No newline at end of file From 3a7f3f6685cb8b2e652599e5660943ee5417caf6 Mon Sep 17 00:00:00 2001 From: pb Date: Thu, 5 Sep 2024 11:23:43 +0200 Subject: [PATCH 9/9] compatibility with oclib update --- conf/conf.go | 4 ++++ go.mod | 6 +++--- go.sum | 6 ++++++ main.go | 25 ++++++++++++++++++------- 4 files changed, 31 insertions(+), 10 deletions(-) diff --git a/conf/conf.go b/conf/conf.go index 8f0eda4..3de8b82 100644 --- a/conf/conf.go +++ b/conf/conf.go @@ -3,10 +3,14 @@ package conf import "sync" type Config struct { + MongoURL string + Database string LokiURL string + NatsURL string ExecutionID string Timeout int WorkflowID string + Logs string } var instance *Config diff --git a/go.mod b/go.mod index 8d50990..c3605bc 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module oc-monitord go 1.22.0 require ( - cloud.o-forge.io/core/oc-lib v0.0.0-20240828135227-14d6a5f11c4e + cloud.o-forge.io/core/oc-lib v0.0.0-20240904135449-4f0ab6a3760f github.com/akamensky/argparse v1.4.0 github.com/goraz/onion v0.1.3 github.com/nats-io/nats-server/v2 v2.10.18 @@ -42,6 +42,6 @@ require ( golang.org/x/crypto v0.26.0 // indirect golang.org/x/net v0.28.0 // indirect golang.org/x/sync v0.8.0 // indirect - golang.org/x/sys v0.24.0 // indirect - golang.org/x/text v0.17.0 // indirect + golang.org/x/sys v0.25.0 // indirect + golang.org/x/text v0.18.0 // indirect ) diff --git a/go.sum b/go.sum index 6bf2dc7..6e13fdd 100644 --- a/go.sum +++ b/go.sum @@ -40,6 +40,8 @@ cloud.o-forge.io/core/oc-lib v0.0.0-20240826085916-d0e1474f8f34 h1:40XQgwR9HxXSn cloud.o-forge.io/core/oc-lib v0.0.0-20240826085916-d0e1474f8f34/go.mod h1:1hhYh5QWAbYw9cKplQ0ZD9PMgU8t6gPqiYF8sldv1HU= cloud.o-forge.io/core/oc-lib v0.0.0-20240828135227-14d6a5f11c4e h1:/KWO/gIcP5f7T4r00715fNz0Y/Hil6Bj3J1ycuES1Zw= cloud.o-forge.io/core/oc-lib v0.0.0-20240828135227-14d6a5f11c4e/go.mod h1:FIJD0taWLJ5pjQLJ6sfE2KlTkvbmk5SMcyrxdjsaVz0= +cloud.o-forge.io/core/oc-lib v0.0.0-20240904135449-4f0ab6a3760f h1:v9mw3uNg/DJswOvHooMu8/BMedA+vIXbma+8iUwsjUI= +cloud.o-forge.io/core/oc-lib v0.0.0-20240904135449-4f0ab6a3760f/go.mod h1:FIJD0taWLJ5pjQLJ6sfE2KlTkvbmk5SMcyrxdjsaVz0= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/akamensky/argparse v1.4.0 h1:YGzvsTqCvbEZhL8zZu2AiA5nq805NZh75JNj4ajn1xc= github.com/akamensky/argparse v1.4.0/go.mod h1:S5kwC7IuDcEr5VeXtGPRVZ5o/FdhcMlQz4IZQuw64xA= @@ -206,6 +208,8 @@ golang.org/x/sys v0.23.0 h1:YfKFowiIMvtgl1UERQoTPPToxltDeZfbj4H7dVUCwmM= golang.org/x/sys v0.23.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg= golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= +golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -216,6 +220,8 @@ golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4= golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc= golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= +golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= diff --git a/main.go b/main.go index 3ef3269..54c02b1 100644 --- a/main.go +++ b/main.go @@ -20,7 +20,6 @@ import ( "cloud.o-forge.io/core/oc-lib/logs" "cloud.o-forge.io/core/oc-lib/models/workflow_execution" - "cloud.o-forge.io/core/oc-lib/tools" "github.com/akamensky/argparse" "github.com/google/uuid" @@ -63,13 +62,19 @@ func main() { loadConfig(true, nil) } - logs.SetAppName("oc-monitord") - logger = logs.CreateLogger("oc-monitord", conf.GetConfig().LokiURL) + logger = logs.CreateLogger("oc-monitord") logger.Debug().Msg("Loki URL : " + conf.GetConfig().LokiURL) logger.Debug().Msg("Workflow executed : " + conf.GetConfig().ExecutionID) - oclib.Init("oc-monitord","","") + oclib.SetConfig( + conf.GetConfig().MongoURL, + conf.GetConfig().Database, + conf.GetConfig().NatsURL, + conf.GetConfig().LokiURL, + conf.GetConfig().Logs, + ) + oclib.Init("oc-monitord") wf_id := getWorkflowId(conf.GetConfig().ExecutionID) conf.GetConfig().WorkflowID = wf_id @@ -224,7 +229,9 @@ func setConf(is_k8s bool, o *onion.Onion, parser *argparse.Parser) { conf.GetConfig().ExecutionID = o.GetString("workflow") mongo := o.GetStringDefault("mongourl", "mongodb://127.0.0.1:27017") db := o.GetStringDefault("database", "DC_myDC") - tools.SetConfig(mongo, db, "") + + conf.GetConfig().MongoURL = mongo + conf.GetConfig().Database = db } else { url := parser.String("u", "url", &argparse.Options{Required: true, Default: "http://127.0.0.1:3100", Help: "Url to the Loki database logs will be sent to"}) execution := parser.String("e", "execution", &argparse.Options{Required: true, Help: "Execution ID of the workflow to request from oc-catalog API"}) @@ -236,17 +243,21 @@ func setConf(is_k8s bool, o *onion.Onion, parser *argparse.Parser) { fmt.Println(parser.Usage(err)) os.Exit(1) } + + conf.GetConfig().Logs = "debug" + conf.GetConfig().LokiURL = *url + conf.GetConfig().MongoURL = *mongo + conf.GetConfig().Database = *db conf.GetConfig().Timeout = *timeout conf.GetConfig().ExecutionID = *execution - tools.SetConfig(*mongo, *db, "") } } func initOnion(o *onion.Onion) *onion.Onion { - logger = logs.CreateLogger("oc-monitord", "") + logger = logs.CreateLogger("oc-monitord") configFile := "" l3 := onion.NewEnvLayerPrefix("_", "OCMONITORD")