Monitord Acces Change

This commit is contained in:
mr
2026-05-27 16:09:45 +02:00
parent a9284314ef
commit 7c91a8b032
19 changed files with 2496 additions and 332 deletions
+356 -76
View File
@@ -8,6 +8,7 @@ import (
"fmt"
"oc-monitord/conf"
. "oc-monitord/models"
"sort"
"sync"
"os"
@@ -80,23 +81,23 @@ func (b *Workflow) getDag() *Dag {
// PodSecurityContext mirrors the subset of k8s PodSecurityContext used by Argo.
type PodSecurityContext struct {
RunAsUser *int64 `yaml:"runAsUser,omitempty"`
RunAsUser *int64 `yaml:"runAsUser,omitempty"`
RunAsGroup *int64 `yaml:"runAsGroup,omitempty"`
FSGroup *int64 `yaml:"fsGroup,omitempty"`
FSGroup *int64 `yaml:"fsGroup,omitempty"`
}
// 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"`
Volumes []VolumeClaimTemplate `yaml:"volumeClaimTemplates,omitempty"`
ExistingVolumes []ExistingVolume `yaml:"volumes,omitempty"`
Templates []Template `yaml:"templates"`
Timeout int `yaml:"activeDeadlineSeconds,omitempty"`
SecurityContext *PodSecurityContext `yaml:"securityContext,omitempty"`
ArtifactRepositoryRef *ArtifactRepositoryRef `yaml:"artifactRepositoryRef,omitempty"`
ServiceAccountName string `yaml:"serviceAccountName,omitempty"`
Entrypoint string `yaml:"entrypoint"`
Arguments []Parameter `yaml:"arguments,omitempty"`
Volumes []VolumeClaimTemplate `yaml:"volumeClaimTemplates,omitempty"`
ExistingVolumes []ExistingVolume `yaml:"volumes,omitempty"`
Templates []Template `yaml:"templates"`
Timeout int `yaml:"activeDeadlineSeconds,omitempty"`
SecurityContext *PodSecurityContext `yaml:"securityContext,omitempty"`
}
// CreateDAG est le point d'entrée de la construction du DAG Argo.
@@ -151,10 +152,11 @@ func (b *ArgoBuilder) createTemplates(exec *workflow_execution.WorkflowExecution
if d, ok := exec.SelectedInstances[res.GetID()]; ok {
index = d
}
instance := item.Processing.GetSelectedInstance(&index)
logger.Info().Msg(fmt.Sprint("Creating template for", item.Processing.GetName(), instance))
if instance == nil || instance.(*resources.ProcessingInstance).Access == nil && instance.(*resources.ProcessingInstance).Access.Container != nil {
logger.Error().Msg("Not enough configuration setup, template can't be created : " + item.Processing.GetName())
instance := item.ItemResource.Processing.GetSelectedInstance(&index)
logger.Info().Msg(fmt.Sprint("Creating template for", item.ItemResource.Processing.GetName(), instance))
procInst, _ := instance.(*resources.ProcessingInstance)
if instance == nil || procInst == nil || procInst.Access == nil || (procInst.Access.Container == nil && !procInst.Access.HasSource()) {
logger.Error().Msg("Not enough configuration setup, template can't be created : " + item.ItemResource.Processing.GetName())
return firstItems, lastItems, volumes, nil
}
// Un même processing peut être bookié sur plusieurs peers : on crée
@@ -162,16 +164,55 @@ func (b *ArgoBuilder) createTemplates(exec *workflow_execution.WorkflowExecution
for _, pb := range getAllPeersForItem(exec, item.ID) {
var err error
volumes, firstItems, lastItems, err = b.createArgoTemplates(exec,
namespace, item.ID, pb.PeerID, pb.BookingID, item.Processing, volumes, firstItems, lastItems)
namespace, item.ID, pb.PeerID, pb.BookingID, item.ItemResource.Processing, volumes, firstItems, lastItems)
if err != nil {
return firstItems, lastItems, volumes, err
}
}
}
// --- Service Resources ---
// HOSTED : le creator_id identifie le peer propriétaire du compute à contacter ;
// pas de lien avec un compute unit nécessaire.
// DEPLOYMENT : le service doit être déployé sur un compute booké (comme un processing).
for _, item := range b.OriginWorkflow.GetGraphItems(b.OriginWorkflow.Graph.IsService) {
index := 0
_, res := item.GetResource()
if d, ok := exec.SelectedInstances[res.GetID()]; ok {
index = d
}
instance := item.ItemResource.Service.GetSelectedInstance(&index)
logger.Info().Msg(fmt.Sprint("Creating template for service", item.ItemResource.Service.GetName(), instance))
if instance == nil {
logger.Error().Msg("Not enough configuration setup, service template can't be created : " + item.ItemResource.Service.GetName())
continue
}
svcInst := instance.(*resources.ServiceInstance)
if svcInst.Mode == resources.HOSTED {
// HOSTED : le creator_id suffit à identifier le peer cible.
peerID := item.ItemResource.Service.GetCreatorID()
var err error
volumes, firstItems, lastItems, err = b.createArgoTemplates(exec,
namespace, item.ID, peerID, item.ID, item.ItemResource.Service, volumes, firstItems, lastItems)
if err != nil {
return firstItems, lastItems, volumes, err
}
} else {
// DEPLOYMENT : un template par peer booké, comme les processings.
for _, pb := range getAllPeersForItem(exec, item.ID) {
var err error
volumes, firstItems, lastItems, err = b.createArgoTemplates(exec,
namespace, item.ID, pb.PeerID, pb.BookingID, item.ItemResource.Service, volumes, firstItems, lastItems)
if err != nil {
return firstItems, lastItems, volumes, err
}
}
}
}
// --- 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) {
if item.ItemResource.NativeTool.Kind != int(native_tools.WORKFLOW_EVENT) {
continue
}
index := 0
@@ -179,11 +220,14 @@ func (b *ArgoBuilder) createTemplates(exec *workflow_execution.WorkflowExecution
if d, ok := exec.SelectedInstances[res.GetID()]; ok {
index = d
}
instance := item.NativeTool.GetSelectedInstance(&index)
logger.Info().Msg(fmt.Sprint("Creating template for", item.NativeTool.GetName(), instance))
instance := item.ItemResource.NativeTool.GetSelectedInstance(&index)
logger.Info().Msg(fmt.Sprint("Creating template for", item.ItemResource.NativeTool.GetName(), instance))
// Résolution du peer cible : distant si un compute directement connecté
// est distant, local sinon (aucun compute ou compute local).
peerID := b.getNativeToolPeer(item.ID)
var err error
volumes, firstItems, lastItems, err = b.createArgoTemplates(exec,
namespace, item.ID, "", item.ID, item.NativeTool, volumes, firstItems, lastItems)
namespace, item.ID, peerID, item.ID, item.ItemResource.NativeTool, volumes, firstItems, lastItems)
if err != nil {
return firstItems, lastItems, volumes, err
}
@@ -193,7 +237,7 @@ func (b *ArgoBuilder) createTemplates(exec *workflow_execution.WorkflowExecution
firstWfTasks := map[string][]string{}
latestWfTasks := map[string][]string{}
relatedWfTasks := map[string][]string{}
for _, wf := range b.OriginWorkflow.Workflows {
for _, wf := range b.OriginWorkflow.ResourceSet.Workflows {
realWorkflow, code, err := w.NewAccessor(nil).LoadOne(wf)
if code != 200 {
logger.Error().Msg("Error loading the workflow : " + err.Error())
@@ -257,6 +301,12 @@ func (b *ArgoBuilder) createTemplates(exec *workflow_execution.WorkflowExecution
}
}
// --- Sources Data (isReachable = true ET false) ---
// Injecte les steps curl/wrapper pour les Data avec source, APRÈS que toutes les
// steps processing ont été ajoutées au DAG (dépendances câblées).
// Phase 3 (public) et Phase 4 (privé) sont gérées dans HandleDataSources.
b.HandleDataSources(exec, namespace)
// Si des services Kubernetes sont nécessaires, on ajoute le pod dédié.
if b.Services != nil {
dag := b.Workflow.getDag()
@@ -289,17 +339,61 @@ func (b *ArgoBuilder) createArgoTemplates(
template := &Template{Name: getArgoName(obj.GetName(), bookingID)}
logger.Info().Msg(fmt.Sprint("Creating template for", template.Name))
// Résoudre le peer en amont pour que le NativeTool puisse choisir l'URL NATS cible.
isReparted, remotePeer := b.isPeerReparted(peerID)
if obj.GetType() == tools.PROCESSING_RESOURCE.String() {
template.CreateContainer(exec, obj.(*resources.ProcessingResource), b.Workflow.getDag())
proc := obj.(*resources.ProcessingResource)
index := 0
if d, ok := exec.SelectedInstances[proc.GetID()]; ok {
index = d
}
if procInst, ok := proc.GetSelectedInstance(&index).(*resources.ProcessingInstance); ok && procInst.Access.HasSource() {
argoStepName := getArgoName(proc.GetName(), bookingID)
if procInst.Access.Source.IsReachable {
// Phase 3 — source publique : injecter une step curl directe.
if err := b.handleProcessingSource(exec, graphID, proc, procInst, argoStepName, template); err != nil {
logger.Error().Msg("[source-fetch] " + err.Error())
return volumes, firstItems, lastItems, err
}
} else {
// Phase 4 — source privée : NATS + URL pré-signée + Secret K8s.
if err := b.handlePrivateProcessingSource(exec, graphID, proc, procInst, argoStepName, namespace); err != nil {
logger.Error().Msg("[source-private] " + err.Error())
return volumes, firstItems, lastItems, err
}
}
} else {
template.CreateContainer(exec, b.OriginWorkflow, graphID, proc, b.Workflow.getDag())
}
} else if obj.GetType() == tools.NATIVE_TOOL.String() {
template.CreateEventContainer(exec, obj.(*resources.NativeTool), b.Workflow.getDag())
// Pour le cas local, on utilise le FQDN cross-namespace car le pod tourne
// dans le namespace executions_id, pas dans OCNamespace (opencloud).
natsURL := conf.GetConfig().NATSPodURL()
if isReparted && remotePeer != nil && remotePeer.NATSAddress != "" {
natsURL = remotePeer.NATSAddress
}
template.CreateEventContainer(exec, graphID, b.OriginWorkflow, obj.(*resources.NativeTool), b.Workflow.getDag(), natsURL)
} else if obj.GetType() == tools.SERVICE_RESOURCE.String() {
svc := obj.(*resources.ServiceResource)
template.CreateServiceContainer(exec, b.OriginWorkflow, graphID, svc, b.Workflow.getDag())
// Le k8s Service (NodePort/LoadBalancer) et le label "app" ne sont nécessaires
// que pour DEPLOYMENT : le service est déployé et doit être exposé.
// Pour HOSTED, le service tourne déjà chez son créateur, aucune exposition locale.
svcIndex := 0
if d, ok := exec.SelectedInstances[svc.GetID()]; ok {
svcIndex = d
}
if inst, ok := svc.GetSelectedInstance(&svcIndex).(*resources.ServiceInstance); ok && inst.Mode == resources.DEPLOYMENT {
b.CreateService(exec, graphID, obj)
template.Metadata.Labels = make(map[string]string)
template.Metadata.Labels["app"] = "oc-service-" + obj.GetName()
}
}
// Enregistre l'image pour le pre-pull sur le peer cible.
// peerID == "" désigne le peer local (clé "" dans PeerImages).
b.addPeerImage(peerID, template.Container.Image)
// Vérifie si le peer est distant (Admiralty).
isReparted, remotePeer := b.isPeerReparted(peerID)
if isReparted {
logger.Debug().Msg("Reparted processing, on " + remotePeer.GetID())
b.RemotePeers = append(b.RemotePeers, remotePeer.GetID())
@@ -309,14 +403,6 @@ func (b *ArgoBuilder) createArgoTemplates(
b.HasLocalCompute = true
}
// 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, graphID, obj)
template.Metadata.Labels = make(map[string]string)
template.Metadata.Labels["app"] = "oc-service-" + obj.GetName()
}
var err error
volumes, err = b.addStorageAnnotations(exec, graphID, template, namespace, volumes, isReparted)
if err != nil {
@@ -340,19 +426,25 @@ func (b *ArgoBuilder) addStorageAnnotations(exec *workflow_execution.WorkflowExe
related := b.OriginWorkflow.GetByRelatedProcessing(id, b.OriginWorkflow.Graph.IsStorage)
for _, r := range related {
storage := r.Node.(*resources.StorageResource)
for _, linkToStorage := range r.Links {
n := r.Node
storage := n.(*resources.StorageResource)
for _, linkToStorage := range r.Links { //nolint:govet
for _, rw := range linkToStorage.StorageLinkInfos {
var art Artifact
// Le nom de l'artefact doit être alphanumérique + '-' ou '_'.
artifactBaseName := strings.Join(strings.Split(storage.GetName(), " "), "-") + "-" + strings.Replace(rw.FileName, ".", "-", -1)
envs := []Parameter{}
for _, p := range linkToStorage.Env {
envs = append(envs, Parameter{Name: p.Name})
}
if rw.Write {
// Écriture vers S3 : Path = chemin du fichier dans le pod.
art = Artifact{Path: template.ReplacePerEnv(rw.Source, linkToStorage.Env)}
art = Artifact{Path: template.ReplacePerEnv(rw.Source, envs)}
art.Name = artifactBaseName + "-input-write"
} else {
// Lecture depuis S3 : Path = destination dans le pod.
art = Artifact{Path: template.ReplacePerEnv(rw.Destination+"/"+rw.FileName, linkToStorage.Env)}
art = Artifact{Path: template.ReplacePerEnv(rw.Destination+"/"+rw.FileName, envs)}
art.Name = artifactBaseName + "-input-read"
}
@@ -430,6 +522,97 @@ func (b *ArgoBuilder) addStorageAnnotations(exec *workflow_execution.WorkflowExe
}, volumes)
}
}
// Embedded storages: scan links for compute nodes connected to this processing.
// Key in SelectedEmbeddedStorages is the graph item ID (not resource ID), so we
// iterate links directly to preserve the graph position identity.
for _, link := range b.OriginWorkflow.Graph.Links {
var computeGraphID string
if link.Source.ID == id && b.OriginWorkflow.Graph.IsCompute(b.OriginWorkflow.Graph.Items[link.Destination.ID]) {
computeGraphID = link.Destination.ID
} else if link.Destination.ID == id && b.OriginWorkflow.Graph.IsCompute(b.OriginWorkflow.Graph.Items[link.Source.ID]) {
computeGraphID = link.Source.ID
}
if computeGraphID == "" {
continue
}
sel, ok := exec.SelectedEmbeddedStorages[computeGraphID]
if !ok || sel == nil {
continue
}
c := b.OriginWorkflow.Graph.Items[computeGraphID]
_, computeRes := (&c).GetResource()
computeResource := computeRes.(*resources.ComputeResource)
computeIdx := 0
if d, ok := exec.SelectedInstances[computeResource.GetID()]; ok {
computeIdx = d
}
if computeIdx >= len(computeResource.Instances) {
continue
}
computeInst := computeResource.Instances[computeIdx]
if sel.StorageIndex >= len(computeInst.AvailableStorages) {
continue
}
storage := computeInst.AvailableStorages[sel.StorageIndex]
if storage.StorageType == enum.S3 {
relatedProcessing := b.getStorageRelatedProcessing(storage.GetID())
var wg sync.WaitGroup
errCh := make(chan error, len(relatedProcessing))
for _, rp := range relatedProcessing {
wg.Add(1)
go waitForConsiders(exec.ExecutionsID, tools.STORAGE_RESOURCE, ArgoKubeEvent{
ExecutionsID: exec.ExecutionsID,
DestPeerID: rp.GetID(),
Type: tools.STORAGE_RESOURCE,
SourcePeerID: storage.GetCreatorID(),
OriginID: conf.GetConfig().PeerID,
}, &wg, errCh)
}
wg.Wait()
close(errCh)
for err := range errCh {
if err != nil {
return volumes, err
}
}
b.addS3annotations(storage, namespace)
} else {
// Local volume / Minio: provision PVC via oc-datacenter then mount it.
var pvcWg sync.WaitGroup
pvcErrCh := make(chan error, 1)
pvcWg.Add(1)
go waitForConsiders(exec.ExecutionsID, tools.STORAGE_RESOURCE, ArgoKubeEvent{
ExecutionsID: exec.ExecutionsID,
Type: tools.STORAGE_RESOURCE,
SourcePeerID: conf.GetConfig().PeerID,
DestPeerID: conf.GetConfig().PeerID,
OriginID: conf.GetConfig().PeerID,
MinioID: storage.GetID(),
Local: true,
StorageName: storage.GetName(),
}, &pvcWg, pvcErrCh)
pvcWg.Wait()
close(pvcErrCh)
for err := range pvcErrCh {
if err != nil {
return volumes, err
}
}
// Use the first instance's source as mount path if available.
mountPath := ""
if len(storage.Instances) > 0 {
mountPath = storage.Instances[0].Source
}
volumes = template.Container.AddVolumeMount(VolumeMount{
Name: strings.ReplaceAll(strings.ToLower(storage.GetName()), " ", "-"),
MountPath: mountPath,
Storage: storage,
IsReparted: isReparted,
}, volumes)
}
}
return volumes, nil
}
@@ -478,12 +661,26 @@ func (b *ArgoBuilder) getComputeProcessing(processingId string) (res []resources
// 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{
b.Workflow.Spec.ArtifactRepositoryRef = &ArtifactRepositoryRef{
ConfigMap: storage.GetID() + "-artifact-repository",
Key: storage.GetID() + "-s3-local",
}
}
func (b *ArgoBuilder) getRealVar(exec *workflow_execution.WorkflowExecution, val string, processing resources.ResourceInterface) string {
if strings.Contains(val, "[resource]instance.") {
attr := strings.ReplaceAll(val, "[resource]instance.", "")
index := 0
if d, ok := exec.SelectedInstances[processing.GetID()]; ok {
index = d
}
instance := processing.GetSelectedInstance(&index)
ser := instance.Serialize(instance)
return fmt.Sprintf("%v", ser[attr])
}
return val
}
// 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
@@ -494,32 +691,77 @@ func (b *ArgoBuilder) addTaskToArgo(exec *workflow_execution.WorkflowExecution,
unique_name := getArgoName(processing.GetName(), bookingID)
step := Task{Name: unique_name, Template: unique_name}
index := 0
if d, ok := exec.SelectedInstances[processing.GetID()]; ok {
index = d
// Propagation des variables d'environnement, entrées et sorties
// de l'instance vers les paramètres de la tâche Argo.
// AppendParamIfAbsent évite les doublons quand une variable est définie
// à la fois sur le ProcessingResource et sur le Workflow (override).
for _, value := range processing.GetEnv() {
step.Arguments.Parameters = AppendParamIfAbsent(step.Arguments.Parameters, Parameter{
Name: value.Name,
Value: b.getRealVar(exec, value.Value, processing),
})
}
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,
Value: value.Value,
})
for _, value := range b.OriginWorkflow.Env[graphItemID] {
step.Arguments.Parameters = AppendParamIfAbsent(step.Arguments.Parameters, Parameter{
Name: value.Name,
Value: b.getRealVar(exec, value.Value, processing),
})
}
for _, value := range processing.GetInputs() {
step.Arguments.Parameters = AppendParamIfAbsent(step.Arguments.Parameters, Parameter{
Name: value.Name,
Value: b.getRealVar(exec, value.Value, processing),
})
}
for _, value := range b.OriginWorkflow.Inputs[graphItemID] {
step.Arguments.Parameters = AppendParamIfAbsent(step.Arguments.Parameters, Parameter{
Name: value.Name,
Value: b.getRealVar(exec, value.Value, processing),
})
}
for _, value := range processing.GetOutputs() {
step.Arguments.Parameters = AppendParamIfAbsent(step.Arguments.Parameters, Parameter{
Name: value.Name,
Value: b.getRealVar(exec, value.Value, processing),
})
}
for _, value := range b.OriginWorkflow.Outputs[graphItemID] {
step.Arguments.Parameters = AppendParamIfAbsent(step.Arguments.Parameters, Parameter{
Name: value.Name,
Value: b.getRealVar(exec, value.Value, processing),
})
}
// Résolution récursive des références $VAR_NAME entre paramètres.
// Les needles sont triées par longueur décroissante pour éviter que $FOO
// matche à l'intérieur de $FOOBAR (le plus long est substitué en premier).
// On itère jusqu'au point fixe pour gérer les dépendances transitives
// (A=$B, B=$C → après deux passes A=valeur de C).
sortedParams := make([]Parameter, len(step.Arguments.Parameters))
copy(sortedParams, step.Arguments.Parameters)
sort.Slice(sortedParams, func(i, j int) bool {
return len(sortedParams[i].Name) > len(sortedParams[j].Name)
})
for {
changed := false
for i := range step.Arguments.Parameters {
for _, needle_param := range sortedParams {
if step.Arguments.Parameters[i].Name == needle_param.Name {
continue
}
needle := "$" + needle_param.Name
if strings.Contains(step.Arguments.Parameters[i].Value, needle) {
step.Arguments.Parameters[i].Value = strings.ReplaceAll(
step.Arguments.Parameters[i].Value,
needle,
needle_param.Value,
)
changed = true
}
}
}
for _, value := range instance.(*resources.ProcessingInstance).Inputs {
step.Arguments.Parameters = append(step.Arguments.Parameters, Parameter{
Name: value.Name,
Value: value.Value,
})
}
for _, value := range instance.(*resources.ProcessingInstance).Outputs {
step.Arguments.Parameters = append(step.Arguments.Parameters, Parameter{
Name: value.Name,
Value: value.Value,
})
if !changed {
break
}
}
@@ -527,11 +769,14 @@ func (b *ArgoBuilder) addTaskToArgo(exec *workflow_execution.WorkflowExecution,
// 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()
if b.OriginWorkflow.Graph.Items[graphItemID].ItemResource.Processing != nil {
name = b.OriginWorkflow.Graph.Items[graphItemID].ItemResource.Processing.GetName()
}
if b.OriginWorkflow.Graph.Items[graphItemID].Workflow != nil {
name = b.OriginWorkflow.Graph.Items[graphItemID].Workflow.GetName()
if b.OriginWorkflow.Graph.Items[graphItemID].ItemResource.Workflow != nil {
name = b.OriginWorkflow.Graph.Items[graphItemID].ItemResource.Workflow.GetName()
}
if b.OriginWorkflow.Graph.Items[graphItemID].ItemResource.Service != nil {
name = b.OriginWorkflow.Graph.Items[graphItemID].ItemResource.Service.GetName()
}
if len(step.Dependencies) == 0 && name != "" {
firstItems = append(firstItems, getArgoName(name, bookingID))
@@ -557,9 +802,10 @@ func (b *ArgoBuilder) createVolumes(exec *workflow_execution.WorkflowExecution,
}
seen[name] = struct{}{}
claimName := name + "-" + exec.ExecutionsID
ev := ExistingVolume{}
ev.Name = name
ev.PersistentVolumeClaim.ClaimName = claimName
ev := ExistingVolume{
Name: name,
PersistentVolumeClaim: &PVCRef{ClaimName: claimName},
}
b.Workflow.Spec.ExistingVolumes = append(b.Workflow.Spec.ExistingVolumes, ev)
}
// hostPath PVs are created as root:root 0755. Ensure pods can read/write
@@ -586,20 +832,27 @@ func (b *ArgoBuilder) isArgoDependancy(exec *workflow_execution.WorkflowExecutio
logger.Info().Msg(fmt.Sprint("Could not find the source of the link", link.Destination.ID))
continue
}
source := b.OriginWorkflow.Graph.Items[link.Destination.ID].Processing
source := b.OriginWorkflow.Graph.Items[link.Destination.ID].ItemResource.Processing
if id == link.Source.ID && source != nil {
isDeps = true
for _, pb := range getAllPeersForItem(exec, link.Destination.ID) {
dependancyOfIDs = append(dependancyOfIDs, getArgoName(source.GetName(), pb.BookingID))
}
}
wourceWF := b.OriginWorkflow.Graph.Items[link.Destination.ID].Workflow
wourceWF := b.OriginWorkflow.Graph.Items[link.Destination.ID].ItemResource.Workflow
if id == link.Source.ID && wourceWF != nil {
isDeps = true
for _, pb := range getAllPeersForItem(exec, link.Destination.ID) {
dependancyOfIDs = append(dependancyOfIDs, getArgoName(wourceWF.GetName(), pb.BookingID))
}
}
sourceSvc := b.OriginWorkflow.Graph.Items[link.Destination.ID].ItemResource.Service
if id == link.Source.ID && sourceSvc != nil {
isDeps = true
for _, pb := range getAllPeersForItem(exec, link.Destination.ID) {
dependancyOfIDs = append(dependancyOfIDs, getArgoName(sourceSvc.GetName(), pb.BookingID))
}
}
}
return isDeps, dependancyOfIDs
}
@@ -614,12 +867,18 @@ func (b *ArgoBuilder) getArgoDependencies(exec *workflow_execution.WorkflowExecu
logger.Info().Msg(fmt.Sprint("Could not find the source of the link", link.Source.ID))
continue
}
source := b.OriginWorkflow.Graph.Items[link.Source.ID].Processing
source := b.OriginWorkflow.Graph.Items[link.Source.ID].ItemResource.Processing
if id == link.Destination.ID && source != nil {
for _, pb := range getAllPeersForItem(exec, link.Source.ID) {
dependencies = append(dependencies, getArgoName(source.GetName(), pb.BookingID))
}
}
sourceSvc := b.OriginWorkflow.Graph.Items[link.Source.ID].ItemResource.Service
if id == link.Destination.ID && sourceSvc != nil {
for _, pb := range getAllPeersForItem(exec, link.Source.ID) {
dependencies = append(dependencies, getArgoName(sourceSvc.GetName(), pb.BookingID))
}
}
}
return
}
@@ -657,6 +916,24 @@ func getAllPeersForItem(exec *workflow_execution.WorkflowExecution, graphItemID
return result
}
// getNativeToolPeer résout le peer cible d'un NativeTool WORKFLOW_EVENT.
// Règle : si un compute est directement connecté au NativeTool dans le graphe
// et que ce compute appartient à un peer distant, on retourne ce peerID.
// Dans tous les autres cas (aucun compute connecté, ou compute local), on retourne "".
func (b *ArgoBuilder) getNativeToolPeer(graphItemID string) string {
computeRel := b.OriginWorkflow.GetByRelatedProcessing(graphItemID, b.OriginWorkflow.Graph.IsCompute)
for _, rel := range computeRel {
peerID := rel.Node.GetCreatorID()
if peerID == "" {
continue
}
if isReparted, _ := b.isPeerReparted(peerID); isReparted {
return peerID
}
}
return ""
}
// isPeerReparted vérifie si le peerID désigne un peer distant (Relation != 1).
// Un peerID vide signifie exécution locale : retourne false sans appel réseau.
func (b *ArgoBuilder) isPeerReparted(peerID string) (bool, *peer.Peer) {
@@ -725,7 +1002,7 @@ func waitForConsiders(executionsId string, dataType tools.DataType, event ArgoKu
}
// ArgoKubeEvent est la structure publiée sur NATS lors de la demande de
// provisionnement d'une ressource distante (Admiralty ou stockage S3).
// provisionnement d'une ressource distante (Admiralty, stockage S3, ou source privée).
// 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 {
@@ -733,7 +1010,8 @@ type ArgoKubeEvent struct {
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 indique la nature de la ressource : COMPUTE_RESOURCE, STORAGE_RESOURCE
// ou PROCESSING_RESOURCE (source privée Phase 4).
Type tools.DataType `json:"data_type"`
// SourcePeerID est le peer source de la ressource demandée.
SourcePeerID string `json:"source_peer_id"`
@@ -747,8 +1025,11 @@ type ArgoKubeEvent struct {
// StorageName est le nom normalisé du storage, utilisé pour calculer le claimName.
StorageName string `json:"storage_name,omitempty"`
// Images est la liste des images de conteneurs à pre-pull sur le peer cible
// avant le démarrage du workflow. Vide pour les events STORAGE_RESOURCE.
// avant le démarrage du workflow. Vide pour les events STORAGE_RESOURCE / PROCESSING_RESOURCE.
Images []string `json:"images,omitempty"`
// SourceResourceID est l'ID de la ressource Processing/Data dont on demande
// une URL pré-signée (Phase 4, isReachable=false uniquement).
SourceResourceID string `json:"source_resource_id,omitempty"`
}
// addPeerImage enregistre une image à pre-pull pour un peer donné.
@@ -768,7 +1049,6 @@ func (b *ArgoBuilder) addPeerImage(peerID, image string) {
b.PeerImages[peerID] = append(b.PeerImages[peerID], image)
}
// 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
+9 -15
View File
@@ -30,24 +30,18 @@ func (b *ArgoBuilder) CreateService(exec *workflow_execution.WorkflowExecution,
}
func (b *ArgoBuilder) completeServicePorts(exec *workflow_execution.WorkflowExecution, service *models.Service, id string, processing resources.ResourceInterface) {
index := 0
if d, ok := exec.SelectedInstances[processing.GetID()]; ok {
index = d
}
instance := processing.GetSelectedInstance(&index)
if instance != nil && instance.(*resources.ProcessingInstance).Access != nil && instance.(*resources.ProcessingInstance).Access.Container != nil {
for _, execute := range instance.(*resources.ProcessingInstance).Access.Container.Exposes {
if execute.PAT != 0 {
new_port_translation := models.ServicePort{
Name: strings.ToLower(processing.GetName()) + id,
Port: execute.Port,
TargetPort: execute.PAT,
Protocol: "TCP",
}
service.Spec.Ports = append(service.Spec.Ports, new_port_translation)
for _, execute := range b.OriginWorkflow.Exposes[processing.GetID()] {
if execute.PAT != 0 {
new_port_translation := models.ServicePort{
Name: strings.ToLower(processing.GetName()) + id,
Port: execute.Port,
TargetPort: execute.PAT,
Protocol: "TCP",
}
service.Spec.Ports = append(service.Spec.Ports, new_port_translation)
}
}
}
func (b *ArgoBuilder) addServiceToArgo() error {
+89 -5
View File
@@ -10,6 +10,8 @@ import (
"cloud.o-forge.io/core/oc-lib/tools"
)
// ── considersCache (signal-only) ─────────────────────────────────────────────
// considersCache stocke les canaux en attente d'un PB_CONSIDERS,
// indexés par "executionsId:dataType". Un même message NATS réveille
// tous les waiters enregistrés sous la même clé (broadcast).
@@ -75,9 +77,78 @@ func (c *considersCache) confirm(key string) {
}
}
// ── sourcePresignedCache (value-bearing) ─────────────────────────────────────
// sourcePresignedCache stocke les canaux en attente d'une URL pré-signée pour
// une source privée (isReachable=false), indexés par la clé sourceConsidersKey.
// La valeur transportée est l'URL pré-signée elle-même.
type sourcePresignedCache struct {
mu sync.Mutex
pending map[string][]chan string
}
var globalSourceCache = &sourcePresignedCache{
pending: make(map[string][]chan string),
}
// sourceConsidersKey construit une clé unique pour une demande de source privée.
// La clé encode l'executionsID, le peerID du propriétaire et le resourceID
// pour permettre des requêtes parallèles distinctes.
func sourceConsidersKey(executionsID, peerID, resourceID string) string {
return executionsID + ":src:" + peerID + ":" + resourceID
}
// register inscrit un nouveau canal d'attente pour la clé donnée.
// Retourne le canal à lire et une fonction de désinscription à appeler en defer.
func (c *sourcePresignedCache) register(key string) (<-chan string, func()) {
ch := make(chan string, 1)
c.mu.Lock()
c.pending[key] = append(c.pending[key], ch)
c.mu.Unlock()
unregister := func() {
c.mu.Lock()
defer c.mu.Unlock()
list := c.pending[key]
for i, existing := range list {
if existing == ch {
c.pending[key] = append(list[:i], list[i+1:]...)
break
}
}
if len(c.pending[key]) == 0 {
delete(c.pending, key)
}
}
return ch, unregister
}
// confirm réveille tous les waiters enregistrés sous la clé donnée
// en leur transmettant l'URL pré-signée, puis les supprime du cache.
func (c *sourcePresignedCache) confirm(key, url string) {
c.mu.Lock()
list := c.pending[key]
delete(c.pending, key)
c.mu.Unlock()
for _, ch := range list {
select {
case ch <- url:
default:
}
}
}
// ── StartConsidersListener ────────────────────────────────────────────────────
// StartConsidersListener démarre un abonné NATS global via ListenNats (oclib)
// qui reçoit les messages CONSIDERS_EVENT et réveille les goroutines en attente
// via globalConsidersCache. Doit être appelé une seule fois au démarrage.
// qui reçoit les messages CONSIDERS_EVENT et réveille les goroutines en attente.
//
// Deux chemins de dispatch :
// - Si presigned_url est présent dans le payload → globalSourceCache (Phase 4).
// - Sinon → globalConsidersCache (Phases COMPUTE / STORAGE, signal sans valeur).
//
// Doit être appelé une seule fois au démarrage.
func StartConsidersListener() {
log := logs.GetLogger()
log.Info().Msg("Considers NATS listener starting on " + tools.CONSIDERS_EVENT.GenerateKey())
@@ -87,14 +158,27 @@ func StartConsidersListener() {
var body struct {
ExecutionsID string `json:"executions_id"`
PeerID string `json:"peer_id,omitempty"`
// PresignedURL est non-vide uniquement pour les réponses de source privée (Phase 4).
PresignedURL string `json:"presigned_url,omitempty"`
// ResourceID identifie la ressource Processing/Data pour la Phase 4.
ResourceID string `json:"resource_id,omitempty"`
}
if err := json.Unmarshal(resp.Payload, &body); err != nil {
log.Error().Msg("CONSIDERS_EVENT: cannot unmarshal payload: " + err.Error())
return
}
key := considersKey(body.ExecutionsID, resp.Datatype, body.PeerID)
log.Info().Msg(fmt.Sprintf("CONSIDERS_EVENT dispatched for key=%s", key))
globalConsidersCache.confirm(key)
if body.PresignedURL != "" {
// Phase 4 — source privée : transmettre l'URL pré-signée.
key := sourceConsidersKey(body.ExecutionsID, body.PeerID, body.ResourceID)
log.Info().Msg(fmt.Sprintf("CONSIDERS_EVENT (presigned) dispatched for key=%s", key))
globalSourceCache.confirm(key, body.PresignedURL)
} else {
// Phases COMPUTE / STORAGE — simple signal.
key := considersKey(body.ExecutionsID, resp.Datatype, body.PeerID)
log.Info().Msg(fmt.Sprintf("CONSIDERS_EVENT dispatched for key=%s", key))
globalConsidersCache.confirm(key)
}
},
})
}
+354
View File
@@ -0,0 +1,354 @@
package workflow_builder
// source_fetch.go — Phase 3 : gestion des sources tierces (isReachable = true)
//
// Pour chaque ressource (Processing ou Data) dont l'instance expose une source
// publique (access.Container == nil, access.Source != "", access.IsReachable),
// le builder injecte une step Argo de téléchargement (curl) AVANT la step qui
// consomme la ressource.
//
// Garde critique : si la step aval (processing) contient déjà un curl ciblant
// la même URL dans sa commande de container, on n'injecte PAS de step
// supplémentaire — ce serait un double téléchargement.
import (
"fmt"
"net/url"
"path"
"strings"
. "oc-monitord/models"
"cloud.o-forge.io/core/oc-lib/models/resources"
"cloud.o-forge.io/core/oc-lib/models/workflow_execution"
)
// curlImage est l'image utilisée pour la step de téléchargement.
// alpine dispose de wget ; on installe curl à la volée, ou on utilise
// directement wget. Utiliser curlimages/curl évite l'installation.
const curlImage = "curlimages/curl:latest"
// ── Garde ────────────────────────────────────────────────────────────────────
// sourceAlreadyFetchedByStep retourne true si le container du processing
// identifié par processingItemID contient déjà un appel curl/wget ciblant
// sourceURL dans sa commande ou ses arguments.
//
// Si c'est le cas on NE doit PAS injecter une step curl supplémentaire :
// le processing gère lui-même le téléchargement et injecter une step
// amont serait un double téléchargement.
func (b *ArgoBuilder) sourceAlreadyFetchedByStep(
exec *workflow_execution.WorkflowExecution,
processingItemID string,
sourceURL string,
) bool {
item, ok := b.OriginWorkflow.Graph.Items[processingItemID]
if !ok || item.ItemResource.Processing == nil {
return false
}
index := 0
if d, ok := exec.SelectedInstances[item.ItemResource.Processing.GetID()]; ok {
index = d
}
inst := item.ItemResource.Processing.GetSelectedInstance(&index)
if inst == nil {
return false
}
procInst, ok := inst.(*resources.ProcessingInstance)
if !ok || procInst.Access == nil || procInst.Access.Container == nil {
// Pas de container → le step sera lui-même construit depuis la source,
// pas de double téléchargement possible.
return false
}
fullCmd := procInst.Access.Container.Command + " " + procInst.Access.Container.Args
hasFetch := strings.Contains(fullCmd, "curl") || strings.Contains(fullCmd, "wget")
hasURL := strings.Contains(fullCmd, sourceURL)
return hasFetch && hasURL
}
// ── Injection de la step curl ─────────────────────────────────────────────────
func (b *ArgoBuilder) injectSourceFetchStep(
stepBaseName string,
sourceURL string,
destPath string,
isExecutable bool,
dependsOn []string,
) string {
curlStepName := stepBaseName + "-src-fetch"
filename := sourceFilename(sourceURL)
fullDest := destPath + "/" + filename
var script string
if isExecutable {
script = fmt.Sprintf(
"curl -fsSL '%s' -o '%s' && chmod +x '%s'",
sourceURL, fullDest, fullDest,
)
} else {
script = fmt.Sprintf("curl -fsSL '%s' -o '%s'", sourceURL, fullDest)
}
// Tâche dans le DAG.
fetchTask := Task{
Name: curlStepName,
Template: curlStepName,
Dependencies: dependsOn,
}
b.Workflow.getDag().Tasks = append(b.Workflow.getDag().Tasks, fetchTask)
// Template Argo correspondant.
fetchTemplate := Template{
Name: curlStepName,
Container: Container{
Image: curlImage,
ImagePullPolicy: "IfNotPresent",
Command: []string{"sh", "-c"},
Args: []string{script},
},
}
b.Workflow.Spec.Templates = append(b.Workflow.Spec.Templates, fetchTemplate)
logger.Info().Msg(fmt.Sprintf(
"[source-fetch] injected curl step '%s' → %s → %s",
curlStepName, sourceURL, fullDest,
))
return curlStepName
}
// ── Traitement Processing source (isReachable = true) ────────────────────────
// handleProcessingSource gère le cas où un ProcessingInstance a une source
// publique (access.HasSource() && access.IsReachable) sans container associé.
//
// Elle injecte une step curl avant la step processing dans le DAG, puis
// modifie le template du processing pour exécuter le binaire téléchargé
// depuis le storage lié.
//
// Retourne une erreur si aucun storage n'est lié (prérequis obligatoire).
func (b *ArgoBuilder) handleProcessingSource(
exec *workflow_execution.WorkflowExecution,
graphID string,
procResource *resources.ProcessingResource,
procInst *resources.ProcessingInstance,
argoStepName string,
template *Template,
) error {
access := procInst.Access
if !access.HasSource() || !access.Source.IsReachable {
return nil
}
// Récupérer le storage lié à ce processing.
related := b.OriginWorkflow.GetByRelatedProcessing(graphID, b.OriginWorkflow.Graph.IsStorage)
if len(related) == 0 {
return fmt.Errorf(
"processing '%s' has source '%s' but no storage linked — cannot inject fetch step",
procResource.GetName(), access.Source,
)
}
// On utilise le premier storage lié (cas nominal).
var mountPath string
for _, r := range related {
n := r.Node
storage := n.(*resources.StorageResource)
if len(storage.Instances) > 0 && storage.Instances[0].Source != "" {
mountPath = storage.Instances[0].Source
break
}
}
if mountPath == "" {
return fmt.Errorf(
"processing '%s': linked storage has no mount path configured",
procResource.GetName(),
)
}
// Dépendances courantes de la step processing (pour les câbler sur la step curl).
existingDeps := b.getArgoDependencies(exec, graphID)
// Injection de la step curl.
fetchStepName := b.injectSourceFetchStep(
argoStepName,
access.Source.Source,
mountPath,
true, // binaire exécutable
existingDeps,
)
// La step processing dépend maintenant de la step curl.
// On met à jour la tâche DAG existante.
dag := b.Workflow.getDag()
for i, task := range dag.Tasks {
if task.Name == argoStepName {
dag.Tasks[i].Dependencies = []string{fetchStepName}
break
}
}
// Le template processing doit exécuter le binaire téléchargé.
filename := sourceFilename(access.Source.Source)
binaryPath := mountPath + "/" + filename
template.Container = Container{
Image: "alpine:latest",
ImagePullPolicy: "IfNotPresent",
Command: []string{"sh", "-c"},
Args: []string{binaryPath},
}
// Propagation des paramètres d'entrée/sortie du workflow.
for _, v := range procResource.GetEnv() {
template.Inputs.Parameters = AppendParamIfAbsent(template.Inputs.Parameters, Parameter{Name: v.Name})
}
for _, v := range b.OriginWorkflow.Env[graphID] {
template.Inputs.Parameters = AppendParamIfAbsent(template.Inputs.Parameters, Parameter{Name: v.Name})
}
return nil
}
// ── Traitement Data source (isReachable = true) ───────────────────────────────
// HandleDataSources parcourt tous les items Data du graphe dont une instance
// expose une source publique (access.HasSource() && access.IsReachable) et
// injecte pour chacun une step curl de téléchargement dans le storage lié.
//
// Les sources privées (isReachable=false) sont gérées par HandlePrivateDataSources
// (Phase 4), appelée en fin de cette fonction.
//
// Garde : si la step processing aval contient déjà un curl ciblant la même URL,
// on saute l'injection pour ce processing.
//
// Cette fonction est appelée depuis createTemplates() après la boucle principale.
func (b *ArgoBuilder) HandleDataSources(exec *workflow_execution.WorkflowExecution, namespace string) {
for itemID, item := range b.OriginWorkflow.Graph.Items {
if !b.OriginWorkflow.Graph.IsData(item) || item.ItemResource.Data == nil {
continue
}
// Chercher une instance avec source PUBLIQUE (isReachable=true).
// Les sources privées sont traitées par HandlePrivateDataSources.
var sourceURL string
var mountPath string
for _, inst := range item.ItemResource.Data.Instances {
if inst == nil || !inst.Access.HasSource() || !inst.Access.Source.IsReachable {
continue
}
sourceURL = inst.Access.Source.Source
break
}
if sourceURL == "" {
continue
}
// Storage lié à cette Data (ValidateIntegrity garantit qu'il en existe un).
linkedStorageIDs := b.OriginWorkflow.Graph.GetLinkedStorageForData(itemID)
if len(linkedStorageIDs) == 0 {
logger.Error().Msg(fmt.Sprintf(
"[source-fetch] data '%s' has source but no storage linked — skipping",
item.ItemResource.Data.GetName(),
))
continue
}
storageItemID := linkedStorageIDs[0]
storageItem, ok := b.OriginWorkflow.Graph.Items[storageItemID]
if !ok || storageItem.ItemResource.Storage == nil || len(storageItem.ItemResource.Storage.Instances) == 0 {
continue
}
mountPath = storageItem.ItemResource.Storage.Instances[0].Source
if mountPath == "" {
logger.Error().Msg(fmt.Sprintf(
"[source-fetch] storage linked to data '%s' has no mount path — skipping",
item.ItemResource.Data.GetName(),
))
continue
}
// Trouver tous les processings qui lisent depuis ce storage.
downstreamProcIDs := b.processingsThatReadStorage(storageItemID)
// Pour chaque processing aval, appliquer la garde puis injecter si nécessaire.
for _, procItemID := range downstreamProcIDs {
if b.sourceAlreadyFetchedByStep(exec, procItemID, sourceURL) {
logger.Info().Msg(fmt.Sprintf(
"[source-fetch] data '%s': downstream processing '%s' already curls source — skipping injection",
item.ItemResource.Data.GetName(), procItemID,
))
continue
}
procItem := b.OriginWorkflow.Graph.Items[procItemID]
if procItem.ItemResource.Processing == nil {
continue
}
// Dépendances courantes de la step processing aval.
existingDeps := b.getArgoDependencies(exec, procItemID)
// Nom de la step curl : basé sur le nom de la Data + storage.
fetchBaseName := strings.ToLower(strings.ReplaceAll(item.ItemResource.Data.GetName(), " ", "-")) +
"-" + strings.ToLower(strings.ReplaceAll(storageItem.ItemResource.Storage.GetName(), " ", "-"))
fetchStepName := b.injectSourceFetchStep(
fetchBaseName,
sourceURL,
mountPath,
false, // donnée, pas un binaire
existingDeps,
)
// Ajouter la step curl comme dépendance de CHAQUE instance (peer) du processing aval.
dag := b.Workflow.getDag()
for _, pb := range getAllPeersForItem(exec, procItemID) {
procArgoName := getArgoName(procItem.ItemResource.Processing.GetName(), pb.BookingID)
for i, task := range dag.Tasks {
if task.Name == procArgoName {
// Remplacer les dépendances existantes par [fetchStepName].
// Les anciennes dépendances sont déjà portées par la step curl.
dag.Tasks[i].Dependencies = []string{fetchStepName}
break
}
}
}
}
}
// Phase 4 — sources privées (isReachable=false).
b.HandlePrivateDataSources(exec, namespace)
}
// ── Helpers ───────────────────────────────────────────────────────────────────
// sourceFilename extrait le nom de fichier depuis une URL source.
// Fallback : "source-binary" si l'URL n'a pas de chemin exploitable.
func sourceFilename(sourceURL string) string {
u, err := url.Parse(sourceURL)
if err == nil && u.Path != "" {
if base := path.Base(u.Path); base != "." && base != "/" {
return base
}
}
return "source-binary"
}
// processingsThatReadStorage retourne les IDs des items Processing
// connectés (via un lien quelconque) au storage identifié par storageItemID.
func (b *ArgoBuilder) processingsThatReadStorage(storageItemID string) []string {
var result []string
for _, link := range b.OriginWorkflow.Graph.Links {
var otherID string
if link.Source.ID == storageItemID {
otherID = link.Destination.ID
} else if link.Destination.ID == storageItemID {
otherID = link.Source.ID
} else {
continue
}
if other, ok := b.OriginWorkflow.Graph.Items[otherID]; ok && b.OriginWorkflow.Graph.IsProcessing(other) {
result = append(result, otherID)
}
}
return result
}
+459
View File
@@ -0,0 +1,459 @@
package workflow_builder
// source_private.go — Phase 4 : sources privées (isReachable = false)
//
// Pour les ressources (Processing ou Data) dont la source n'est pas
// directement accessible (access.IsReachable == false), le protocole est :
//
// 1. oc-monitord publie un ARGO_KUBE_EVENT(PROCESSING_RESOURCE) sur NATS
// avec les informations de couplage (vérification AE côté peer distant).
//
// 2. Le peer propriétaire valide l'AE, génère une URL pré-signée Minio
// éphémère et répond via CONSIDERS_EVENT avec presigned_url + resource_id.
//
// 3. oc-monitord crée un Secret Kubernetes éphémère contenant l'URL,
// labelisé oc-execution-id pour nettoyage post-exécution.
//
// 4. La step Argo injecte un wrapper sh qui :
// • Processing binary : lit l'URL → /dev/shm/.exec → chmod+x → fork → rm → wait
// • Data : lit l'URL → destPath/filename (pas de chmod/rm/exec)
import (
"encoding/json"
"fmt"
"strings"
"sync"
"time"
"oc-monitord/conf"
. "oc-monitord/models"
"oc-monitord/tools"
oclib "cloud.o-forge.io/core/oc-lib"
"cloud.o-forge.io/core/oc-lib/models/resources"
"cloud.o-forge.io/core/oc-lib/models/workflow_execution"
octools "cloud.o-forge.io/core/oc-lib/tools"
)
// ── Demande NATS d'URL pré-signée ────────────────────────────────────────────
// waitForPresignedURL publie un ARGO_KUBE_EVENT(PROCESSING_RESOURCE) sur NATS
// pour demander une URL pré-signée au peer propriétaire de la source privée,
// puis attend la réponse via globalSourceCache.
//
// Résultats envoyés dans urlCh / errCh ; wg.Done() est toujours appelé.
func waitForPresignedURL(
executionsID string,
event ArgoKubeEvent,
wg *sync.WaitGroup,
urlCh chan<- string,
errCh chan<- error,
) {
defer wg.Done()
b, err := json.Marshal(event)
if err != nil {
logger.Error().Msg("[source-private] cannot marshal ArgoKubeEvent: " + err.Error())
urlCh <- ""
errCh <- err
return
}
octools.NewNATSCaller().SetNATSPub(octools.ARGO_KUBE_EVENT, octools.NATSResponse{
FromApp: "oc-monitord",
Datatype: octools.PROCESSING_RESOURCE,
User: "root",
Method: int(octools.ARGO_KUBE_EVENT),
Payload: b,
})
key := sourceConsidersKey(executionsID, event.SourcePeerID, event.SourceResourceID)
ch, unregister := globalSourceCache.register(key)
defer unregister()
select {
case url := <-ch:
logger.Info().Msg(fmt.Sprintf(
"[source-private] presigned URL received resource=%s exec=%s",
event.SourceResourceID, executionsID,
))
urlCh <- url
errCh <- nil
case <-time.After(5 * time.Minute):
ferr := fmt.Errorf(
"timeout waiting for presigned URL resource=%s exec=%s",
event.SourceResourceID, executionsID,
)
logger.Error().Msg(ferr.Error())
urlCh <- ""
errCh <- ferr
}
}
// ── Nommage du Secret ─────────────────────────────────────────────────────────
// secretNameFor génère un nom de Secret K8s valide (63 chars max, alphanum+-)
// à partir d'un nom de step et d'un execution ID.
func secretNameFor(stepBaseName, executionID string) string {
base := strings.ToLower(strings.ReplaceAll(stepBaseName, "_", "-"))
if len(base) > 30 {
base = base[:30]
}
suffix := executionID
if len(suffix) > 8 {
suffix = suffix[:8]
}
name := "oc-src-" + base + "-" + suffix
// Éliminer les caractères non autorisés par K8s (alphanum + '-').
var clean strings.Builder
for _, c := range name {
if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' {
clean.WriteRune(c)
}
}
s := strings.Trim(clean.String(), "-")
if len(s) > 63 {
s = s[:63]
}
return s
}
// ── Injection step Processing (source privée) ─────────────────────────────────
// injectPrivateProcessingStep ajoute dans le DAG et dans les templates Argo une
// step wrapper pour un Processing à source privée.
//
// Le script sh :
// 1. Lit l'URL pré-signée depuis le Secret monté à /var/oc-secrets/presigned-url
// 2. Télécharge le binaire dans /dev/shm/.exec (RAM — jamais sur disque)
// 3. Le rend exécutable, le lance en background, supprime le fichier, attend la fin
//
// Le Secret est déclaré dans spec.volumes (ExistingVolume) et monté en lecture
// seule dans le container.
//
// Retourne le nom Argo de la step créée.
func (b *ArgoBuilder) injectPrivateProcessingStep(
stepBaseName string,
secretName string,
dependsOn []string,
) string {
stepName := stepBaseName + "-prv-fetch"
volName := strings.ReplaceAll(secretName, ".", "-")
script := `PRESIGNED=$(cat /var/oc-secrets/presigned-url)
curl -fsSL "$PRESIGNED" -o /dev/shm/.exec
chmod +x /dev/shm/.exec
/dev/shm/.exec &
PID=$!
rm -f /dev/shm/.exec
wait $PID`
// Volume Secret dans le spec du workflow (partagé entre toutes les steps).
b.addSecretVolumeIfAbsent(volName, secretName)
fetchTask := Task{
Name: stepName,
Template: stepName,
Dependencies: dependsOn,
}
b.Workflow.getDag().Tasks = append(b.Workflow.getDag().Tasks, fetchTask)
fetchTemplate := Template{
Name: stepName,
Container: Container{
Image: curlImage,
ImagePullPolicy: "IfNotPresent",
Command: []string{"sh", "-c"},
Args: []string{script},
VolumeMounts: []VolumeMount{
{Name: volName, MountPath: "/var/oc-secrets", ReadOnly: true},
},
},
}
b.Workflow.Spec.Templates = append(b.Workflow.Spec.Templates, fetchTemplate)
logger.Info().Msg(fmt.Sprintf(
"[source-private] injected private processing step '%s' (secret=%s)",
stepName, secretName,
))
return stepName
}
// ── Injection step Data (source privée) ──────────────────────────────────────
// injectPrivateDataStep ajoute dans le DAG une step de téléchargement sécurisé
// pour une Data à source privée vers le storage lié (pas de /dev/shm, pas de rm).
func (b *ArgoBuilder) injectPrivateDataStep(
stepBaseName string,
secretName string,
destPath string,
filename string,
dependsOn []string,
) string {
stepName := stepBaseName + "-prv-fetch"
volName := strings.ReplaceAll(secretName, ".", "-")
fullDest := destPath + "/" + filename
script := fmt.Sprintf(
"PRESIGNED=$(cat /var/oc-secrets/presigned-url)\ncurl -fsSL \"$PRESIGNED\" -o '%s'",
fullDest,
)
b.addSecretVolumeIfAbsent(volName, secretName)
fetchTask := Task{
Name: stepName,
Template: stepName,
Dependencies: dependsOn,
}
b.Workflow.getDag().Tasks = append(b.Workflow.getDag().Tasks, fetchTask)
fetchTemplate := Template{
Name: stepName,
Container: Container{
Image: curlImage,
ImagePullPolicy: "IfNotPresent",
Command: []string{"sh", "-c"},
Args: []string{script},
VolumeMounts: []VolumeMount{
{Name: volName, MountPath: "/var/oc-secrets", ReadOnly: true},
},
},
}
b.Workflow.Spec.Templates = append(b.Workflow.Spec.Templates, fetchTemplate)
logger.Info().Msg(fmt.Sprintf(
"[source-private] injected private data step '%s' → %s (secret=%s)",
stepName, fullDest, secretName,
))
return stepName
}
// addSecretVolumeIfAbsent déclare un volume de type Secret dans spec.volumes
// uniquement s'il n'est pas déjà présent (déduplication par nom).
func (b *ArgoBuilder) addSecretVolumeIfAbsent(volName, secretName string) {
for _, v := range b.Workflow.Spec.ExistingVolumes {
if v.Name == volName {
return
}
}
b.Workflow.Spec.ExistingVolumes = append(b.Workflow.Spec.ExistingVolumes, ExistingVolume{
Name: volName,
Secret: &SecretRef{SecretName: secretName},
})
}
// ── handlePrivateProcessingSource ────────────────────────────────────────────
// handlePrivateProcessingSource gère le cas où un ProcessingInstance a une source
// privée (access.HasSource() && !access.IsReachable).
//
// Orchestration :
// 1. Demande de l'URL pré-signée via NATS (waitForPresignedURL)
// 2. Création du Secret K8s éphémère
// 3. Injection de la step wrapper dans le DAG
// 4. Recâblage des dépendances (processing dépend du step wrapper)
func (b *ArgoBuilder) handlePrivateProcessingSource(
exec *workflow_execution.WorkflowExecution,
graphID string,
procResource *resources.ProcessingResource,
procInst *resources.ProcessingInstance,
argoStepName string,
namespace string,
) error {
access := procInst.Access
if !access.HasSource() || access.Source.IsReachable {
return nil
}
self, err := oclib.GetMySelf()
if err != nil {
return fmt.Errorf("[source-private] cannot get local peer ID: %w", err)
}
// Demande de l'URL pré-signée au peer propriétaire.
var wg sync.WaitGroup
urlCh := make(chan string, 1)
errCh := make(chan error, 1)
wg.Add(1)
go waitForPresignedURL(exec.ExecutionsID, ArgoKubeEvent{
ExecutionsID: exec.ExecutionsID,
Type: octools.PROCESSING_RESOURCE,
SourcePeerID: procResource.GetCreatorID(),
DestPeerID: self.GetID(),
OriginID: conf.GetConfig().PeerID,
SourceResourceID: procResource.GetID(),
}, &wg, urlCh, errCh)
wg.Wait()
close(urlCh)
close(errCh)
presignedURL := <-urlCh
if ferr := <-errCh; ferr != nil || presignedURL == "" {
if ferr == nil {
ferr = fmt.Errorf("empty presigned URL for processing '%s'", procResource.GetName())
}
return ferr
}
// Création du Secret K8s contenant l'URL.
secretName := secretNameFor(argoStepName, exec.ExecutionsID)
kube, kerr := tools.NewKubernetesTool()
if kerr != nil {
return fmt.Errorf("[source-private] cannot create K8s client: %w", kerr)
}
if kerr = kube.CreateSourceSecret(secretName, presignedURL, exec.ExecutionsID, namespace); kerr != nil {
return fmt.Errorf("[source-private] CreateSourceSecret: %w", kerr)
}
// Dépendances actuelles de la step processing (seront portées par le step wrapper).
existingDeps := b.getArgoDependencies(exec, graphID)
// Injection de la step wrapper.
fetchStepName := b.injectPrivateProcessingStep(argoStepName, secretName, existingDeps)
// Recâblage : la step processing ne dépend plus que du step wrapper.
dag := b.Workflow.getDag()
for i, task := range dag.Tasks {
if task.Name == argoStepName {
dag.Tasks[i].Dependencies = []string{fetchStepName}
break
}
}
logger.Info().Msg(fmt.Sprintf(
"[source-private] processing '%s' wired: %v → %s → %s",
procResource.GetName(), existingDeps, fetchStepName, argoStepName,
))
return nil
}
// ── HandlePrivateDataSources ─────────────────────────────────────────────────
// HandlePrivateDataSources parcourt tous les items Data dont une instance a
// une source privée (access.HasSource() && !access.IsReachable) et injecte
// pour chacun une step de téléchargement sécurisé dans le storage lié.
//
// Appelé depuis HandleDataSources() en fin de createTemplates().
func (b *ArgoBuilder) HandlePrivateDataSources(
exec *workflow_execution.WorkflowExecution,
namespace string,
) {
self, err := oclib.GetMySelf()
if err != nil {
logger.Error().Msg("[source-private] cannot get local peer ID: " + err.Error())
return
}
for itemID, item := range b.OriginWorkflow.Graph.Items {
if !b.OriginWorkflow.Graph.IsData(item) || item.ItemResource.Data == nil {
continue
}
var sourceURL string
var resourceID string
var creatorID string
for _, inst := range item.ItemResource.Data.Instances {
if inst == nil || !inst.Access.HasSource() || inst.Access.Source.IsReachable {
continue
}
sourceURL = inst.Access.Source.Source
resourceID = item.ItemResource.Data.GetID()
creatorID = item.ItemResource.Data.GetCreatorID()
break
}
if sourceURL == "" {
continue
}
// Storage lié à cette Data.
linkedStorageIDs := b.OriginWorkflow.Graph.GetLinkedStorageForData(itemID)
if len(linkedStorageIDs) == 0 {
logger.Error().Msg(fmt.Sprintf(
"[source-private] data '%s' has private source but no storage linked — skipping",
item.ItemResource.Data.GetName(),
))
continue
}
storageItem, ok := b.OriginWorkflow.Graph.Items[linkedStorageIDs[0]]
if !ok || storageItem.ItemResource.Storage == nil || len(storageItem.ItemResource.Storage.Instances) == 0 {
continue
}
mountPath := storageItem.ItemResource.Storage.Instances[0].Source
if mountPath == "" {
logger.Error().Msg(fmt.Sprintf(
"[source-private] storage linked to data '%s' has no mount path — skipping",
item.ItemResource.Data.GetName(),
))
continue
}
// Demande de l'URL pré-signée.
var wg sync.WaitGroup
urlCh := make(chan string, 1)
errCh := make(chan error, 1)
wg.Add(1)
go waitForPresignedURL(exec.ExecutionsID, ArgoKubeEvent{
ExecutionsID: exec.ExecutionsID,
Type: octools.PROCESSING_RESOURCE,
SourcePeerID: creatorID,
DestPeerID: self.GetID(),
OriginID: conf.GetConfig().PeerID,
SourceResourceID: resourceID,
}, &wg, urlCh, errCh)
wg.Wait()
close(urlCh)
close(errCh)
presignedURL := <-urlCh
if ferr := <-errCh; ferr != nil || presignedURL == "" {
logger.Error().Msg(fmt.Sprintf(
"[source-private] data '%s': failed to get presigned URL: %v",
item.ItemResource.Data.GetName(), ferr,
))
continue
}
// Création du Secret K8s.
fetchBaseName := strings.ToLower(strings.ReplaceAll(item.ItemResource.Data.GetName(), " ", "-"))
secretName := secretNameFor(fetchBaseName, exec.ExecutionsID)
kube, kerr := tools.NewKubernetesTool()
if kerr != nil {
logger.Error().Msg("[source-private] cannot create K8s client: " + kerr.Error())
continue
}
if kerr = kube.CreateSourceSecret(secretName, presignedURL, exec.ExecutionsID, namespace); kerr != nil {
logger.Error().Msg("[source-private] cannot create source secret: " + kerr.Error())
continue
}
// Injection pour chaque processing aval lisant ce storage.
downstreamProcIDs := b.processingsThatReadStorage(linkedStorageIDs[0])
filename := sourceFilename(sourceURL)
for _, procItemID := range downstreamProcIDs {
procItem := b.OriginWorkflow.Graph.Items[procItemID]
if procItem.ItemResource.Processing == nil {
continue
}
existingDeps := b.getArgoDependencies(exec, procItemID)
fetchStepName := b.injectPrivateDataStep(
fetchBaseName, secretName, mountPath, filename, existingDeps,
)
// Recâblage des steps processing aval.
dag := b.Workflow.getDag()
for _, pb := range getAllPeersForItem(exec, procItemID) {
procArgoName := getArgoName(procItem.ItemResource.Processing.GetName(), pb.BookingID)
for i, task := range dag.Tasks {
if task.Name == procArgoName {
dag.Tasks[i].Dependencies = []string{fetchStepName}
break
}
}
}
}
}
}