executor

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 8, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultExecutorConfig = &ExecutorConfig{
	Namespace:           "ares-system",
	DefaultTimeout:      1 * time.Hour,
	DefaultMemoryMB:     1024,
	DefaultCPUMillis:    500,
	HealthCheckInterval: 5 * time.Second,
	MaxConcurrentJobs:   100,

	ImageRegistry:            "",
	DefaultJobImage:          "nvidia/cuda:13.0.2-runtime-ubuntu22.04",
	RestartPolicy:            "OnFailure",
	ImagePullPolicy:          "IfNotPresent",
	EnableGPUSupport:         true,
	LogCollectionEnabled:     true,
	MetricsCollectionEnabled: true,
}

Default config

Functions

This section is empty.

Types

type ExecutionContext

type ExecutionContext struct {
	JobID         string
	LeaseID       int64      // Carried from K8Decision for fencing validation
	LocalDecision K8Decision // From Layer 6 (Local Scheduler)
	PodName       string
	Namespace     string
	StartTime     time.Time
	Timeout       time.Duration
	Status        JobStatus
	LastUpdated   time.Time
	CurrentPhase  PodPhase
	NodeID        string                 // From LocalSchedulingDecision
	GPUIndices    []int                  // From LocalSchedulingDecision
	Logs          string                 // Job logs (if collected)
	Metrics       map[string]interface{} // Pod metrics
}

ExecutionContext: Runtime context for a job being executed

type ExecutionResult

type ExecutionResult struct {
	JobID        string
	PodName      string
	Status       JobStatus
	Phase        PodPhase
	StartTime    time.Time
	EndTime      time.Time
	Duration     time.Duration
	ExitCode     int
	ErrorMessage string
	Logs         string
	Metrics      map[string]interface{}
	CompletedAt  time.Time
}

ExecutionResult: Final result of job execution

type Executor

type Executor struct {
	ClusterID    string
	ControlPlane string
	Log          *logger.Logger
	Config       *ExecutorConfig

	JobStore     job.JobStore
	LeaseManager *lease.LeaseManager

	// Job tracking
	JobsMu        sync.RWMutex
	ActiveJobs    map[string]*ExecutionContext // JobID -> ExecutionContext
	CompletedJobs map[string]*ExecutionResult  // JobID -> ExecutionResult

	// Metrics (atomic for thread-safety)
	TotalJobs       uint64
	TotalSuccessful uint64
	TotalFailed     uint64
	TotalCancelled  uint64
	TotalDuration   int64 // nanoseconds, atomic

	// Pod management
	PodMu       sync.RWMutex
	PodRegistry map[string]*PodInfo // PodName -> PodInfo

	K8sClient K8sClient

	OnJobRunning func(jobID string)
	// Callback when job completes (for resource release)
	OnJobComplete func(jobID string, nodeID string, gpuCount int, memoryMB int)
}

Scope: Single cluster (runs on each cluster's control plane)

func NewExecutor

func NewExecutor(
	clusterID string,
	k8sClient K8sClient,
	config *ExecutorConfig,
	jobStore job.JobStore,
	leaseManager *lease.LeaseManager,
) (*Executor, error)

NewExecutor: Create new executor ✅ FIXED SIGNATURE:

  • k8sClient: common.K8sClient (INTERFACE, not pointer to interface)
  • No log parameter (create own inside)
  • 3 parameters total (matches cmd/local/main.go call)

func (*Executor) CancelJob

func (ex *Executor) CancelJob(jobID string, gracePeriodSeconds int64) error

CancelJob: Cancel a running job. gracePeriodSeconds gives the pod time to catch SIGTERM and checkpoint before being killed; pass a negative value to fall back to the pod's default termination grace.

func (*Executor) Cleanup

func (ex *Executor) Cleanup(olderThan time.Duration) error

Cleanup: Clean up old completed jobs

func (*Executor) ExecuteJob

func (ex *Executor) ExecuteJob(
	ctx context.Context,
	decision *K8Decision,
) (*ExecutionContext, error)

ExecuteJob: Execute job by creating Kubernetes Pod Input: LocalSchedulingDecision (from LocalScheduler - Layer 6) Output: ExecutionContext (tracking info)

func (*Executor) GetExecutorHealth

func (ex *Executor) GetExecutorHealth() map[string]interface{}

GetExecutorHealth: Get executor health status

func (*Executor) GetJobResult

func (ex *Executor) GetJobResult(jobID string) (*ExecutionResult, error)

GetJobResult: Get completed job result

func (*Executor) GetJobStatus

func (ex *Executor) GetJobStatus(jobID string) (*ExecutionContext, error)

GetJobStatus: Get current job status

func (*Executor) GetStats

func (ex *Executor) GetStats() map[string]interface{}

GetStats: Get executor statistics

func (*Executor) ListActiveJobs

func (ex *Executor) ListActiveJobs() []*ExecutionContext

ListActiveJobs: List all active jobs

func (*Executor) ListCompletedJobs

func (ex *Executor) ListCompletedJobs() []*ExecutionResult

ListCompletedJobs: List all completed jobs

type ExecutorConfig

type ExecutorConfig struct {
	ClusterID                string        // e.g., "cluster-us-west-2a"
	Namespace                string        // e.g., "default" or "ares-jobs"
	DefaultTimeout           time.Duration // Pod timeout (default: 1 hour)
	DefaultMemoryMB          int           // Pod default memory
	DefaultCPUMillis         int           // Pod default CPU (millicores)
	HealthCheckInterval      time.Duration // Pod health check frequency
	MaxConcurrentJobs        int           // Max concurrent Pods
	ImageRegistry            string        // e.g., "docker.io", "ghcr.io"
	DefaultJobImage          string        // e.g., "ares-job:latest"
	RestartPolicy            string        // Always, OnFailure, Never
	ImagePullPolicy          string        // Always, IfNotPresent, Never
	EnableGPUSupport         bool          // Enable GPU requests
	LogCollectionEnabled     bool          // Collect Pod logs
	MetricsCollectionEnabled bool          // Collect Pod metrics
}

ExecutorConfig: Configuration for executor

type JobStatus

type JobStatus string

JobStatus: High-level job status

const (
	StatusPending    JobStatus = "Pending"
	StatusRunning    JobStatus = "Running"
	StatusSuccessful JobStatus = "Successful"
	StatusFailed     JobStatus = "Failed"
	StatusCancelled  JobStatus = "Canceled"
	StatusUnknown    JobStatus = "Unknown"
)

type K8Decision

type K8Decision struct {
	JobID             string
	NodeID            string
	GPUIndices        []int
	NodeScore         float64
	GPUAffinityScore  float64
	PlacementReasons  []string
	ScheduledAt       time.Time
	Command           []string
	Args              []string
	Image             string
	LeaseID           int64  // Fencing: Prevents split-brain at pod level
	FencingToken      string // Fencing: Human-readable fencing token for validation
	CheckpointEnabled bool
	CheckpointPath    string // Where to write checkpoints
	CheckpointRestore string // Last checkpoint to restore from (empty = fresh)
	CheckpointMeta    string // Metadata from last checkpoint

	// Gang scheduling: rank/world-size for distributed frameworks (torchrun,
	// Horovod, DeepSpeed). The gang manager already knows each member's index
	// and the gang size; these surface that into the pod env so the training
	// entrypoint can self-configure. Zero-valued for non-gang jobs.
	// NOTE: MASTER_ADDR for rendezvous is intentionally NOT here yet — it needs
	// a per-gang headless Service so rank-0's pod resolves via stable DNS.
	GangID        string // Gang identifier (empty = not a gang member)
	GangSize      int    // Total members in the gang (world size)
	GangMemberIdx int    // 0-based rank of this member within the gang
}

type K8sClient

type K8sClient interface {
	CreatePod(ctx context.Context, pod *PodSpec) (podName string, err error)
	GetPod(ctx context.Context, podName string) (*PodInfo, error)
	DeletePod(ctx context.Context, podName string, gracePeriodSeconds int64) error
	ListPods(ctx context.Context) ([]*PodInfo, error)
	GetPodLogs(ctx context.Context, podName string) (string, error)
	GetPodMetrics(ctx context.Context, podName string) (map[string]interface{}, error)
	WatchPod(ctx context.Context, podName string, callback func(*PodInfo)) error
}

K8sClient: Interface for Kubernetes operations (mock in this file)

type MockK8sClient

type MockK8sClient struct {
	// contains filtered or unexported fields
}

MockK8sClient: Mock Kubernetes client for development

func NewMockK8sClient

func NewMockK8sClient() *MockK8sClient

NewMockK8sClient: Create mock client

func (*MockK8sClient) CreatePod

func (m *MockK8sClient) CreatePod(ctx context.Context, pod *PodSpec) (string, error)

CreatePod: Mock Pod creation

func (*MockK8sClient) DeletePod

func (m *MockK8sClient) DeletePod(ctx context.Context, podName string, gracePeriodSeconds int64) error

DeletePod: Mock delete Pod

func (*MockK8sClient) GetPod

func (m *MockK8sClient) GetPod(ctx context.Context, podName string) (*PodInfo, error)

GetPod: Mock get Pod

func (*MockK8sClient) GetPodLogs

func (m *MockK8sClient) GetPodLogs(ctx context.Context, podName string) (string, error)

GetPodLogs: Mock get Pod logs

func (*MockK8sClient) GetPodMetrics

func (m *MockK8sClient) GetPodMetrics(ctx context.Context, podName string) (map[string]interface{}, error)

GetPodMetrics: Mock get Pod metrics

func (*MockK8sClient) ListPods

func (m *MockK8sClient) ListPods(ctx context.Context) ([]*PodInfo, error)

ListPods: Mock list Pods

func (*MockK8sClient) SetPodLogs

func (m *MockK8sClient) SetPodLogs(podName string, logs string)

SetPodLogs: Helper to set Pod logs (for testing)

func (*MockK8sClient) SetPodMetrics

func (m *MockK8sClient) SetPodMetrics(podName string, metrics map[string]interface{})

SetPodMetrics: Helper to set Pod metrics (for testing)

func (*MockK8sClient) WatchPod

func (m *MockK8sClient) WatchPod(ctx context.Context, podName string, callback func(*PodInfo)) error

WatchPod: Mock watch Pod

type PodInfo

type PodInfo struct {
	PodName       string
	Namespace     string
	JobID         string
	NodeID        string
	Phase         PodPhase
	CreatedAt     time.Time
	StartedAt     time.Time
	FinishedAt    time.Time
	ContainerID   string
	GPUIndices    []int
	ResourceUsage map[string]interface{}
	Ready         bool
}

PodInfo: Information about created Kubernetes Pod

type PodPhase

type PodPhase string

PodPhase: Kubernetes Pod phase

const (
	PhasePending   PodPhase = "Pending"
	PhaseRunning   PodPhase = "Running"
	PhaseSucceeded PodPhase = "Succeeded"
	PhaseFailed    PodPhase = "Failed"
	PhaseUnknown   PodPhase = "Unknown"
)

type PodSpec

type PodSpec struct {
	PodName         string
	Namespace       string
	Image           string
	Command         []string
	Args            []string
	ImagePullPolicy string
	EnvVars         map[string]string
	MemoryMB        int
	CPUMillis       int
	GPUCount        int
	GPUIndices      []int
	Timeout         time.Duration
	RestartPolicy   string
	NodeID          string
	Labels          map[string]string
}

PodSpec: Specification for Kubernetes Pod

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL