S3 based on config MAP + Rework distant... config

This commit is contained in:
mr
2026-02-25 09:02:24 +01:00
parent 9fb973179b
commit 921ee900ce
6 changed files with 528 additions and 292 deletions

View File

@@ -1,145 +0,0 @@
package workflow_builder
import (
"encoding/json"
"fmt"
"net/http"
"oc-monitord/utils"
"slices"
"time"
oclib "cloud.o-forge.io/core/oc-lib"
"cloud.o-forge.io/core/oc-lib/logs"
"cloud.o-forge.io/core/oc-lib/models/peer"
tools "cloud.o-forge.io/core/oc-lib/tools"
)
type AdmiraltySetter struct {
Id string // ID to identify the execution, correspond to workflow_executions id
NodeName string // Allows to retrieve the name of the node used for this execution on each peer {"peerId": "nodeName"}
}
func (s *AdmiraltySetter) InitializeAdmiralty(localPeerID string, remotePeerID string) error {
logger := logs.GetLogger()
data := oclib.NewRequest(oclib.LibDataEnum(oclib.PEER), "", localPeerID, nil, nil).LoadOne(remotePeerID)
if data.Code != 200 {
logger.Error().Msg("Error while trying to instantiate remote peer " + remotePeerID)
return fmt.Errorf(data.Err)
}
remotePeer := data.ToPeer()
data = oclib.NewRequest(oclib.LibDataEnum(oclib.PEER), "", localPeerID, nil, nil).LoadOne(localPeerID)
if data.Code != 200 {
logger.Error().Msg("Error while trying to instantiate local peer " + remotePeerID)
return fmt.Errorf(data.Err)
}
localPeer := data.ToPeer()
caller := tools.NewHTTPCaller(
map[tools.DataType]map[tools.METHOD]string{
tools.ADMIRALTY_SOURCE: {
tools.POST: "/:id",
},
tools.ADMIRALTY_KUBECONFIG: {
tools.GET: "/:id",
},
tools.ADMIRALTY_SECRET: {
tools.POST: "/:id/" + remotePeerID,
},
tools.ADMIRALTY_TARGET: {
tools.POST: "/:id/" + remotePeerID,
},
tools.ADMIRALTY_NODES: {
tools.GET: "/:id/" + remotePeerID,
},
},
)
logger.Info().Msg("\n\n Creating the Admiralty Source on " + remotePeerID + " ns-" + s.Id)
s.callRemoteExecution(remotePeer, []int{http.StatusCreated, http.StatusConflict}, caller, s.Id, tools.ADMIRALTY_SOURCE, tools.POST, nil, true)
logger.Info().Msg("\n\n Retrieving kubeconfig with the secret on " + remotePeerID + " ns-" + s.Id)
kubeconfig := s.getKubeconfig(remotePeer, caller)
logger.Info().Msg("\n\n Creating a secret from the kubeconfig " + localPeerID + " ns-" + s.Id)
s.callRemoteExecution(localPeer, []int{http.StatusCreated}, caller, s.Id, tools.ADMIRALTY_SECRET, tools.POST, kubeconfig, true)
logger.Info().Msg("\n\n Creating the Admiralty Target on " + localPeerID + " in namespace " + s.Id)
s.callRemoteExecution(localPeer, []int{http.StatusCreated, http.StatusConflict}, caller, s.Id, tools.ADMIRALTY_TARGET, tools.POST, nil, true)
logger.Info().Msg("\n\n Checking for the creation of the admiralty node on " + localPeerID + " ns-" + s.Id)
s.checkNodeStatus(localPeer, caller)
return nil
}
func (s *AdmiraltySetter) getKubeconfig(peer *peer.Peer, caller *tools.HTTPCaller) map[string]string {
var kubedata map[string]string
s.callRemoteExecution(peer, []int{http.StatusOK}, caller, s.Id, tools.ADMIRALTY_KUBECONFIG, tools.GET, nil, true)
if caller.LastResults["body"] == nil || len(caller.LastResults["body"].([]byte)) == 0 {
l := utils.GetLogger()
l.Error().Msg("Something went wrong when retrieving data from Get call for kubeconfig")
panic(0)
}
err := json.Unmarshal(caller.LastResults["body"].([]byte), &kubedata)
if err != nil {
l := utils.GetLogger()
l.Error().Msg("Something went wrong when unmarshalling data from Get call for kubeconfig")
panic(0)
}
return kubedata
}
func (*AdmiraltySetter) callRemoteExecution(peer *peer.Peer, expectedCode []int, caller *tools.HTTPCaller, dataID string, dt tools.DataType, method tools.METHOD, body interface{}, panicCode bool) {
l := utils.GetLogger()
_, err := peer.LaunchPeerExecution(peer.UUID, dataID, dt, method, body, caller)
if err != nil {
l.Error().Msg("Error when executing on peer at" + peer.APIUrl)
l.Error().Msg(err.Error())
panic(0)
}
if !slices.Contains(expectedCode, caller.LastResults["code"].(int)) {
l.Error().Msg(fmt.Sprint("Didn't receive the expected code :", caller.LastResults["code"], "when expecting", expectedCode))
if _, ok := caller.LastResults["body"]; ok {
l.Info().Msg(string(caller.LastResults["body"].([]byte)))
}
if panicCode {
panic(0)
}
}
}
func (s *AdmiraltySetter) storeNodeName(caller *tools.HTTPCaller) {
var data map[string]interface{}
if resp, ok := caller.LastResults["body"]; ok {
json.Unmarshal(resp.([]byte), &data)
}
if node, ok := data["node"]; ok {
metadata := node.(map[string]interface{})["metadata"]
name := metadata.(map[string]interface{})["name"].(string)
s.NodeName = name
} else {
l := utils.GetLogger()
l.Error().Msg("Could not retrieve data about the recently created node")
panic(0)
}
}
func (s *AdmiraltySetter) checkNodeStatus(localPeer *peer.Peer, caller *tools.HTTPCaller) {
for i := range 5 {
time.Sleep(10 * time.Second) // let some time for kube to generate the node
s.callRemoteExecution(localPeer, []int{http.StatusOK}, caller, s.Id, tools.ADMIRALTY_NODES, tools.GET, nil, false)
if caller.LastResults["code"] == 200 {
s.storeNodeName(caller)
return
}
if i == 5 {
logger.Error().Msg("Node on " + localPeer.Name + " was never found, panicking !")
panic(0)
}
logger.Info().Msg("Could not verify that node is up. Retrying...")
}
}

View File

@@ -1,20 +1,20 @@
// A class that translates the informations held in the graph object
// via its lists of components into an argo file, using the a list of
// link ID to build the dag
// Package workflow_builder traduit les informations du graphe d'un Workflow
// (ses composants, ses liens) en un fichier YAML Argo Workflow prêt à être
// soumis à un cluster Kubernetes. Le point d'entrée principal est ArgoBuilder.
package workflow_builder
import (
"encoding/json"
"fmt"
"oc-monitord/conf"
. "oc-monitord/models"
tools2 "oc-monitord/tools"
"os"
"strings"
"time"
oclib "cloud.o-forge.io/core/oc-lib"
oclib_config "cloud.o-forge.io/core/oc-lib/config"
"cloud.o-forge.io/core/oc-lib/logs"
"cloud.o-forge.io/core/oc-lib/models/common/enum"
"cloud.o-forge.io/core/oc-lib/models/peer"
@@ -24,21 +24,34 @@ import (
"cloud.o-forge.io/core/oc-lib/models/workflow/graph"
"cloud.o-forge.io/core/oc-lib/models/workflow_execution"
"cloud.o-forge.io/core/oc-lib/tools"
"github.com/nats-io/nats.go"
"github.com/nwtgck/go-fakelish"
"github.com/rs/zerolog"
"gopkg.in/yaml.v3"
)
// logger est le logger zerolog partagé au sein du package, initialisé à
// chaque appel de CreateDAG pour récupérer la configuration courante.
var logger zerolog.Logger
// ArgoBuilder est le constructeur principal du fichier Argo Workflow.
// Il porte l'état de la construction (workflow source, templates générés,
// services k8s à créer, timeout global, liste des peers distants impliqués).
type ArgoBuilder struct {
// OriginWorkflow est le workflow métier Open Cloud dont on construit la représentation Argo.
OriginWorkflow *w.Workflow
Workflow Workflow
Services []*Service
Timeout int
RemotePeers []string
// Workflow est la structure YAML Argo en cours de construction.
Workflow Workflow
// Services liste les services Kubernetes à exposer pour les processings "IsService".
Services []*Service
// Timeout est la durée maximale d'exécution en secondes (activeDeadlineSeconds).
Timeout int
// RemotePeers contient les IDs des peers distants détectés via Admiralty.
RemotePeers []string
}
// Workflow est la structure racine du fichier YAML Argo Workflow.
// Elle correspond exactement au format attendu par le contrôleur Argo.
type Workflow struct {
ApiVersion string `yaml:"apiVersion"`
Kind string `yaml:"kind"`
@@ -48,6 +61,8 @@ type Workflow struct {
Spec Spec `yaml:"spec,omitempty"`
}
// getDag retourne le pointeur sur le template "dag" du workflow.
// S'il n'existe pas encore, il est créé et ajouté à la liste des templates.
func (b *Workflow) getDag() *Dag {
for _, t := range b.Spec.Templates {
if t.Name == "dag" {
@@ -58,7 +73,10 @@ func (b *Workflow) getDag() *Dag {
return b.Spec.Templates[len(b.Spec.Templates)-1].Dag
}
// Spec contient la spécification complète du workflow Argo :
// compte de service, point d'entrée, volumes, templates et timeout.
type Spec struct {
ArtifactRepositoryRef
ServiceAccountName string `yaml:"serviceAccountName,omitempty"`
Entrypoint string `yaml:"entrypoint"`
Arguments []Parameter `yaml:"arguments,omitempty"`
@@ -67,12 +85,21 @@ type Spec struct {
Timeout int `yaml:"activeDeadlineSeconds,omitempty"`
}
// TODO: found on a processing instance linked to storage
// add s3, gcs, azure, etc if needed on a link between processing and storage
// CreateDAG est le point d'entrée de la construction du DAG Argo.
// Il crée tous les templates (un par processing / native tool / sous-workflow),
// configure les volumes persistants, positionne les métadonnées globales du
// workflow et retourne :
// - le nombre de tâches dans le DAG,
// - les noms des premières tâches (sans dépendances),
// - les noms des dernières tâches (dont personne ne dépend),
// - une éventuelle erreur.
//
// Le paramètre write est conservé pour usage futur (écriture effective du YAML).
// TODO: gérer S3, GCS, Azure selon le type de stockage lié au processing.
func (b *ArgoBuilder) CreateDAG(exec *workflow_execution.WorkflowExecution, namespace string, write bool) (int, []string, []string, error) {
logger = logs.GetLogger()
logger.Info().Msg(fmt.Sprint("Creating DAG ", b.OriginWorkflow.Graph.Items))
// handle services by checking if there is only one processing with hostname and port
// Crée un template Argo pour chaque nœud du graphe et collecte les volumes.
firstItems, lastItems, volumes := b.createTemplates(exec, namespace)
b.createVolumes(exec, volumes)
@@ -90,10 +117,17 @@ func (b *ArgoBuilder) CreateDAG(exec *workflow_execution.WorkflowExecution, name
return len(b.Workflow.getDag().Tasks), firstItems, lastItems, nil
}
// createTemplates parcourt tous les nœuds du graphe (processings, native tools,
// sous-workflows) et génère les templates Argo correspondants.
// Elle gère également le recâblage des dépendances DAG entre sous-workflows
// imbriqués, et l'ajout du pod de service si nécessaire.
// Retourne les premières tâches, les dernières tâches et les volumes à créer.
func (b *ArgoBuilder) createTemplates(exec *workflow_execution.WorkflowExecution, namespace string) ([]string, []string, []VolumeMount) {
volumes := []VolumeMount{}
firstItems := []string{}
lastItems := []string{}
// --- Processings ---
for _, item := range b.OriginWorkflow.GetGraphItems(b.OriginWorkflow.Graph.IsProcessing) {
index := 0
_, res := item.GetResource()
@@ -110,6 +144,8 @@ func (b *ArgoBuilder) createTemplates(exec *workflow_execution.WorkflowExecution
namespace,
item.ID, item.Processing, volumes, firstItems, lastItems)
}
// --- Native Tools de type WORKFLOW_EVENT uniquement ---
for _, item := range b.OriginWorkflow.GetGraphItems(b.OriginWorkflow.Graph.IsNativeTool) {
if item.NativeTool.Kind != int(native_tools.WORKFLOW_EVENT) {
continue
@@ -124,6 +160,8 @@ func (b *ArgoBuilder) createTemplates(exec *workflow_execution.WorkflowExecution
volumes, firstItems, lastItems = b.createArgoTemplates(exec,
namespace, item.ID, item.NativeTool, volumes, firstItems, lastItems)
}
// --- Sous-workflows : chargement, construction récursive et fusion du DAG ---
firstWfTasks := map[string][]string{}
latestWfTasks := map[string][]string{}
relatedWfTasks := map[string][]string{}
@@ -140,18 +178,22 @@ func (b *ArgoBuilder) createTemplates(exec *workflow_execution.WorkflowExecution
continue
}
firstWfTasks[wf] = fi
if ok, depsOfIds := subBuilder.isArgoDependancy(wf); ok { // IS BEFORE
if ok, depsOfIds := subBuilder.isArgoDependancy(wf); ok { // le sous-workflow est une dépendance d'autre chose
latestWfTasks[wf] = li
relatedWfTasks[wf] = depsOfIds
}
// Fusion des tâches, templates, volumes et arguments du sous-workflow dans le DAG principal.
subDag := subBuilder.Workflow.getDag()
d := b.Workflow.getDag()
d.Tasks = append(d.Tasks, subDag.Tasks...) // add the tasks of the subworkflow to the main workflow
d.Tasks = append(d.Tasks, subDag.Tasks...)
b.Workflow.Spec.Templates = append(b.Workflow.Spec.Templates, subBuilder.Workflow.Spec.Templates...)
b.Workflow.Spec.Volumes = append(b.Workflow.Spec.Volumes, subBuilder.Workflow.Spec.Volumes...)
b.Workflow.Spec.Arguments = append(b.Workflow.Spec.Arguments, subBuilder.Workflow.Spec.Arguments...)
b.Services = append(b.Services, subBuilder.Services...)
}
// Recâblage : les tâches qui dépendaient du sous-workflow dépendent désormais
// de sa dernière tâche réelle (latestWfTasks).
for wfID, depsOfIds := range relatedWfTasks {
for _, dep := range depsOfIds {
for _, task := range b.Workflow.getDag().Tasks {
@@ -171,6 +213,9 @@ func (b *ArgoBuilder) createTemplates(exec *workflow_execution.WorkflowExecution
}
}
}
// Les premières tâches du sous-workflow héritent des dépendances
// que le sous-workflow avait vis-à-vis du DAG principal.
for wfID, fi := range firstWfTasks {
deps := b.getArgoDependencies(wfID)
if len(deps) > 0 {
@@ -183,6 +228,8 @@ func (b *ArgoBuilder) createTemplates(exec *workflow_execution.WorkflowExecution
}
}
}
// Si des services Kubernetes sont nécessaires, on ajoute le pod dédié.
if b.Services != nil {
dag := b.Workflow.getDag()
dag.Tasks = append(dag.Tasks, Task{Name: "workflow-service-pod", Template: "workflow-service-pod"})
@@ -191,6 +238,13 @@ func (b *ArgoBuilder) createTemplates(exec *workflow_execution.WorkflowExecution
return firstItems, lastItems, volumes
}
// createArgoTemplates crée le template Argo pour un nœud du graphe (processing
// ou native tool). Il :
// 1. Ajoute la tâche au DAG avec ses dépendances.
// 2. Crée le template de container (ou d'événement pour les native tools).
// 3. Ajoute les annotations Admiralty si le processing est hébergé sur un peer distant.
// 4. Crée un service Kubernetes si le processing est déclaré IsService.
// 5. Configure les annotations de stockage (S3, volumes locaux).
func (b *ArgoBuilder) createArgoTemplates(
exec *workflow_execution.WorkflowExecution,
namespace string,
@@ -199,9 +253,12 @@ func (b *ArgoBuilder) createArgoTemplates(
volumes []VolumeMount,
firstItems []string,
lastItems []string) ([]VolumeMount, []string, []string) {
_, firstItems, lastItems = b.addTaskToArgo(exec, b.Workflow.getDag(), id, obj, firstItems, lastItems)
template := &Template{Name: getArgoName(obj.GetName(), id)}
logger.Info().Msg(fmt.Sprint("Creating template for", template.Name))
// Vérifie si le processing est sur un peer distant (Admiralty).
isReparted, peer := b.isReparted(obj, id)
if obj.GetType() == tools.PROCESSING_RESOURCE.String() {
template.CreateContainer(exec, obj.(*resources.ProcessingResource), b.Workflow.getDag())
@@ -214,11 +271,13 @@ func (b *ArgoBuilder) createArgoTemplates(
b.RemotePeers = append(b.RemotePeers, peer.GetID())
template.AddAdmiraltyAnnotations(peer.GetID())
}
// get datacenter from the processing
// Si le processing expose un service Kubernetes, on l'enregistre et on
// applique le label "app" pour que le Service puisse le sélectionner.
if obj.GetType() == tools.PROCESSING_RESOURCE.String() && obj.(*resources.ProcessingResource).IsService {
b.CreateService(exec, id, obj)
template.Metadata.Labels = make(map[string]string)
template.Metadata.Labels["app"] = "oc-service-" + obj.GetName() // Construct the template for the k8s service and add a link in graph between k8s service and processing
template.Metadata.Labels["app"] = "oc-service-" + obj.GetName()
}
volumes = b.addStorageAnnotations(exec, id, template, namespace, volumes)
@@ -226,26 +285,48 @@ func (b *ArgoBuilder) createArgoTemplates(
return volumes, firstItems, lastItems
}
// addStorageAnnotations parcourt tous les nœuds de stockage liés au processing
// identifié par id. Pour chaque lien de stockage :
// - Construit le nom de l'artefact Argo (lecture ou écriture).
// - Pour les stockages S3 : appelle waitForConsiders (STORAGE_RESOURCE) pour
// attendre la validation PB_CONSIDERS avant de configurer les annotations S3.
// - Pour les volumes locaux : ajoute un VolumeMount dans le container.
func (b *ArgoBuilder) addStorageAnnotations(exec *workflow_execution.WorkflowExecution, id string, template *Template, namespace string, volumes []VolumeMount) []VolumeMount {
related := b.OriginWorkflow.GetByRelatedProcessing(id, b.OriginWorkflow.Graph.IsStorage) // Retrieve all of the storage node linked to the processing for which we create the template
// Récupère tous les nœuds de stockage connectés au processing courant.
related := b.OriginWorkflow.GetByRelatedProcessing(id, b.OriginWorkflow.Graph.IsStorage)
for _, r := range related {
storage := r.Node.(*resources.StorageResource)
for _, linkToStorage := range r.Links {
for _, rw := range linkToStorage.StorageLinkInfos {
var art Artifact
artifactBaseName := strings.Join(strings.Split(storage.GetName(), " "), "-") + "-" + strings.Replace(rw.FileName, ".", "-", -1) // Parameter/Artifact name must consist of alpha-numeric characters, '_' or '-'
// Le nom de l'artefact doit être alphanumérique + '-' ou '_'.
artifactBaseName := strings.Join(strings.Split(storage.GetName(), " "), "-") + "-" + strings.Replace(rw.FileName, ".", "-", -1)
if rw.Write {
art = Artifact{Path: template.ReplacePerEnv(rw.Source, linkToStorage.Env)} // When we are writing to the s3 the Path element is the path to the file in the pod
// Écriture vers S3 : Path = chemin du fichier dans le pod.
art = Artifact{Path: template.ReplacePerEnv(rw.Source, linkToStorage.Env)}
art.Name = artifactBaseName + "-input-write"
} else {
art = Artifact{Path: template.ReplacePerEnv(rw.Destination+"/"+rw.FileName, linkToStorage.Env)} // When we are reading from the s3 the Path element in pod should be the destination of the file
// Lecture depuis S3 : Path = destination dans le pod.
art = Artifact{Path: template.ReplacePerEnv(rw.Destination+"/"+rw.FileName, linkToStorage.Env)}
art.Name = artifactBaseName + "-input-read"
}
if storage.StorageType == enum.S3 {
b.addS3annotations(exec, &art, template, rw, linkToStorage, storage, namespace)
// Pour chaque ressource de compute liée à ce stockage S3,
// on notifie via NATS et on attend la validation PB_CONSIDERS
// avec DataType = STORAGE_RESOURCE avant de continuer.
for _, r := range b.getStorageRelatedProcessing(storage.GetID()) {
waitForConsiders(exec.ExecutionsID, tools.STORAGE_RESOURCE, ArgoKubeEvent{
ExecutionsID: exec.ExecutionsID,
DestPeerID: r.GetID(),
Type: tools.STORAGE_RESOURCE,
SourcePeerID: storage.GetCreatorID(),
OriginID: conf.GetConfig().PeerID,
})
}
// Configure la référence au dépôt d'artefacts S3 dans le Spec.
b.addS3annotations(storage, namespace)
}
if rw.Write {
@@ -255,6 +336,8 @@ func (b *ArgoBuilder) addStorageAnnotations(exec *workflow_execution.WorkflowExe
}
}
}
// Si l'instance de stockage est locale, on monte un volume persistant.
index := 0
if s, ok := exec.SelectedInstances[storage.GetID()]; ok {
index = s
@@ -271,107 +354,75 @@ func (b *ArgoBuilder) addStorageAnnotations(exec *workflow_execution.WorkflowExe
return volumes
}
func (b *ArgoBuilder) addS3annotations(exec *workflow_execution.WorkflowExecution, art *Artifact, template *Template, rw graph.StorageProcessingGraphLink, linkToStorage graph.GraphLink, storage *resources.StorageResource, namespace string) {
art.S3 = &Key{
// Key: template.ReplacePerEnv(rw.Destination+"/"+rw.FileName, linkToStorage.Env),
Insecure: true, // temporary
}
if rw.Write {
art.S3.Key = rw.Destination + "/" + rw.FileName
} else {
art.S3.Key = rw.Source
}
index := 0
if d, ok := exec.SelectedInstances[storage.GetID()]; ok {
index = d
}
sel := storage.GetSelectedInstance(&index)
// v0.1 : add the storage.Source to the s3 object
// v0.2 : test if the storage.Source exists in the configMap and quit if not
// v1 : v0.2 + if doesn't exist edit/create the configMap with the response from API call
if sel != nil {
b.addAuthInformation(exec, storage, namespace, art)
art.S3.Bucket = namespace // DEFAULT : will need to update this to create an unique
art.S3.EndPoint = sel.(*resources.StorageResourceInstance).Source
}
}
func (b *ArgoBuilder) addAuthInformation(exec *workflow_execution.WorkflowExecution, storage *resources.StorageResource, namespace string, art *Artifact) {
index := 0
if d, ok := exec.SelectedInstances[storage.GetID()]; ok {
index = d
}
sel := storage.GetSelectedInstance(&index)
tool, err := tools2.NewService(conf.GetConfig().Mode)
if err != nil || tool == nil {
logger.Fatal().Msg("Could not create the access secret :" + err.Error())
}
secretName, err := b.SetupS3Credentials(storage, namespace, tool) // this method return should be updated once we have decided how to retrieve credentials
if err == nil {
art.S3.AccessKeySecret = &Secret{
Name: secretName,
Key: "access-key",
}
art.S3.SecretKeySecret = &Secret{
Name: secretName,
Key: "secret-key",
// getStorageRelatedProcessing retourne la liste des ressources de compute
// connectées (via un processing intermédiaire) au stockage identifié par storageId.
// Ces ressources sont utilisées pour construire les ArgoKubeEvent destinés
// à la validation NATS.
func (b *ArgoBuilder) getStorageRelatedProcessing(storageId string) (res []resources.ResourceInterface) {
var storageLinks []graph.GraphLink
// On ne conserve que les liens impliquant ce stockage.
for _, link := range b.OriginWorkflow.Graph.Links {
if link.Destination.ID == storageId || link.Source.ID == storageId {
storageLinks = append(storageLinks, link)
}
}
art.S3.Key = strings.ReplaceAll(art.S3.Key, sel.(*resources.StorageResourceInstance).Source+"/", "")
art.S3.Key = strings.ReplaceAll(art.S3.Key, sel.(*resources.StorageResourceInstance).Source, "")
splits := strings.Split(art.S3.EndPoint, "/")
if len(splits) > 1 {
art.S3.Bucket = splits[0]
art.S3.EndPoint = strings.Join(splits[1:], "/")
} else {
art.S3.Bucket = splits[0]
}
}
func (b *ArgoBuilder) SetupS3Credentials(storage *resources.StorageResource, namespace string, tool tools2.Tool) (string, error) {
s := tool.GetS3Secret(storage.UUID, namespace)
// var s *v1.Secret
accessKey, secretKey := retrieveMinioCredential("peer", namespace)
if s == nil {
id, err := tool.CreateAccessSecret(
accessKey,
secretKey,
storage.UUID,
namespace,
)
if err != nil {
l := oclib.GetLogger()
l.Fatal().Msg("Error when creating the secret holding credentials for S3 access in " + namespace + " : " + err.Error())
for _, link := range storageLinks {
var resourceId string
// L'opposé du lien est soit la source soit la destination selon la direction.
if link.Source.ID != storageId {
resourceId = link.Source.ID
} else {
resourceId = link.Destination.ID
}
// Si l'opposé est un processing, on récupère ses ressources de compute.
if b.OriginWorkflow.Graph.IsProcessing(b.OriginWorkflow.Graph.Items[resourceId]) {
res = append(res, b.getComputeProcessing(resourceId)...)
}
return id, nil
}
return s.Name, nil
return
}
// This method needs to evolve to an API call to the peer passed as a parameter
func retrieveMinioCredential(peer string, namespace string) (string, string) {
return "hF9wRGog75JuMdshWeEZ", "OwXXJkVQyb5l1aVPdOegKOtDJGoP1dJYeo8O7mDW"
// getComputeProcessing retourne toutes les ressources de compute attachées
// au processing identifié par processingId dans le graphe du workflow.
func (b *ArgoBuilder) getComputeProcessing(processingId string) (res []resources.ResourceInterface) {
arr := []resources.ResourceInterface{}
computeRel := b.OriginWorkflow.GetByRelatedProcessing(processingId, b.OriginWorkflow.Graph.IsCompute)
for _, rel := range computeRel {
arr = append(arr, rel.Node)
}
return arr
}
// addS3annotations configure la référence au dépôt d'artefacts S3 dans le Spec
// du workflow Argo. La ConfigMap et la clé sont dérivées de l'ID du stockage.
// Le namespace est conservé en signature pour une évolution future.
func (b *ArgoBuilder) addS3annotations(storage *resources.StorageResource, namespace string) {
b.Workflow.Spec.ArtifactRepositoryRef = ArtifactRepositoryRef{
ConfigMap: storage.GetID() + "-artifact-repository",
Key: storage.GetID() + "-s3-local",
}
}
// addTaskToArgo ajoute une tâche au DAG Argo pour le nœud graphItemID.
// Elle résout les dépendances DAG, propage les paramètres d'environnement,
// d'entrée et de sortie de l'instance sélectionnée, et met à jour les listes
// firstItems / lastItems utilisées pour le recâblage des sous-workflows.
func (b *ArgoBuilder) addTaskToArgo(exec *workflow_execution.WorkflowExecution, dag *Dag, graphItemID string, processing resources.ResourceInterface,
firstItems []string, lastItems []string) (*Dag, []string, []string) {
unique_name := getArgoName(processing.GetName(), graphItemID)
step := Task{Name: unique_name, Template: unique_name}
index := 0
if d, ok := exec.SelectedInstances[processing.GetID()]; ok {
index = d
}
instance := processing.GetSelectedInstance(&index)
if instance != nil {
// Propagation des variables d'environnement, entrées et sorties
// de l'instance vers les paramètres de la tâche Argo.
for _, value := range instance.(*resources.ProcessingInstance).Env {
step.Arguments.Parameters = append(step.Arguments.Parameters, Parameter{
Name: value.Name,
@@ -391,7 +442,10 @@ func (b *ArgoBuilder) addTaskToArgo(exec *workflow_execution.WorkflowExecution,
})
}
}
step.Dependencies = b.getArgoDependencies(graphItemID)
// Détermine si ce nœud est une première ou une dernière tâche du DAG.
name := ""
if b.OriginWorkflow.Graph.Items[graphItemID].Processing != nil {
name = b.OriginWorkflow.Graph.Items[graphItemID].Processing.GetName()
@@ -405,11 +459,15 @@ func (b *ArgoBuilder) addTaskToArgo(exec *workflow_execution.WorkflowExecution,
if ok, _ := b.isArgoDependancy(graphItemID); !ok && name != "" {
lastItems = append(lastItems, getArgoName(name, graphItemID))
}
dag.Tasks = append(dag.Tasks, step)
return dag, firstItems, lastItems
}
func (b *ArgoBuilder) createVolumes(exec *workflow_execution.WorkflowExecution, volumes []VolumeMount) { // TODO : one think about remote volume but TG
// createVolumes crée les PersistentVolumeClaims Argo (volumeClaimTemplates)
// pour chaque volume local référencé dans les templates de processing.
// TODO: gérer les volumes distants.
func (b *ArgoBuilder) createVolumes(exec *workflow_execution.WorkflowExecution, volumes []VolumeMount) {
for _, volume := range volumes {
index := 0
if s, ok := exec.SelectedInstances[volume.Storage.GetID()]; ok {
@@ -424,6 +482,10 @@ func (b *ArgoBuilder) createVolumes(exec *workflow_execution.WorkflowExecution,
}
}
// isArgoDependancy vérifie si le nœud identifié par id est une dépendance
// d'au moins un autre nœud du DAG (i.e. s'il existe un lien sortant vers
// un processing ou un workflow).
// Retourne true + la liste des noms Argo des nœuds qui en dépendent.
func (b *ArgoBuilder) isArgoDependancy(id string) (bool, []string) {
dependancyOfIDs := []string{}
isDeps := false
@@ -446,6 +508,8 @@ func (b *ArgoBuilder) isArgoDependancy(id string) (bool, []string) {
return isDeps, dependancyOfIDs
}
// getArgoDependencies retourne la liste des noms de tâches Argo dont dépend
// le nœud identifié par id (liens entrants depuis des processings).
func (b *ArgoBuilder) getArgoDependencies(id string) (dependencies []string) {
for _, link := range b.OriginWorkflow.Graph.Links {
if _, ok := b.OriginWorkflow.Graph.Items[link.Source.ID]; !ok {
@@ -462,6 +526,9 @@ func (b *ArgoBuilder) getArgoDependencies(id string) (dependencies []string) {
return
}
// getArgoName construit le nom unique d'une tâche / template Argo à partir
// du nom humain de la ressource et de son ID dans le graphe.
// Les espaces sont remplacés par des tirets et tout est mis en minuscules.
func getArgoName(raw_name string, component_id string) (formatedName string) {
formatedName = strings.ReplaceAll(raw_name, " ", "-")
formatedName += "-" + component_id
@@ -469,8 +536,10 @@ func getArgoName(raw_name string, component_id string) (formatedName string) {
return
}
// Verify if a processing resource is attached to another Compute than the one hosting
// the current Open Cloud instance. If true return the peer ID to contact
// isReparted vérifie si le processing est hébergé sur un Compute appartenant
// à un peer distant (Relation != 1, i.e. pas le peer local).
// Si c'est le cas, elle retourne true et le Peer concerné pour qu'Admiralty
// puisse router les pods vers le bon cluster.
func (b *ArgoBuilder) isReparted(processing resources.ResourceInterface, graphID string) (bool, *peer.Peer) {
computeAttached := b.retrieveProcessingCompute(graphID)
if computeAttached == nil {
@@ -478,7 +547,7 @@ func (b *ArgoBuilder) isReparted(processing resources.ResourceInterface, graphID
panic(0)
}
// Creates an accessor srtictly for Peer Collection
// Résolution du Peer propriétaire du Compute via l'API oc-lib.
req := oclib.NewRequest(oclib.LibDataEnum(oclib.PEER), "", "", nil, nil)
if req == nil {
fmt.Println("TODO : handle error when trying to create a request on the Peer Collection")
@@ -494,15 +563,18 @@ func (b *ArgoBuilder) isReparted(processing resources.ResourceInterface, graphID
peer := res.ToPeer()
isNotReparted := peer.State == 1
// Relation == 1 signifie "moi-même" : le processing est local.
isNotReparted := peer.Relation == 1
logger.Info().Msg(fmt.Sprint("Result IsMySelf for ", peer.UUID, " : ", isNotReparted))
return !isNotReparted, peer
}
// retrieveProcessingCompute parcourt les liens du graphe pour retrouver
// la ressource de Compute directement connectée au nœud graphID.
// Retourne nil si aucun Compute n'est trouvé.
func (b *ArgoBuilder) retrieveProcessingCompute(graphID string) *resources.ComputeResource {
for _, link := range b.OriginWorkflow.Graph.Links {
// If a link contains the id of the processing
var oppositeId string
if link.Source.ID == graphID {
oppositeId = link.Destination.ID
@@ -518,32 +590,142 @@ func (b *ArgoBuilder) retrieveProcessingCompute(graphID string) *resources.Compu
continue
}
}
}
return nil
}
// Execute the last actions once the YAML file for the Argo Workflow is created
// waitForConsiders publie un ArgoKubeEvent sur le canal NATS ARGO_KUBE_EVENT
// puis se bloque jusqu'à réception d'un PropalgationMessage vérifiant :
// - Action == PB_CONSIDERS
// - DataType == dataType (COMPUTE_RESOURCE ou STORAGE_RESOURCE)
// - Payload décodé en JSON contenant "executions_id" == executionsId
//
// Cela garantit que l'infrastructure distante (Admiralty ou Minio) a bien
// pris en compte la demande avant que la construction du workflow continue.
// Un timeout de 5 minutes est appliqué pour éviter un blocage indéfini.
func waitForConsiders(executionsId string, dataType tools.DataType, event ArgoKubeEvent) {
// Sérialise l'événement et le publie sur ARGO_KUBE_EVENT.
b, err := json.Marshal(event)
if err != nil {
logger.Error().Msg("Cannot marshal ArgoKubeEvent: " + err.Error())
return
}
tools.NewNATSCaller().SetNATSPub(tools.ARGO_KUBE_EVENT, tools.NATSResponse{
FromApp: "oc-monitord",
Datatype: dataType,
User: "root",
Method: int(tools.PROPALGATION_EVENT),
Payload: b,
})
// Connexion NATS pour écouter la réponse PB_CONSIDERS.
natsURL := oclib_config.GetConfig().NATSUrl
if natsURL == "" {
logger.Error().Msg("NATS_SERVER not set, skipping PB_CONSIDERS wait")
return
}
nc, err := nats.Connect(natsURL)
if err != nil {
logger.Error().Msg("NATS connect error waiting for PB_CONSIDERS: " + err.Error())
return
}
defer nc.Close()
// Souscription au canal PROPALGATION_EVENT avec un buffer de 64 messages.
ch := make(chan *nats.Msg, 64)
sub, err := nc.ChanSubscribe(tools.PROPALGATION_EVENT.GenerateKey(), ch)
if err != nil {
logger.Error().Msg("NATS subscribe error waiting for PB_CONSIDERS: " + err.Error())
return
}
defer sub.Unsubscribe()
timeout := time.After(5 * time.Minute)
for {
select {
case msg := <-ch:
// Désérialise le message en PropalgationMessage.
var pm tools.PropalgationMessage
if err := json.Unmarshal(msg.Data, &pm); err != nil {
continue
}
// Filtre : action, type de données.
if pm.Action != tools.PB_CONSIDERS || pm.DataType != int(dataType) {
continue
}
// Filtre : executions_id dans le Payload du PropalgationMessage.
var body struct {
ExecutionsID string `json:"executions_id"`
}
if err := json.Unmarshal(pm.Payload, &body); err != nil {
continue
}
if body.ExecutionsID != executionsId {
continue
}
logger.Info().Msg(fmt.Sprintf("PB_CONSIDERS received for executions_id=%s datatype=%s", executionsId, dataType.String()))
return
case <-timeout:
logger.Warn().Msg(fmt.Sprintf("Timeout waiting for PB_CONSIDERS executions_id=%s datatype=%s", executionsId, dataType.String()))
return
}
}
}
// ArgoKubeEvent est la structure publiée sur NATS lors de la demande de
// provisionnement d'une ressource distante (Admiralty ou stockage S3).
// Le champ OriginID identifie le peer initiateur : c'est vers lui que la
// réponse PB_CONSIDERS sera routée par le système de propagation.
type ArgoKubeEvent struct {
// ExecutionsID est l'identifiant de l'exécution de workflow en cours.
ExecutionsID string `json:"executions_id"`
// DestPeerID est le peer de destination (compute ou peer S3 cible).
DestPeerID string `json:"dest_peer_id"`
// Type indique la nature de la ressource : COMPUTE_RESOURCE ou STORAGE_RESOURCE.
Type tools.DataType `json:"data_type"`
// SourcePeerID est le peer source de la ressource demandée.
SourcePeerID string `json:"source_peer_id"`
// OriginID est le peer qui a initié la demande de provisionnement ;
// la réponse PB_CONSIDERS lui sera renvoyée.
OriginID string `json:"origin_id"`
}
// CompleteBuild finalise la construction du workflow Argo après la génération
// du DAG. Elle effectue dans l'ordre :
// 1. Pour chaque peer distant (Admiralty) : publie un ArgoKubeEvent de type
// COMPUTE_RESOURCE et attend la validation PB_CONSIDERS via waitForConsiders.
// 2. Met à jour les annotations Admiralty des templates avec le nom de cluster
// construit à partir du peerId et de l'executionsId.
// 3. Sérialise le workflow en YAML et l'écrit dans ./argo_workflows/.
//
// Retourne le chemin du fichier YAML généré.
func (b *ArgoBuilder) CompleteBuild(executionsId string) (string, error) {
logger.Info().Msg(fmt.Sprint("DEV :: Completing build"))
setter := AdmiraltySetter{Id: executionsId}
// Setup admiralty for each node
logger.Info().Msg("DEV :: Completing build")
// --- Étape 1 : validation Admiralty pour chaque peer distant ---
for _, peer := range b.RemotePeers {
logger.Info().Msg(fmt.Sprint("DEV :: Launching Admiralty Setup for ", peer))
setter.InitializeAdmiralty(conf.GetConfig().PeerID, peer)
// Publie l'événement COMPUTE_RESOURCE et attend PB_CONSIDERS (bloquant).
waitForConsiders(executionsId, tools.COMPUTE_RESOURCE, ArgoKubeEvent{
ExecutionsID: executionsId,
Type: tools.COMPUTE_RESOURCE,
DestPeerID: conf.GetConfig().PeerID,
SourcePeerID: peer,
OriginID: conf.GetConfig().PeerID,
})
}
// Update the name of the admiralty node to use
// --- Étape 2 : mise à jour du nom de cluster Admiralty ---
// Le nom final du cluster cible est "target-<peerId>-<executionsId>".
for _, template := range b.Workflow.Spec.Templates {
if len(template.Metadata.Annotations) > 0 {
if peerId, ok := template.Metadata.Annotations["multicluster.admiralty.io/clustername"]; ok {
template.Metadata.Annotations["multicluster.admiralty.io/clustername"] = "target-" + oclib.GetConcatenatedName(peerId, executionsId)
template.Metadata.Annotations["multicluster.admiralty.io/clustername"] = "target-" + tools.GetConcatenatedName(peerId, executionsId)
}
}
}
// Generate the YAML file
// --- Étape 3 : génération et écriture du fichier YAML ---
random_name := fakelish.GenerateFakeWord(5, 8) + "-" + fakelish.GenerateFakeWord(5, 8)
b.Workflow.Metadata.Name = "oc-monitor-" + random_name
logger = oclib.GetLogger()
@@ -552,12 +734,11 @@ func (b *ArgoBuilder) CompleteBuild(executionsId string) (string, error) {
logger.Error().Msg("Could not transform object to yaml file")
return "", err
}
// Give a unique name to each argo file with its timestamp DD:MM:YYYY_hhmmss
// Nom de fichier horodaté au format DD_MM_YYYY_hhmmss.
current_timestamp := time.Now().Format("02_01_2006_150405")
file_name := random_name + "_" + current_timestamp + ".yml"
workflows_dir := "./argo_workflows/"
err = os.WriteFile(workflows_dir+file_name, []byte(yamlified), 0660)
if err != nil {
logger.Error().Msg("Could not write the yaml file")
return "", err

View File

@@ -0,0 +1,128 @@
# argo_builder.go — Résumé
## Rôle général
`argo_builder.go` traduit un **Workflow Open Cloud** (graphe de nœuds : processings,
stockages, computes, sous-workflows) en un **fichier YAML Argo Workflow** prêt à
être soumis à un cluster Kubernetes.
---
## Structures principales
| Struct | Rôle |
|---|---|
| `ArgoBuilder` | Constructeur principal. Porte le workflow source, la structure YAML en cours de build, les services k8s, le timeout et la liste des peers distants (Admiralty). |
| `Workflow` | Racine du YAML Argo (`apiVersion`, `kind`, `metadata`, `spec`). |
| `Spec` | Spécification du workflow : compte de service, entrypoint, templates, volumes, timeout, référence au dépôt d'artefacts S3. |
| `ArgoKubeEvent` | Événement publié sur NATS lors de la demande de provisionnement d'une ressource distante (compute ou stockage S3). Contient `executions_id`, `dest_peer_id`, `source_peer_id`, `data_type`, `origin_id`. |
---
## Flux d'exécution principal
```
CreateDAG()
└─ createTemplates()
├─ [pour chaque processing] createArgoTemplates()
│ ├─ addTaskToArgo() → ajoute la tâche au DAG + dépendances
│ ├─ CreateContainer() → template container Argo
│ ├─ AddAdmiraltyAnnotations() → si peer distant détecté
│ └─ addStorageAnnotations() → S3 + volumes locaux
├─ [pour chaque native tool WORKFLOW_EVENT] createArgoTemplates()
└─ [pour chaque sous-workflow]
├─ CreateDAG() récursif
└─ fusion DAG + recâblage des dépendances
└─ createVolumes() → PersistentVolumeClaims
CompleteBuild()
├─ waitForConsiders() × N peers → validation Admiralty (COMPUTE_RESOURCE)
├─ mise à jour annotations Admiralty (clustername)
└─ écriture du YAML dans ./argo_workflows/
```
---
## Fonctions clés
### `CreateDAG(exec, namespace, write) → (nbTâches, firstItems, lastItems, err)`
Point d'entrée. Initialise le logger, déclenche la création des templates et des
volumes, configure les métadonnées globales du workflow Argo.
### `createTemplates(exec, namespace) → (firstItems, lastItems, volumes)`
Itère sur tous les nœuds du graphe.
- Processings → template container.
- Native tools `WORKFLOW_EVENT` → template événement.
- Sous-workflows → build récursif + fusion DAG + recâblage des dépendances entrantes/sortantes.
### `createArgoTemplates(exec, namespace, id, obj, …)`
Crée le template Argo pour un nœud donné.
Détecte si le processing est **réparti** (peer distant via `isReparted`) → ajoute les
annotations Admiralty et enregistre le peer dans `RemotePeers`.
Délègue la configuration du stockage à `addStorageAnnotations`.
### `addStorageAnnotations(exec, id, template, namespace, volumes)`
Pour chaque stockage lié au processing :
- **S3** : appelle `waitForConsiders(STORAGE_RESOURCE)` pour chaque compute associé,
puis configure la référence au dépôt d'artefacts via `addS3annotations`.
- **Local** : monte un `VolumeMount` dans le container.
### `waitForConsiders(executionsId, dataType, event)`
**Fonction bloquante.**
1. Publie l'`ArgoKubeEvent` sur le canal NATS `ARGO_KUBE_EVENT`.
2. S'abonne à `PROPALGATION_EVENT`.
3. Attend un `PropalgationMessage` vérifiant :
- `Action == PB_CONSIDERS`
- `DataType == dataType`
- `Payload.executions_id == executionsId`
4. Timeout : **5 minutes**.
| Appelant | DataType attendu | Signification |
|---|---|---|
| `addStorageAnnotations` (S3) | `STORAGE_RESOURCE` | Le stockage S3 distant est prêt |
| `CompleteBuild` (Admiralty) | `COMPUTE_RESOURCE` | Le cluster cible Admiralty est configuré |
### `CompleteBuild(executionsId) → (cheminYAML, err)`
Finalise le build :
1. Pour chaque peer dans `RemotePeers``waitForConsiders(COMPUTE_RESOURCE)` (bloquant, séquentiel).
2. Met à jour les annotations `multicluster.admiralty.io/clustername` avec `target-<peerId>-<executionsId>`.
3. Sérialise le workflow en YAML et l'écrit dans `./argo_workflows/<nom>_<timestamp>.yml`.
### `isReparted(processing, graphID) → (bool, *peer.Peer)`
Retrouve le Compute attaché au processing, charge le Peer propriétaire via l'API
oc-lib, et vérifie si `Relation != 1` (pas le peer local).
### `addTaskToArgo(exec, dag, graphItemID, processing, …)`
Crée une `Task` Argo (nom unique, template, dépendances DAG, paramètres env/inputs/outputs)
et la rattache au DAG. Met à jour `firstItems` / `lastItems`.
### `isArgoDependancy(id) → (bool, []string)`
Vérifie si un nœud est utilisé comme source d'un lien sortant vers un autre
processing ou workflow (il est donc une dépendance pour quelqu'un).
### `getArgoDependencies(id) → []string`
Retourne les noms des tâches Argo dont ce nœud dépend (liens entrants).
---
## Protocole NATS utilisé
```
Publication → canal : ARGO_KUBE_EVENT
payload : NATSResponse{Method: PROPALGATION_EVENT, Payload: ArgoKubeEvent}
Attente ← canal : PROPALGATION_EVENT
filtre : PropalgationMessage{
Action = PB_CONSIDERS,
DataType = COMPUTE_RESOURCE | STORAGE_RESOURCE,
Payload = {"executions_id": "<id en cours>"}
}
```
---
## Fichier YAML produit
- Nom : `oc-monitor-<mot1>-<mot2>_<DD_MM_YYYY_hhmmss>.yml`
- Dossier : `./argo_workflows/`
- Permissions : `0660`