同步完整源码 - 2026-05-25
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,237 @@
|
||||
# AgentOps Deployment Infrastructure
|
||||
|
||||
Multi-tenant Kubernetes deployment system for CrewAI agents with ALB ingress routing.
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
- **Kubernetes Cluster**: EKS cluster running agent deployments
|
||||
- **Application Load Balancer**: Shared ALB with host-based routing for multi-tenant isolation
|
||||
- **Instance Files**: ConfigMap-based deployment with content hashing
|
||||
- **Container Registry**: ECR for storing built agent images
|
||||
- **Build System**: Kaniko-based image building with S3 cache in dedicated builder namespace
|
||||
|
||||
## Load Balancer Setup
|
||||
|
||||
The deployment system uses AWS Application Load Balancer (ALB) with the AWS Load Balancer Controller for internet-facing traffic routing.
|
||||
|
||||
### Architecture
|
||||
|
||||
```
|
||||
Internet → ALB (host-based routing) → Kubernetes Services → Pods
|
||||
```
|
||||
|
||||
- Each project gets its own hostname: `{project-uuid}.deploy.agentops.ai`
|
||||
- **Shared ALB**: All deployments use a single ALB instance (`alb-deployments` group) providing one IP address for wildcard DNS routing
|
||||
- ALB routes traffic based on hostname to the correct service using host-based routing
|
||||
- Services use `ClusterIP` type (not LoadBalancer) for cost efficiency
|
||||
- ALB Ingress Controller manages ALB lifecycle automatically
|
||||
- Deployments are tagged with `deployment` and `hostname` labels for routing
|
||||
|
||||
### Prerequisites
|
||||
|
||||
1. **EKS Cluster** with appropriate IAM permissions
|
||||
2. **AWS CLI** configured with ELB permissions
|
||||
3. **Domain** configured for wildcard DNS (*.deploy.agentops.ai)
|
||||
4. **Subnets** tagged with `kubernetes.io/role/elb=1` for ALB creation
|
||||
5. **AWS credentials** available via `aws-credentials` secret in `kube-system` namespace
|
||||
6. **Builder namespace** configured for image building operations
|
||||
|
||||
### Step 1: Install AWS Load Balancer Controller
|
||||
|
||||
Install the AWS Load Balancer Controller to manage ALBs:
|
||||
|
||||
```bash
|
||||
# Install cert-manager (required dependency)
|
||||
kubectl apply -f https://github.com/jetstack/cert-manager/releases/download/v1.5.4/cert-manager.yaml
|
||||
|
||||
# Wait for cert-manager to be ready
|
||||
kubectl wait --for=condition=ready pod -l app=cert-manager -n cert-manager --timeout=60s
|
||||
|
||||
# Install required CRDs for ALB controller
|
||||
kubectl apply -f https://raw.githubusercontent.com/kubernetes-sigs/aws-load-balancer-controller/v2.7.2/config/crd/bases/elbv2.k8s.aws_targetgroupbindings.yaml
|
||||
kubectl apply -f https://raw.githubusercontent.com/kubernetes-sigs/aws-load-balancer-controller/v2.7.2/config/crd/bases/elbv2.k8s.aws_ingressclassparams.yaml
|
||||
|
||||
# Copy AWS credentials to kube-system namespace
|
||||
kubectl get secret aws-credentials -n default -o yaml | sed 's/namespace: default/namespace: kube-system/' | kubectl apply -f -
|
||||
|
||||
# Apply the ALB controller and webhook configurations
|
||||
kubectl apply -f configs/aws-load-balancer-controller.yaml
|
||||
kubectl apply -f configs/aws-load-balancer-webhook.yaml
|
||||
|
||||
# Tag public subnets for ALB creation (replace with your subnet IDs)
|
||||
aws ec2 create-tags --resources subnet-07bb9663fa1d8f572 subnet-0b0bc494208f4d020 --tags Key=kubernetes.io/role/elb,Value=1
|
||||
```
|
||||
|
||||
### Step 2: Configure Services
|
||||
|
||||
Services should use `ClusterIP` type to work with ALB ingress:
|
||||
|
||||
```yaml
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: svc-{project-uuid}
|
||||
spec:
|
||||
type: ClusterIP # Important: NOT LoadBalancer
|
||||
ports:
|
||||
- port: 80
|
||||
targetPort: 8080
|
||||
selector:
|
||||
app: {project-uuid}
|
||||
```
|
||||
|
||||
### Step 3: Ingress Configuration
|
||||
|
||||
The deployment system automatically creates ingress resources with proper ALB annotations:
|
||||
|
||||
```yaml
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: ing-{project-uuid}
|
||||
annotations:
|
||||
kubernetes.io/ingress.class: alb
|
||||
alb.ingress.kubernetes.io/scheme: internet-facing
|
||||
alb.ingress.kubernetes.io/target-type: ip
|
||||
alb.ingress.kubernetes.io/listen-ports: '[{"HTTP": 80}, {"HTTPS": 443}]'
|
||||
alb.ingress.kubernetes.io/ssl-redirect: "443"
|
||||
alb.ingress.kubernetes.io/group.name: group-ing-{project-uuid} # Ensures separate ALB per project
|
||||
spec:
|
||||
rules:
|
||||
- host: {project-uuid}.deploy.agentops.ai
|
||||
http:
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
backend:
|
||||
service:
|
||||
name: svc-{project-uuid}
|
||||
port:
|
||||
number: 80
|
||||
```
|
||||
|
||||
### Key Features
|
||||
|
||||
- **Project Isolation**: Each project gets its own ALB group for complete isolation
|
||||
- **Host-based Routing**: Traffic routed by hostname to correct service
|
||||
- **SSL Termination**: ALB handles HTTPS with automatic redirects
|
||||
- **Health Checks**: ALB performs HTTP health checks on `/health` endpoint
|
||||
- **Cost Effective**: One ALB per project vs individual Classic ELBs
|
||||
|
||||
## Instance Files Management
|
||||
|
||||
Instance files (server.py, providers/) are managed via Kubernetes ConfigMaps with content hashing.
|
||||
|
||||
### How It Works
|
||||
|
||||
1. **Content Hashing**: Files are hashed to create unique ConfigMap names
|
||||
2. **Tar Archive**: All instance files packaged into base64-encoded tar.gz
|
||||
3. **ConfigMap**: Tar archive stored in ConfigMap with hash-based name
|
||||
4. **Build Process**: ConfigMap mounted to builder and extracted into image
|
||||
5. **Immutable Deployments**: Hash changes force new ConfigMap creation
|
||||
|
||||
### Benefits
|
||||
|
||||
- **No Stale Files**: Hash-based naming prevents stale file reuse
|
||||
- **Fast Updates**: Only changed files create new ConfigMaps
|
||||
- **Version Control**: Each deployment gets exactly the files it was built with
|
||||
- **No External Dependencies**: No EFS or external storage required
|
||||
|
||||
## Deployment Process
|
||||
|
||||
The deployment system automatically handles ALB creation:
|
||||
|
||||
1. **Service Creation**: Creates ClusterIP service for each deployment
|
||||
2. **Ingress Creation**: Creates ingress with unique group name for ALB isolation
|
||||
3. **ALB Provisioning**: AWS Load Balancer Controller creates dedicated ALB
|
||||
4. **DNS Configuration**: Update DNS to point hostname to ALB IP addresses
|
||||
|
||||
### Verifying ALB Creation
|
||||
|
||||
```bash
|
||||
# Check ALB controller status
|
||||
kubectl get pods -n kube-system -l app.kubernetes.io/name=aws-load-balancer-controller
|
||||
|
||||
# Check ingress status (should show ALB address when ready)
|
||||
kubectl get ingress
|
||||
|
||||
# Check ingress events for troubleshooting
|
||||
kubectl describe ingress ing-{project-uuid}
|
||||
|
||||
# List ALBs via AWS CLI
|
||||
aws elbv2 describe-load-balancers --query 'LoadBalancers[*].[LoadBalancerName,DNSName,State.Code]' --output table
|
||||
|
||||
# Get ALB IP addresses for /etc/hosts
|
||||
nslookup {alb-dns-name}
|
||||
```
|
||||
|
||||
### Troubleshooting
|
||||
|
||||
Common issues and solutions:
|
||||
|
||||
- **Subnet discovery failed**: Ensure public subnets are tagged with `kubernetes.io/role/elb=1`
|
||||
- **No credentials**: Verify `aws-credentials` secret exists in `kube-system` namespace
|
||||
- **Certificate errors**: Use HTTP-only ingress or configure SSL certificates
|
||||
- **Permission errors**: Check ALB controller logs and ensure all CRDs are installed
|
||||
|
||||
## Environment Configuration
|
||||
|
||||
### Builder Namespace
|
||||
|
||||
The deployment system uses a dedicated namespace for image building operations to simplify management and logging.
|
||||
|
||||
**Environment Variable**: `BUILDER_NAMESPACE` (default: `builder`)
|
||||
|
||||
All Kaniko builder jobs run in this namespace, which allows for:
|
||||
- Centralized builder pod management
|
||||
- Simplified logging with `jockey logs-builder`
|
||||
- Cleaner separation between build and deployment concerns
|
||||
- Easy builder resource monitoring
|
||||
|
||||
### Setup Builder Namespace
|
||||
|
||||
Use the built-in command to create the builder namespace and AWS credentials:
|
||||
|
||||
```bash
|
||||
# Create builder namespace and AWS credentials secret
|
||||
jockey setup-builder
|
||||
|
||||
# View builder logs (automatically uses builder namespace)
|
||||
jockey logs-builder
|
||||
|
||||
# Or specify a different namespace
|
||||
jockey logs-builder --namespace custom-builder
|
||||
```
|
||||
|
||||
The builder namespace requires the `aws-credentials` secret to authenticate with ECR for image pushing.
|
||||
|
||||
## Shared ALB Management
|
||||
|
||||
The deployment system uses a shared ALB (`alb-deployments` group) for all deployments to enable wildcard DNS routing with a single IP address. This allows `*.deploy.agentops.ai` to point to one ALB that handles all subdomain routing. All deployments automatically use the shared ALB configuration.
|
||||
|
||||
### ALB Configuration
|
||||
|
||||
- **Group Name**: `alb-deployments` (configurable via `ALB_SHARED_GROUP_NAME` environment variable)
|
||||
- **Host-based Routing**: Each deployment gets its own hostname for traffic routing
|
||||
- **Tagging**: Each ingress is tagged with `deployment` and `hostname` for identification
|
||||
- **Health Checks**: Configured to use `/health` endpoint with fast deregistration (30s)
|
||||
|
||||
### Management Commands
|
||||
|
||||
```bash
|
||||
# Check the status of the shared ALB
|
||||
jockey alb-status
|
||||
|
||||
# List all ingresses using the shared ALB
|
||||
jockey list-alb-ingresses --namespace default
|
||||
|
||||
# Validate ALB routing for a specific hostname
|
||||
jockey validate-alb-routing yourdomain.deploy.agentops.ai
|
||||
```
|
||||
|
||||
### Environment Variables
|
||||
|
||||
- `ALB_SHARED_GROUP_NAME`: Name of the shared ALB group (default: `alb-deployments`)
|
||||
- `DEPLOYMENT_DOMAIN`: Base domain for deployments (default: `deploy.agentops.ai`)
|
||||
|
||||
The shared ALB is automatically provisioned when the first ingress is created and will handle all subsequent deployments through host-based routing. This provides a single IP address that can be used for wildcard DNS records (`*.deploy.agentops.ai`), simplifying DNS management and enabling seamless subdomain routing.
|
||||
@@ -0,0 +1,268 @@
|
||||
apiVersion: v1
|
||||
kind: ServiceAccount
|
||||
metadata:
|
||||
labels:
|
||||
app.kubernetes.io/component: controller
|
||||
app.kubernetes.io/name: aws-load-balancer-controller
|
||||
name: aws-load-balancer-controller
|
||||
namespace: kube-system
|
||||
---
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: ClusterRole
|
||||
metadata:
|
||||
creationTimestamp: null
|
||||
name: aws-load-balancer-controller
|
||||
rules:
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- endpoints
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- watch
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- events
|
||||
verbs:
|
||||
- create
|
||||
- patch
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- namespaces
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- watch
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- nodes
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- watch
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- pods
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- watch
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- pods/status
|
||||
verbs:
|
||||
- patch
|
||||
- update
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- secrets
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- watch
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- configmaps
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- watch
|
||||
- create
|
||||
- update
|
||||
- patch
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- services
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- patch
|
||||
- update
|
||||
- watch
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- services/status
|
||||
verbs:
|
||||
- patch
|
||||
- update
|
||||
- apiGroups:
|
||||
- extensions
|
||||
resources:
|
||||
- ingresses
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- patch
|
||||
- update
|
||||
- watch
|
||||
- apiGroups:
|
||||
- extensions
|
||||
resources:
|
||||
- ingresses/status
|
||||
verbs:
|
||||
- patch
|
||||
- update
|
||||
- apiGroups:
|
||||
- networking.k8s.io
|
||||
resources:
|
||||
- ingresses
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- patch
|
||||
- update
|
||||
- watch
|
||||
- apiGroups:
|
||||
- networking.k8s.io
|
||||
resources:
|
||||
- ingresses/status
|
||||
verbs:
|
||||
- patch
|
||||
- update
|
||||
- apiGroups:
|
||||
- networking.k8s.io
|
||||
resources:
|
||||
- ingressclasses
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- watch
|
||||
- apiGroups:
|
||||
- elbv2.k8s.aws
|
||||
resources:
|
||||
- targetgroupbindings
|
||||
verbs:
|
||||
- create
|
||||
- delete
|
||||
- get
|
||||
- list
|
||||
- patch
|
||||
- update
|
||||
- watch
|
||||
- apiGroups:
|
||||
- elbv2.k8s.aws
|
||||
resources:
|
||||
- targetgroupbindings/status
|
||||
verbs:
|
||||
- patch
|
||||
- update
|
||||
- apiGroups:
|
||||
- elbv2.k8s.aws
|
||||
resources:
|
||||
- ingressclassparams
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- watch
|
||||
- apiGroups:
|
||||
- coordination.k8s.io
|
||||
resources:
|
||||
- leases
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- watch
|
||||
- create
|
||||
- update
|
||||
- patch
|
||||
---
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: ClusterRoleBinding
|
||||
metadata:
|
||||
name: aws-load-balancer-controller
|
||||
roleRef:
|
||||
apiGroup: rbac.authorization.k8s.io
|
||||
kind: ClusterRole
|
||||
name: aws-load-balancer-controller
|
||||
subjects:
|
||||
- kind: ServiceAccount
|
||||
name: aws-load-balancer-controller
|
||||
namespace: kube-system
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
labels:
|
||||
app.kubernetes.io/component: controller
|
||||
app.kubernetes.io/name: aws-load-balancer-controller
|
||||
name: aws-load-balancer-controller
|
||||
namespace: kube-system
|
||||
spec:
|
||||
replicas: 2
|
||||
selector:
|
||||
matchLabels:
|
||||
app.kubernetes.io/component: controller
|
||||
app.kubernetes.io/name: aws-load-balancer-controller
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app.kubernetes.io/component: controller
|
||||
app.kubernetes.io/name: aws-load-balancer-controller
|
||||
spec:
|
||||
containers:
|
||||
- args:
|
||||
- --cluster-name=agentops-eks
|
||||
- --ingress-class=alb
|
||||
- --aws-vpc-id=vpc-087da2eb9031c2c29
|
||||
image: public.ecr.aws/eks/aws-load-balancer-controller:v2.7.2
|
||||
name: controller
|
||||
env:
|
||||
- name: AWS_DEFAULT_REGION
|
||||
value: us-west-1
|
||||
- name: AWS_ACCESS_KEY_ID
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: aws-credentials
|
||||
key: access-key
|
||||
- name: AWS_SECRET_ACCESS_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: aws-credentials
|
||||
key: secret-key
|
||||
securityContext:
|
||||
allowPrivilegeEscalation: false
|
||||
readOnlyRootFilesystem: true
|
||||
runAsNonRoot: true
|
||||
livenessProbe:
|
||||
failureThreshold: 2
|
||||
httpGet:
|
||||
path: /healthz
|
||||
port: 61779
|
||||
scheme: HTTP
|
||||
initialDelaySeconds: 30
|
||||
timeoutSeconds: 10
|
||||
ports:
|
||||
- containerPort: 9443
|
||||
name: webhook-server
|
||||
protocol: TCP
|
||||
- containerPort: 61779
|
||||
name: metrics-server
|
||||
protocol: TCP
|
||||
resources:
|
||||
limits:
|
||||
cpu: 200m
|
||||
memory: 500Mi
|
||||
requests:
|
||||
cpu: 100m
|
||||
memory: 200Mi
|
||||
volumeMounts:
|
||||
- mountPath: /tmp/k8s-webhook-server/serving-certs
|
||||
name: cert
|
||||
readOnly: true
|
||||
serviceAccountName: aws-load-balancer-controller
|
||||
terminationGracePeriodSeconds: 10
|
||||
volumes:
|
||||
- name: cert
|
||||
secret:
|
||||
defaultMode: 420
|
||||
secretName: aws-load-balancer-webhook-tls
|
||||
@@ -0,0 +1,35 @@
|
||||
apiVersion: cert-manager.io/v1
|
||||
kind: Certificate
|
||||
metadata:
|
||||
name: aws-load-balancer-webhook-tls
|
||||
namespace: kube-system
|
||||
spec:
|
||||
dnsNames:
|
||||
- aws-load-balancer-webhook-service.kube-system.svc
|
||||
- aws-load-balancer-webhook-service.kube-system.svc.cluster.local
|
||||
issuerRef:
|
||||
kind: Issuer
|
||||
name: aws-load-balancer-selfsigned-issuer
|
||||
secretName: aws-load-balancer-webhook-tls
|
||||
---
|
||||
apiVersion: cert-manager.io/v1
|
||||
kind: Issuer
|
||||
metadata:
|
||||
name: aws-load-balancer-selfsigned-issuer
|
||||
namespace: kube-system
|
||||
spec:
|
||||
selfSigned: {}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: aws-load-balancer-webhook-service
|
||||
namespace: kube-system
|
||||
spec:
|
||||
ports:
|
||||
- name: webhook-server
|
||||
port: 443
|
||||
targetPort: 9443
|
||||
selector:
|
||||
app.kubernetes.io/component: controller
|
||||
app.kubernetes.io/name: aws-load-balancer-controller
|
||||
@@ -0,0 +1,7 @@
|
||||
apiVersion: v1
|
||||
kind: ServiceAccount
|
||||
metadata:
|
||||
name: ecr-service-account
|
||||
namespace: default
|
||||
annotations:
|
||||
eks.amazonaws.com/role-arn: arn:aws:iam::315680545607:role/EKS-ECR-Role
|
||||
@@ -0,0 +1,13 @@
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: RoleBinding
|
||||
metadata:
|
||||
name: deployment-manager-binding
|
||||
namespace: default
|
||||
subjects:
|
||||
- kind: User
|
||||
name: do-nyc1-agent-cluster-admin
|
||||
apiGroup: rbac.authorization.k8s.io
|
||||
roleRef:
|
||||
kind: Role
|
||||
name: deployment-manager
|
||||
apiGroup: rbac.authorization.k8s.io
|
||||
@@ -0,0 +1,13 @@
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: RoleBinding
|
||||
metadata:
|
||||
name: deployment-manager-binding
|
||||
namespace: default
|
||||
subjects:
|
||||
- kind: User
|
||||
name: admin@k3d-agentstack-cluster
|
||||
apiGroup: rbac.authorization.k8s.io
|
||||
roleRef:
|
||||
kind: Role
|
||||
name: deployment-manager
|
||||
apiGroup: rbac.authorization.k8s.io
|
||||
@@ -0,0 +1,15 @@
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: Role
|
||||
metadata:
|
||||
name: deployment-manager
|
||||
namespace: default
|
||||
rules:
|
||||
- apiGroups: ["apps"] # Deployments are part of the "apps" API group
|
||||
resources: ["deployments"]
|
||||
verbs: ["get", "list", "create", "update", "delete"]
|
||||
- apiGroups: [""] # Core API group
|
||||
resources: [ "namespaces" ]
|
||||
verbs: [ "get", "list" ]
|
||||
- apiGroups: [""]
|
||||
resources: ["services/proxy"]
|
||||
verbs: ["get", "create", "post"]
|
||||
@@ -0,0 +1,3 @@
|
||||
## Configs
|
||||
|
||||
look at the atuin runbooks for cluster connection and setup
|
||||
@@ -0,0 +1,38 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: redis
|
||||
spec:
|
||||
replicas: 1 # Only need one Redis instance
|
||||
selector:
|
||||
matchLabels:
|
||||
app: redis
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: redis
|
||||
spec:
|
||||
containers:
|
||||
- name: redis
|
||||
image: redis:latest
|
||||
resources:
|
||||
requests:
|
||||
memory: "128Mi"
|
||||
cpu: "100m"
|
||||
limits:
|
||||
memory: "256Mi"
|
||||
cpu: "500m"
|
||||
ports:
|
||||
- containerPort: 6379
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: redis
|
||||
spec:
|
||||
type: LoadBalancer
|
||||
ports:
|
||||
- port: 6379
|
||||
targetPort: 6379
|
||||
selector:
|
||||
app: redis
|
||||
@@ -0,0 +1,41 @@
|
||||
# Configuration files
|
||||
config/
|
||||
.env.local
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.so
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
|
||||
# Virtual environments
|
||||
.venv/
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
@@ -0,0 +1,285 @@
|
||||
# Jockey - Kubernetes Deployment Package
|
||||
|
||||
## Project Overview
|
||||
|
||||
Jockey is a Python package that implements Kubernetes-based deployment orchestration for AI agents, based on the patterns and features from the AgentStack TypeScript host project. It provides a clean, model-style interface for managing Kubernetes resources and deployment workflows.
|
||||
|
||||
## Architecture Goals
|
||||
|
||||
The jockey package is designed as a standalone Python library that can be embedded in other applications or used directly for Kubernetes deployment operations. It follows the repository's patterns for environment configuration and provides a clean abstraction over the Kubernetes Python client.
|
||||
|
||||
## Core Features to Implement
|
||||
|
||||
### 1. Kubernetes Resource Management
|
||||
|
||||
**Models to Implement:**
|
||||
- `Deployment` - Kubernetes deployment management
|
||||
- `Service` - Service discovery and load balancing
|
||||
- `ConfigMap` - Configuration management
|
||||
- `Secret` - Sensitive data management
|
||||
- `ResourceQuota` - Resource limit enforcement
|
||||
- `Pod` - Individual pod management and monitoring
|
||||
|
||||
**Key Capabilities:**
|
||||
- Dynamic deployment creation and updates
|
||||
- Real-time status monitoring using Kubernetes Watch API
|
||||
- Resource constraint management (CPU/Memory limits)
|
||||
- Automatic rollback on deployment failures
|
||||
- Pod lifecycle management and health checks
|
||||
|
||||
### 2. Docker Integration
|
||||
|
||||
**Components:**
|
||||
- `DockerBuilder` - Docker image building and management
|
||||
- `Registry` - Docker registry operations (push/pull)
|
||||
- `ImageManager` - Version control and cleanup
|
||||
|
||||
**Features:**
|
||||
- Dynamic Dockerfile generation from project templates
|
||||
- Build progress streaming and logging
|
||||
- Registry authentication and image pushing
|
||||
- Image versioning and tag management
|
||||
- Build artifact cleanup
|
||||
|
||||
### 3. Deployment Pipeline
|
||||
|
||||
**Pipeline Stages:**
|
||||
1. **Upload/Extract** - Project code processing
|
||||
2. **Build** - Docker image creation
|
||||
3. **Deploy** - Kubernetes deployment
|
||||
4. **Monitor** - Real-time status tracking
|
||||
5. **Cleanup** - Resource management
|
||||
|
||||
**Data Structures:**
|
||||
```python
|
||||
@dataclass
|
||||
class DeploymentConfig:
|
||||
project_id: str
|
||||
image_tag: str
|
||||
replicas: int = 1
|
||||
cpu_request: str = "100m"
|
||||
cpu_limit: str = "500m"
|
||||
memory_request: str = "128Mi"
|
||||
memory_limit: str = "256Mi"
|
||||
environment_vars: Dict[str, str] = field(default_factory=dict)
|
||||
|
||||
@dataclass
|
||||
class BuildContext:
|
||||
project_path: str
|
||||
dockerfile_content: str
|
||||
image_name: str
|
||||
build_logs: List[str] = field(default_factory=list)
|
||||
|
||||
@dataclass
|
||||
class DeploymentStatus:
|
||||
name: str
|
||||
status: Literal["pending", "building", "deploying", "running", "failed"]
|
||||
replicas_ready: int
|
||||
replicas_desired: int
|
||||
created_at: datetime
|
||||
last_updated: datetime
|
||||
error_message: Optional[str] = None
|
||||
```
|
||||
|
||||
### 4. Multi-tenancy and Isolation
|
||||
|
||||
**Namespace Management:**
|
||||
- Organization-based namespace isolation
|
||||
- Project-specific resource labeling
|
||||
- RBAC integration for access control
|
||||
- Resource quota enforcement per namespace
|
||||
|
||||
**Security Features:**
|
||||
- Secret management for registry credentials
|
||||
- ConfigMap isolation between projects
|
||||
- Network policies for pod isolation
|
||||
- Service account management
|
||||
|
||||
### 5. Monitoring and Observability
|
||||
|
||||
**Metrics Collection:**
|
||||
- Deployment status tracking
|
||||
- Resource utilization monitoring
|
||||
- Build time and success rate metrics
|
||||
- Pod restart and failure tracking
|
||||
|
||||
**Logging Integration:**
|
||||
- Structured logging with correlation IDs
|
||||
- Build log streaming
|
||||
- Pod log aggregation
|
||||
- Error tracking and alerting
|
||||
|
||||
### 6. Real-time Communication
|
||||
|
||||
**WebSocket Support:**
|
||||
- Build progress streaming
|
||||
- Deployment status updates
|
||||
- Pod log streaming
|
||||
- Resource metric updates
|
||||
|
||||
**Event System:**
|
||||
- Kubernetes watch event processing
|
||||
- Custom event publishing
|
||||
- Webhook integration for external notifications
|
||||
|
||||
## Implementation Plan
|
||||
|
||||
### Phase 1: Core Kubernetes Models (Completed)
|
||||
- ✅ BaseModel with shared client access
|
||||
- ✅ Deployment model with CRUD operations
|
||||
- ✅ Environment configuration
|
||||
- ✅ Client wrapper with proper typing
|
||||
|
||||
### Phase 2: Extended Resource Models
|
||||
- `Service` model for load balancing
|
||||
- `ConfigMap` model for configuration
|
||||
- `Secret` model for sensitive data
|
||||
- `Pod` model for individual pod management
|
||||
- `ResourceQuota` model for limits
|
||||
|
||||
### Phase 3: Docker Integration
|
||||
- `DockerBuilder` for image creation
|
||||
- `Registry` client for push/pull operations
|
||||
- Build context management
|
||||
- Progress streaming utilities
|
||||
|
||||
### Phase 4: Deployment Pipeline
|
||||
- `DeploymentPipeline` orchestrator
|
||||
- Build and deploy workflow
|
||||
- Status monitoring and reporting
|
||||
- Error handling and rollback
|
||||
|
||||
### Phase 5: Advanced Features
|
||||
- Multi-tenant namespace management
|
||||
- Real-time event streaming
|
||||
- Metrics collection and reporting
|
||||
- Integration with external services
|
||||
|
||||
## Data Structures from Host Project
|
||||
|
||||
### Project Configuration
|
||||
```python
|
||||
@dataclass
|
||||
class ProjectConfig:
|
||||
id: str
|
||||
name: str
|
||||
organization_id: str
|
||||
environment: str = "production"
|
||||
region: str = "us-east-1"
|
||||
framework: str = "agentstack"
|
||||
python_version: str = "3.12"
|
||||
```
|
||||
|
||||
### Resource Specifications
|
||||
```python
|
||||
@dataclass
|
||||
class ResourceSpec:
|
||||
cpu_request: str = "100m"
|
||||
cpu_limit: str = "500m"
|
||||
memory_request: str = "128Mi"
|
||||
memory_limit: str = "256Mi"
|
||||
storage_request: str = "1Gi"
|
||||
storage_limit: str = "10Gi"
|
||||
```
|
||||
|
||||
### Deployment Metadata
|
||||
```python
|
||||
@dataclass
|
||||
class DeploymentMetadata:
|
||||
project_id: str
|
||||
version: str
|
||||
deployed_at: datetime
|
||||
deployed_by: str
|
||||
build_hash: str
|
||||
environment_vars: Dict[str, str]
|
||||
labels: Dict[str, str]
|
||||
```
|
||||
|
||||
## Kubernetes Concepts Integration
|
||||
|
||||
### 1. Deployment Patterns
|
||||
- **Rolling Updates**: Zero-downtime deployments with configurable rollout strategy
|
||||
- **Blue/Green**: Environment switching for testing and validation
|
||||
- **Canary**: Gradual traffic shifting for risk mitigation
|
||||
- **Resource Quotas**: CPU/Memory constraints per deployment
|
||||
|
||||
### 2. Service Discovery
|
||||
- **ClusterIP**: Internal service communication
|
||||
- **LoadBalancer**: External traffic distribution
|
||||
- **Ingress**: HTTP/HTTPS routing and TLS termination
|
||||
- **DNS**: Service name resolution
|
||||
|
||||
### 3. Configuration Management
|
||||
- **ConfigMaps**: Non-sensitive configuration data
|
||||
- **Secrets**: Sensitive data (API keys, passwords)
|
||||
- **Environment Variables**: Runtime configuration
|
||||
- **Volume Mounts**: File-based configuration
|
||||
|
||||
### 4. Observability
|
||||
- **Pod Logs**: Application output streaming
|
||||
- **Metrics**: Resource utilization tracking
|
||||
- **Health Checks**: Liveness and readiness probes
|
||||
- **Events**: Kubernetes system events
|
||||
|
||||
## Environment Configuration
|
||||
|
||||
Following the repository pattern, jockey uses top-level environment constants:
|
||||
|
||||
```python
|
||||
# Kubernetes configuration
|
||||
KUBERNETES_NAMESPACE = os.getenv("KUBERNETES_NAMESPACE", "default")
|
||||
KUBECONFIG_PATH = os.getenv("KUBECONFIG")
|
||||
KUBERNETES_CONTEXT = os.getenv("KUBERNETES_CONTEXT")
|
||||
|
||||
# Docker registry
|
||||
DOCKER_REGISTRY = os.getenv("DOCKER_REGISTRY", "docker.io")
|
||||
DOCKER_USERNAME = os.getenv("DOCKER_USERNAME")
|
||||
DOCKER_PASSWORD = os.getenv("DOCKER_PASSWORD")
|
||||
|
||||
# Resource limits
|
||||
DEFAULT_CPU_REQUEST = os.getenv("DEFAULT_CPU_REQUEST", "100m")
|
||||
DEFAULT_CPU_LIMIT = os.getenv("DEFAULT_CPU_LIMIT", "500m")
|
||||
DEFAULT_MEMORY_REQUEST = os.getenv("DEFAULT_MEMORY_REQUEST", "128Mi")
|
||||
DEFAULT_MEMORY_LIMIT = os.getenv("DEFAULT_MEMORY_LIMIT", "256Mi")
|
||||
|
||||
# Build configuration
|
||||
BUILD_TIMEOUT = int(os.getenv("BUILD_TIMEOUT", "900")) # 15 minutes
|
||||
MAX_BUILD_LOG_SIZE = int(os.getenv("MAX_BUILD_LOG_SIZE", "10485760")) # 10MB
|
||||
```
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Deployment
|
||||
```python
|
||||
from jockey.models import Deployment
|
||||
from jockey.pipeline import DeploymentPipeline
|
||||
|
||||
# Create deployment
|
||||
deployment = Deployment.create(
|
||||
name="my-agent",
|
||||
image="myregistry/agent:v1.0.0",
|
||||
replicas=3
|
||||
)
|
||||
|
||||
# Monitor status
|
||||
status = deployment.get_status()
|
||||
print(f"Ready replicas: {status.replicas_ready}/{status.replicas_desired}")
|
||||
```
|
||||
|
||||
### Full Pipeline
|
||||
```python
|
||||
from jockey.pipeline import DeploymentPipeline
|
||||
from jockey.models import DeploymentConfig
|
||||
|
||||
config = DeploymentConfig(
|
||||
project_id="my-project",
|
||||
image_tag="v1.2.0",
|
||||
replicas=2,
|
||||
environment_vars={"API_KEY": "secret-value"}
|
||||
)
|
||||
|
||||
pipeline = DeploymentPipeline(config)
|
||||
result = await pipeline.execute()
|
||||
```
|
||||
|
||||
This project plan provides a comprehensive roadmap for implementing the jockey package with all the features and patterns identified from the host TypeScript project, adapted for Python and following the repository's established conventions.
|
||||
@@ -0,0 +1,397 @@
|
||||
# Jockey - Kubernetes Deployment Tool
|
||||
|
||||
Jockey is a Python-based tool for building container images and deploying them to Kubernetes clusters. It uses Kaniko for secure, rootless image building and supports AWS ECR for container registry.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python virtual environment activated (`source ../api/.venv/bin/activate`)
|
||||
- Kubeconfig file configured at `./config/kubeconfig`
|
||||
- AWS credentials secret deployed to Kubernetes
|
||||
- ECR repository available
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Configure these in your environment or `.env` file:
|
||||
|
||||
```bash
|
||||
# Kubernetes Configuration
|
||||
KUBECONFIG=./config/kubeconfig
|
||||
KUBERNETES_NAMESPACE=default
|
||||
|
||||
# Container Registry
|
||||
IMAGE_REGISTRY=315680545607.dkr.ecr.us-west-1.amazonaws.com
|
||||
AWS_DEFAULT_REGION=us-west-1
|
||||
|
||||
# AWS Credentials (for kubectl secret)
|
||||
AWS_ACCESS_KEY_ID=your_access_key
|
||||
AWS_SECRET_ACCESS_KEY=your_secret_key
|
||||
```
|
||||
|
||||
## Setup Commands
|
||||
|
||||
### 1. Setup Kubeconfig
|
||||
```bash
|
||||
# From the jockey directory
|
||||
export KUBECONFIG=./config/kubeconfig
|
||||
python -m jockey setup-kubeconfig
|
||||
```
|
||||
|
||||
### 2. Setup Builder Namespace and AWS Credentials
|
||||
```bash
|
||||
# Create builder namespace and AWS credentials secret from local AWS CLI
|
||||
python -m jockey setup-builder
|
||||
```
|
||||
|
||||
This command will:
|
||||
- Create a dedicated `builder` namespace for image building operations
|
||||
- Extract AWS credentials from your local AWS CLI configuration
|
||||
- Create the `aws-credentials` secret in the builder namespace
|
||||
|
||||
**Why this matters**: Builder pods need AWS credentials to push images to ECR, but deployment pods don't need these credentials since they only pull images. By isolating builder operations in their own namespace, we maintain better security separation.
|
||||
|
||||
## Testing Commands
|
||||
|
||||
All commands should be run from the deploy directory with the virtual environment activated:
|
||||
|
||||
```bash
|
||||
# Activate virtual environment and set kubeconfig
|
||||
source ../api/.venv/bin/activate
|
||||
export KUBECONFIG=./config/kubeconfig
|
||||
```
|
||||
|
||||
### Build and Push Image Only
|
||||
```bash
|
||||
# Test image building and pushing to ECR
|
||||
python -m jockey test-build
|
||||
|
||||
# The test-build command uses default configured values (hosting/agent-images)
|
||||
# and doesn't require additional parameters for basic testing
|
||||
```
|
||||
|
||||
### Complete Build and Deploy
|
||||
```bash
|
||||
# Build image, push to ECR, and deploy to Kubernetes (uses default namespace)
|
||||
python -m jockey deploy-test
|
||||
|
||||
# Deploy with custom namespace (must exist first!)
|
||||
python -m jockey deploy-test --namespace test-namespace
|
||||
|
||||
# Deploy with custom template
|
||||
python -m jockey deploy-test --template simple-api
|
||||
```
|
||||
|
||||
### Management Commands
|
||||
```bash
|
||||
# List running instances in a specific project namespace
|
||||
python -m jockey list-instances --namespace PROJECT_ID
|
||||
|
||||
# List builder pods
|
||||
python -m jockey list-instances --namespace builder
|
||||
|
||||
# Stop a deployment (note: deployment name comes BEFORE --namespace)
|
||||
python -m jockey stop-deployment DEPLOYMENT_NAME --namespace PROJECT_ID
|
||||
|
||||
# Stop a specific pod
|
||||
python -m jockey stop-pod pod-name-12345 --namespace PROJECT_ID
|
||||
|
||||
# View builder logs across all namespaces
|
||||
python -m jockey logs-builder -f
|
||||
```
|
||||
|
||||
## CLI Usage Tips
|
||||
|
||||
### Command Discovery
|
||||
```bash
|
||||
# See all available commands
|
||||
python -m jockey --help
|
||||
|
||||
# Get help for specific commands
|
||||
python -m jockey deploy-test --help
|
||||
python -m jockey stop-deployment --help
|
||||
```
|
||||
|
||||
### Common CLI Patterns
|
||||
1. **Parameter Order**: For commands that take a resource name, the name comes FIRST, then flags:
|
||||
```bash
|
||||
# ✅ Correct
|
||||
python -m jockey stop-deployment hosting-agent-images --namespace default
|
||||
|
||||
# ❌ Wrong
|
||||
python -m jockey stop-deployment --namespace default hosting-agent-images
|
||||
```
|
||||
|
||||
2. **Namespace Requirements**: Custom namespaces must exist in Kubernetes before use:
|
||||
```bash
|
||||
# Create namespace first if needed
|
||||
kubectl create namespace test-namespace
|
||||
|
||||
# Then deploy to it
|
||||
python -m jockey deploy-test --namespace test-namespace
|
||||
```
|
||||
|
||||
3. **Deployment Conflicts**: If a deployment already exists, stop it first:
|
||||
```bash
|
||||
# Clean up existing deployment
|
||||
python -m jockey stop-deployment hosting-agent-images --namespace default
|
||||
|
||||
# Then deploy fresh
|
||||
python -m jockey deploy-test
|
||||
```
|
||||
|
||||
4. **Error Recovery**: If a command fails, check the specific error:
|
||||
- `namespaces "X" not found` → Create the namespace first
|
||||
- `deployments.apps "X" already exists` → Stop the existing deployment
|
||||
- `ModuleNotFoundError` → Check you're in the right directory and venv is activated
|
||||
|
||||
### Direct Kubernetes Commands
|
||||
```bash
|
||||
# Check deployments
|
||||
kubectl get deployments --namespace default
|
||||
|
||||
# Check pods
|
||||
kubectl get pods --namespace default -l app=hosting-agent-images
|
||||
|
||||
# Check pod logs
|
||||
kubectl logs pod-name --namespace default
|
||||
|
||||
# Describe pod for troubleshooting
|
||||
kubectl describe pod pod-name --namespace default
|
||||
|
||||
# Delete deployment
|
||||
kubectl delete deployment hosting-agent-images --namespace default
|
||||
```
|
||||
|
||||
## Available Templates
|
||||
|
||||
Templates are located in `./templates/docker/`:
|
||||
|
||||
- **test**: Simple HTTP server for testing (Alpine + netcat)
|
||||
- **python-agent**: Python application with AgentStack (incomplete)
|
||||
|
||||
## Architecture
|
||||
|
||||
### Namespace Strategy
|
||||
|
||||
Jockey uses a multi-namespace approach for security and isolation:
|
||||
|
||||
#### 1. Builder Namespace (`builder`)
|
||||
- **Purpose**: Houses all image building operations
|
||||
- **Contains**: Kaniko builder pods, AWS credentials secret, build-related ConfigMaps
|
||||
- **Access**: Only builder pods can access AWS credentials for ECR pushing
|
||||
- **Lifecycle**: Persistent namespace, created during setup
|
||||
|
||||
#### 2. Project Namespaces (`project-id`)
|
||||
- **Purpose**: Isolates individual project deployments
|
||||
- **Contains**: Application pods, project-specific secrets (AgentOps API keys), services
|
||||
- **Access**: No AWS credentials needed - only pulls images from ECR
|
||||
- **Lifecycle**: Created automatically when deploying a project
|
||||
|
||||
#### 3. Default Namespace (`default`)
|
||||
- **Purpose**: Legacy operations and cluster-wide resources
|
||||
- **Contains**: May contain shared resources for backward compatibility
|
||||
- **Access**: Limited use in current architecture
|
||||
|
||||
### Secret Management
|
||||
|
||||
#### Cross-Namespace Secret Limitations
|
||||
Kubernetes secrets are namespace-scoped and **cannot be referenced across namespaces**. This is a security feature that maintains namespace isolation.
|
||||
|
||||
#### Our Secret Strategy
|
||||
1. **AWS Credentials**: Only stored in `builder` namespace
|
||||
- Builder pods authenticate with ECR to push images
|
||||
- Deployment pods don't need AWS credentials (ECR pull is cluster-level)
|
||||
|
||||
2. **Project Secrets**: Stored in each project namespace
|
||||
- AgentOps API keys automatically injected from project configuration
|
||||
- Environment-specific secrets isolated per project
|
||||
|
||||
3. **Shared Resources**: Must be replicated to each namespace that needs them
|
||||
- No cross-namespace secret sharing by design
|
||||
- Tools like `kubernetes-reflector` can automate secret replication if needed
|
||||
|
||||
### Image Building
|
||||
- Uses **Kaniko** for secure, rootless container builds in Kubernetes
|
||||
- Builds run as Kubernetes Jobs in the `builder` namespace
|
||||
- Images are pushed directly to AWS ECR with AWS credentials from builder namespace
|
||||
- Built images are referenced by full ECR URL from any namespace
|
||||
|
||||
### Deployment
|
||||
- Creates Kubernetes Deployments in project-specific namespaces
|
||||
- Pulls images from ECR using cluster-level permissions
|
||||
- Automatically includes project-specific secrets (AgentOps API keys)
|
||||
- Supports health checks, environment variables, and volume mounts
|
||||
- Watches deployment progress with real-time events
|
||||
|
||||
### Security
|
||||
- AWS credentials isolated in builder namespace only
|
||||
- Project secrets isolated per namespace
|
||||
- No Docker daemon required (uses Kaniko)
|
||||
- Namespace-based access control and resource isolation
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
1. **Image pull errors**: Check AWS credentials secret exists and is correctly formatted
|
||||
2. **Build failures**: Verify ECR repository exists and AWS credentials have push permissions
|
||||
3. **CrashLoopBackOff**: Check container logs and ensure the application runs as a long-lived process
|
||||
4. **Job name errors**: Kubernetes names can't contain `/` or `:` - they're automatically sanitized
|
||||
|
||||
### Debug Commands
|
||||
```bash
|
||||
# Check recent builder pods (now in builder namespace)
|
||||
kubectl get pods --namespace builder | grep builder
|
||||
|
||||
# Check builder logs (use logs-builder command for convenience)
|
||||
python -m jockey logs-builder -f
|
||||
|
||||
# Check AWS credentials secret in builder namespace
|
||||
kubectl get secret aws-credentials --namespace builder -o yaml
|
||||
|
||||
# Check project deployment pods
|
||||
kubectl get pods --namespace PROJECT_ID
|
||||
|
||||
# Check project secrets
|
||||
kubectl get secrets --namespace PROJECT_ID
|
||||
|
||||
# Verify ECR repository exists
|
||||
aws ecr describe-repositories --region us-west-1 --registry-id 315680545607
|
||||
```
|
||||
|
||||
## Development Notes
|
||||
|
||||
### TODO Items
|
||||
- **Missing crash event feedback**: Deploy command doesn't report container crashes (CrashLoopBackOff) - it just times out silently
|
||||
- **Image pull security**: Consider implementing image pull secrets or IRSA for more secure ECR authentication
|
||||
- **Layer caching**: Implement persistent layer caching for faster builds
|
||||
|
||||
### File Structure
|
||||
```
|
||||
jockey/
|
||||
├── README.md # This file
|
||||
├── __main__.py # CLI commands
|
||||
├── api.py # Public API
|
||||
├── environment.py # Configuration
|
||||
├── backend/models/
|
||||
│ ├── image.py # Image building with Kaniko
|
||||
│ ├── deployment.py # Kubernetes deployments
|
||||
│ └── pod.py # Pod management
|
||||
├── templates/docker/ # Dockerfile templates
|
||||
└── config/
|
||||
└── kubeconfig # Kubernetes config
|
||||
```
|
||||
|
||||
## Example Workflow
|
||||
|
||||
Complete end-to-end example:
|
||||
|
||||
```bash
|
||||
# 1. Initial setup (one-time)
|
||||
source ../api/.venv/bin/activate
|
||||
export KUBECONFIG=./config/kubeconfig
|
||||
|
||||
# Setup kubeconfig
|
||||
python -m jockey setup-kubeconfig
|
||||
|
||||
# Setup builder namespace and AWS credentials
|
||||
python -m jockey setup-builder
|
||||
|
||||
# 2. Build and deploy
|
||||
python -m jockey deploy-test --name hosting/agent-images --template test
|
||||
|
||||
# 3. Verify deployment
|
||||
kubectl get pods -l app=hosting-agent-images
|
||||
|
||||
# 4. Monitor build progress
|
||||
python -m jockey logs-builder -f
|
||||
|
||||
# 5. Cleanup
|
||||
kubectl delete deployment hosting-agent-images
|
||||
```
|
||||
|
||||
## Worker Deployment
|
||||
|
||||
The jockey worker can be deployed as a Docker container to process deployment jobs from a Redis queue.
|
||||
|
||||
### Building the Worker Image
|
||||
|
||||
```bash
|
||||
# Build from the jockey directory
|
||||
cd /path/to/jockey
|
||||
docker build -f worker/Dockerfile -t jockey-worker .
|
||||
```
|
||||
|
||||
### Running the Worker Container
|
||||
|
||||
```bash
|
||||
# Check worker and queue status
|
||||
docker run --rm jockey-worker python -m jockey.worker status
|
||||
|
||||
# Start the worker (requires Redis connection)
|
||||
docker run --rm \
|
||||
-e DEPLOY_REDIS_HOST=redis.example.com \
|
||||
-e DEPLOY_REDIS_PORT=6379 \
|
||||
-e DEPLOY_REDIS_DB=0 \
|
||||
jockey-worker
|
||||
|
||||
# Run with Redis linked container
|
||||
docker run --rm \
|
||||
--link redis:redis \
|
||||
-e DEPLOY_REDIS_HOST=redis \
|
||||
jockey-worker
|
||||
|
||||
# Health check command (used by Docker HEALTHCHECK)
|
||||
docker run --rm jockey-worker python -m jockey.worker health
|
||||
```
|
||||
|
||||
### Worker Commands
|
||||
|
||||
- `python -m jockey.worker start` - Start the deployment worker
|
||||
- `python -m jockey.worker status` - Show queue status and connection info
|
||||
- `python -m jockey.worker health` - Health check (exit 0 = healthy, exit 1 = unhealthy)
|
||||
|
||||
### Environment Variables
|
||||
|
||||
Required for worker operation:
|
||||
|
||||
```bash
|
||||
# Redis Configuration (required)
|
||||
DEPLOY_REDIS_HOST=localhost # Redis server hostname
|
||||
DEPLOY_REDIS_PORT=6379 # Redis server port
|
||||
DEPLOY_REDIS_DB=0 # Redis database number
|
||||
|
||||
# Worker Configuration (optional)
|
||||
WORKER_POLL_INTERVAL=5 # Seconds between queue polls
|
||||
|
||||
# Kubernetes Configuration (required for deployments)
|
||||
KUBECONFIG=/path/to/kubeconfig
|
||||
KUBERNETES_NAMESPACE=default
|
||||
|
||||
# AWS Configuration (required for ECR)
|
||||
AWS_ACCESS_KEY_ID=your_key
|
||||
AWS_SECRET_ACCESS_KEY=your_secret
|
||||
AWS_DEFAULT_REGION=us-west-1
|
||||
```
|
||||
|
||||
### Docker Compose Example
|
||||
|
||||
```yaml
|
||||
version: '3.8'
|
||||
services:
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
ports:
|
||||
- "6379:6379"
|
||||
|
||||
jockey-worker:
|
||||
image: jockey-worker
|
||||
depends_on:
|
||||
- redis
|
||||
environment:
|
||||
- DEPLOY_REDIS_HOST=redis
|
||||
- DEPLOY_REDIS_PORT=6379
|
||||
- DEPLOY_REDIS_DB=0
|
||||
- WORKER_POLL_INTERVAL=5
|
||||
volumes:
|
||||
- /path/to/kubeconfig:/app/config/kubeconfig:ro
|
||||
```
|
||||
@@ -0,0 +1,48 @@
|
||||
from jockey.backend.models.image import ensure_ecr_repository
|
||||
from jockey.backend.event import BaseEvent
|
||||
from jockey.worker.queue import (
|
||||
queue_task,
|
||||
get_task_events,
|
||||
get_task_status,
|
||||
get_tasks,
|
||||
)
|
||||
from jockey.secret import (
|
||||
create_secret,
|
||||
delete_secret,
|
||||
list_secrets,
|
||||
)
|
||||
from jockey.exec import (
|
||||
AggregatedEvent,
|
||||
execute_serve,
|
||||
execute_build,
|
||||
execute_run,
|
||||
delete_deployment_resources,
|
||||
)
|
||||
from jockey.config import (
|
||||
TaskType,
|
||||
DeploymentConfig,
|
||||
DeploymentPack,
|
||||
)
|
||||
|
||||
__version__ = "0.1.0"
|
||||
|
||||
__all__ = [
|
||||
"__version__",
|
||||
"BaseEvent",
|
||||
"AggregatedEvent",
|
||||
"TaskType",
|
||||
"DeploymentConfig",
|
||||
"DeploymentPack",
|
||||
"queue_task",
|
||||
"get_task_events",
|
||||
"get_task_status",
|
||||
"get_tasks",
|
||||
"create_secret",
|
||||
"delete_secret",
|
||||
"list_secrets",
|
||||
"delete_deployment_resources",
|
||||
"ensure_ecr_repository",
|
||||
"execute_serve",
|
||||
"execute_build",
|
||||
"execute_run",
|
||||
]
|
||||
@@ -0,0 +1,598 @@
|
||||
import os
|
||||
import subprocess
|
||||
import click
|
||||
|
||||
from .backend import Pod
|
||||
from . import DeploymentConfig, execute_serve
|
||||
from .backend.event import EventStatus
|
||||
from .environment import EKS_CLUSTER_NAME, AWS_REGION, AWS_PROFILE, KUBECONFIG_PATH, BUILDER_NAMESPACE, ALB_SHARED_GROUP_NAME
|
||||
|
||||
|
||||
@click.group()
|
||||
def cli():
|
||||
"""Jockey - Kubernetes deployment management tool."""
|
||||
pass
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.option('--namespace', default='default', help='Kubernetes namespace to list pods from')
|
||||
def list_instances(namespace):
|
||||
"""List all running pod instances in the namespace."""
|
||||
try:
|
||||
pods = Pod.filter(namespace=namespace)
|
||||
|
||||
if not pods:
|
||||
click.echo(f"No running instances found in namespace '{namespace}'.")
|
||||
return
|
||||
|
||||
click.echo(f"Found {len(pods)} running instance(s) in namespace '{namespace}':\n")
|
||||
|
||||
for pod in pods:
|
||||
status = "●" if pod.ready else "○"
|
||||
phase = pod.phase or "Unknown"
|
||||
node = pod.node_name or "N/A"
|
||||
|
||||
click.echo(f"{status} {pod.name}")
|
||||
click.echo(f" Phase: {phase}")
|
||||
click.echo(f" Node: {node}")
|
||||
click.echo(f" Restarts: {pod.restart_count}")
|
||||
if pod.pod_ip:
|
||||
click.echo(f" IP: {pod.pod_ip}")
|
||||
click.echo()
|
||||
|
||||
except Exception as e:
|
||||
click.echo(f"Error listing instances: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.option('--namespace', default='default', help='Kubernetes namespace')
|
||||
@click.argument('pod_name')
|
||||
def stop_pod(namespace, pod_name):
|
||||
"""Stop (delete) a pod by name."""
|
||||
try:
|
||||
click.echo(f"🛑 Stopping pod '{pod_name}' in namespace '{namespace}'...")
|
||||
|
||||
success = Pod.delete_by_name(name=pod_name, namespace=namespace)
|
||||
|
||||
if success:
|
||||
click.echo(f"✅ Pod '{pod_name}' deleted successfully!")
|
||||
else:
|
||||
click.echo(
|
||||
f"❌ Failed to delete pod '{pod_name}' - it may not exist or you may not have permission."
|
||||
)
|
||||
raise click.Abort()
|
||||
|
||||
except Exception as e:
|
||||
click.echo(f"❌ Error stopping pod: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.option('--namespace', default='default', help='Kubernetes namespace')
|
||||
@click.argument('deployment_name')
|
||||
def stop_deployment(namespace, deployment_name):
|
||||
"""Stop (delete) a deployment by name."""
|
||||
try:
|
||||
from .backend.models.deployment import Deployment
|
||||
|
||||
click.echo(f"🛑 Stopping deployment '{deployment_name}' in namespace '{namespace}'...")
|
||||
|
||||
# Check if deployment exists first
|
||||
deployment = Deployment.get(name=deployment_name, namespace=namespace)
|
||||
if not deployment:
|
||||
click.echo(f"❌ Deployment '{deployment_name}' not found in namespace '{namespace}'.")
|
||||
raise click.Abort()
|
||||
|
||||
# Delete the deployment
|
||||
success = Deployment.delete_by_name(name=deployment_name, namespace=namespace)
|
||||
|
||||
if success:
|
||||
click.echo(f"✅ Deployment '{deployment_name}' deleted successfully!")
|
||||
click.echo("💡 All pods managed by this deployment will be terminated.")
|
||||
else:
|
||||
click.echo(f"❌ Failed to delete deployment '{deployment_name}'.")
|
||||
raise click.Abort()
|
||||
|
||||
except Exception as e:
|
||||
click.echo(f"❌ Error stopping deployment: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
@cli.command()
|
||||
def setup_kubeconfig():
|
||||
"""Generate kubeconfig for EKS cluster using AWS CLI."""
|
||||
try:
|
||||
# Assert required environment variables are set
|
||||
if not EKS_CLUSTER_NAME:
|
||||
raise ValueError("EKS_CLUSTER_NAME")
|
||||
if not AWS_REGION:
|
||||
raise ValueError("AWS_REGION")
|
||||
|
||||
# Ensure config directory exists
|
||||
os.makedirs(os.path.dirname(KUBECONFIG_PATH), exist_ok=True)
|
||||
|
||||
click.echo(f"Generating kubeconfig for cluster: {EKS_CLUSTER_NAME}")
|
||||
click.echo(f"Region: {AWS_REGION}")
|
||||
|
||||
# Run aws eks update-kubeconfig command
|
||||
cmd = [
|
||||
'aws',
|
||||
'eks',
|
||||
'update-kubeconfig',
|
||||
'--region',
|
||||
AWS_REGION,
|
||||
'--name',
|
||||
EKS_CLUSTER_NAME,
|
||||
'--kubeconfig',
|
||||
KUBECONFIG_PATH,
|
||||
]
|
||||
|
||||
if AWS_PROFILE:
|
||||
cmd.extend(['--profile', AWS_PROFILE])
|
||||
|
||||
result = subprocess.run(cmd, capture_output=True, text=True)
|
||||
|
||||
if result.returncode == 0:
|
||||
click.echo("✅ Kubeconfig generated successfully!")
|
||||
click.echo(f"Config saved to: {KUBECONFIG_PATH}")
|
||||
else:
|
||||
click.echo("❌ Failed to generate kubeconfig:")
|
||||
click.echo(result.stderr)
|
||||
raise click.Abort()
|
||||
|
||||
except ValueError as e:
|
||||
click.echo(f"❌ Missing required environment variable: {e}")
|
||||
click.echo("Please ensure EKS_CLUSTER_NAME and AWS_REGION are set in your .env file")
|
||||
raise click.Abort()
|
||||
except FileNotFoundError:
|
||||
click.echo("❌ awscli not found. Please install it first.")
|
||||
raise click.Abort()
|
||||
except Exception as e:
|
||||
click.echo(f"❌ Error generating kubeconfig: {e}")
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
@cli.command()
|
||||
def setup_builder():
|
||||
"""Setup builder namespace and create AWS credentials secret from local AWS CLI."""
|
||||
try:
|
||||
from .environment import KUBECONFIG_PATH, AWS_PROFILE
|
||||
|
||||
click.echo("🔧 Setting up builder namespace and AWS credentials...")
|
||||
|
||||
# Create builder namespace
|
||||
cmd = ['kubectl', '--kubeconfig', KUBECONFIG_PATH, 'create', 'namespace', BUILDER_NAMESPACE]
|
||||
result = subprocess.run(cmd, capture_output=True, text=True)
|
||||
|
||||
if result.returncode == 0:
|
||||
click.echo("✅ Builder namespace created")
|
||||
elif "already exists" in result.stderr:
|
||||
click.echo("✅ Builder namespace already exists")
|
||||
else:
|
||||
click.echo(f"❌ Failed to create builder namespace: {result.stderr}")
|
||||
raise click.Abort()
|
||||
|
||||
# Get AWS credentials from local AWS CLI
|
||||
aws_cmd = ['aws', 'configure', 'get', 'aws_access_key_id']
|
||||
if AWS_PROFILE:
|
||||
aws_cmd.extend(['--profile', AWS_PROFILE])
|
||||
|
||||
access_key_result = subprocess.run(aws_cmd, capture_output=True, text=True)
|
||||
if access_key_result.returncode != 0:
|
||||
click.echo("❌ Failed to get AWS access key from local AWS CLI")
|
||||
click.echo(" Please ensure AWS CLI is configured with 'aws configure'")
|
||||
raise click.Abort()
|
||||
|
||||
aws_cmd = ['aws', 'configure', 'get', 'aws_secret_access_key']
|
||||
if AWS_PROFILE:
|
||||
aws_cmd.extend(['--profile', AWS_PROFILE])
|
||||
|
||||
secret_key_result = subprocess.run(aws_cmd, capture_output=True, text=True)
|
||||
if secret_key_result.returncode != 0:
|
||||
click.echo("❌ Failed to get AWS secret key from local AWS CLI")
|
||||
click.echo(" Please ensure AWS CLI is configured with 'aws configure'")
|
||||
raise click.Abort()
|
||||
|
||||
access_key = access_key_result.stdout.strip()
|
||||
secret_key = secret_key_result.stdout.strip()
|
||||
|
||||
if not access_key or not secret_key:
|
||||
click.echo("❌ AWS credentials are empty")
|
||||
click.echo(" Please ensure AWS CLI is configured with 'aws configure'")
|
||||
raise click.Abort()
|
||||
|
||||
# Delete existing secret if it exists
|
||||
delete_cmd = ['kubectl', '--kubeconfig', KUBECONFIG_PATH, 'delete', 'secret', 'aws-credentials', '-n', BUILDER_NAMESPACE]
|
||||
subprocess.run(delete_cmd, capture_output=True, text=True) # Ignore errors
|
||||
|
||||
# Create aws-credentials secret in builder namespace
|
||||
secret_cmd = [
|
||||
'kubectl', '--kubeconfig', KUBECONFIG_PATH, 'create', 'secret', 'generic', 'aws-credentials',
|
||||
f'--from-literal=access-key={access_key}',
|
||||
f'--from-literal=secret-key={secret_key}',
|
||||
'--namespace', BUILDER_NAMESPACE
|
||||
]
|
||||
|
||||
result = subprocess.run(secret_cmd, capture_output=True, text=True)
|
||||
if result.returncode == 0:
|
||||
click.echo("✅ AWS credentials secret created in builder namespace")
|
||||
else:
|
||||
click.echo(f"❌ Failed to create AWS credentials secret: {result.stderr}")
|
||||
raise click.Abort()
|
||||
|
||||
click.echo("🎉 Builder namespace setup complete!")
|
||||
click.echo(" • Builder namespace created")
|
||||
click.echo(" • AWS credentials secret created from local AWS CLI")
|
||||
|
||||
except FileNotFoundError:
|
||||
click.echo("❌ kubectl or aws CLI not found. Please install them first.")
|
||||
raise click.Abort()
|
||||
except Exception as e:
|
||||
click.echo(f"❌ Error setting up builder namespace: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.option('--name', help='Name for the test image (defaults to configured repository)')
|
||||
@click.option('--namespace', default='default', help='Kubernetes namespace for build context')
|
||||
@click.option('--template', default='test', help='Docker template to use (test or python-agent)')
|
||||
def test_build(name, namespace, template):
|
||||
"""Test image build and push with streaming progress."""
|
||||
try:
|
||||
from .backend.models.image import Image
|
||||
from .backend.event import EventStatus
|
||||
|
||||
from jockey.environment import IMAGE_REGISTRY, IMAGE_REPOSITORY
|
||||
|
||||
# Use default repository if no name provided
|
||||
image_name = name or IMAGE_REPOSITORY
|
||||
|
||||
click.echo("🔨 Testing image build and push:")
|
||||
click.echo(f" Name: {image_name}")
|
||||
click.echo(f" Namespace: {namespace}")
|
||||
click.echo(f" Template: {template}")
|
||||
click.echo(" Builder: Kaniko in-cluster")
|
||||
click.echo(f" Registry: {IMAGE_REGISTRY}")
|
||||
click.echo()
|
||||
|
||||
image = Image(
|
||||
name=image_name,
|
||||
tag='test',
|
||||
namespace=namespace,
|
||||
dockerfile_template=template,
|
||||
)
|
||||
|
||||
click.echo("🔨 Building and pushing image...")
|
||||
for event in image.build():
|
||||
if event.status == EventStatus.STARTED:
|
||||
click.echo(f" Started building {image.image_name}")
|
||||
elif event.status == EventStatus.PROGRESS and event.message:
|
||||
# Show build steps but filter out excessive output
|
||||
message = event.message.strip()
|
||||
if message and not message.startswith(' ---'):
|
||||
click.echo(f" {message}")
|
||||
elif event.status == EventStatus.COMPLETED:
|
||||
click.echo(f"✅ Build completed: {image.image_name}")
|
||||
click.echo(f"✅ Image pushed to registry: {image.url}")
|
||||
click.echo("💡 Image available for deployments in cluster!")
|
||||
return
|
||||
elif event.status == EventStatus.ERROR:
|
||||
click.echo(f"❌ Build failed: {event.message}")
|
||||
raise click.Abort()
|
||||
|
||||
except Exception as e:
|
||||
click.echo(f"❌ Error during build test: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.option('--namespace', default=BUILDER_NAMESPACE, help=f'Kubernetes namespace (defaults to {BUILDER_NAMESPACE})')
|
||||
@click.option('--follow', '-f', is_flag=True, help='Follow/stream logs in real-time')
|
||||
def logs_builder(namespace, follow):
|
||||
"""Show logs from the most recent builder pod."""
|
||||
try:
|
||||
# Search only in the builder namespace (or specified namespace)
|
||||
pods = Pod.filter(namespace=namespace, label_selector="job-name")
|
||||
builder_pods = [p for p in pods if p.name.startswith('builder-')]
|
||||
|
||||
if not builder_pods:
|
||||
click.echo(f"No builder pods found in namespace '{namespace}'.")
|
||||
return
|
||||
|
||||
# Sort by creation time (most recent first)
|
||||
builder_pods.sort(key=lambda p: p.creation_timestamp or "", reverse=True)
|
||||
latest_builder = builder_pods[0]
|
||||
|
||||
click.echo(f"📋 Showing logs for builder pod: {latest_builder.name}")
|
||||
click.echo(f" Namespace: {latest_builder.namespace}")
|
||||
click.echo(f" Phase: {latest_builder.phase}")
|
||||
click.echo(f" Created: {latest_builder.creation_timestamp}")
|
||||
click.echo()
|
||||
|
||||
# Use kubectl to follow logs
|
||||
import subprocess
|
||||
from .environment import KUBECONFIG_PATH
|
||||
|
||||
cmd = ['kubectl', '--kubeconfig', KUBECONFIG_PATH, 'logs', latest_builder.name, '-n', latest_builder.namespace]
|
||||
|
||||
if follow:
|
||||
cmd.append('--follow')
|
||||
|
||||
# Stream logs directly to terminal
|
||||
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
||||
|
||||
try:
|
||||
for line in process.stdout:
|
||||
click.echo(line.rstrip())
|
||||
except KeyboardInterrupt:
|
||||
process.terminate()
|
||||
click.echo("\n🛑 Log streaming stopped.")
|
||||
|
||||
process.wait()
|
||||
|
||||
except Exception as e:
|
||||
click.echo(f"❌ Error getting builder logs: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.option('--name', help='Name for the test application (defaults to configured repository)')
|
||||
@click.option('--namespace', default='default', help='Kubernetes namespace')
|
||||
@click.option('--template', default='test', help='Docker template to use (test, simple-api, or python-agent)')
|
||||
def deploy_test(name, namespace, template):
|
||||
"""Deploy a minimal test application with health checks."""
|
||||
from jockey.environment import IMAGE_REGISTRY, IMAGE_REPOSITORY
|
||||
|
||||
# Use default repository if no name provided
|
||||
click.echo(f"🚀 Starting test deployment: {name or IMAGE_REPOSITORY}")
|
||||
click.echo(f" Namespace: {namespace}")
|
||||
click.echo(f" Template: {template}")
|
||||
click.echo(f" Registry: {IMAGE_REGISTRY}")
|
||||
click.echo()
|
||||
|
||||
# Create deployment config without repository
|
||||
config = DeploymentConfig(
|
||||
namespace=namespace,
|
||||
tag='test',
|
||||
dockerfile_template=template,
|
||||
ports=[8080], # Simple API runs on port 8080
|
||||
)
|
||||
|
||||
# Deploy with progress events and capture the return value
|
||||
generator = execute_serve(config)
|
||||
deployment = None
|
||||
|
||||
try:
|
||||
for event in generator:
|
||||
if hasattr(event, 'event_type'):
|
||||
if event.event_type == 'build':
|
||||
if event.status == EventStatus.STARTED:
|
||||
click.echo("🔨 Building Docker image...")
|
||||
elif event.status == EventStatus.PROGRESS and event.message:
|
||||
click.echo(f" {event.message.strip()}")
|
||||
elif event.status == EventStatus.COMPLETED:
|
||||
click.echo(f"✅ Build completed: {name or IMAGE_REPOSITORY}:test")
|
||||
elif event.status == EventStatus.ERROR:
|
||||
click.echo(f"❌ Build failed: {event.message}")
|
||||
raise click.Abort()
|
||||
|
||||
elif event.event_type == 'push':
|
||||
if event.status == EventStatus.STARTED:
|
||||
click.echo("📤 Pushing to registry...")
|
||||
elif event.status == EventStatus.PROGRESS and event.message:
|
||||
# Only show important push messages
|
||||
if 'digest:' in event.message or 'Pushed' in event.message:
|
||||
click.echo(f" {event.message}")
|
||||
elif event.status == EventStatus.COMPLETED:
|
||||
click.echo(f"✅ Push completed: {event.image_url}")
|
||||
elif event.status == EventStatus.ERROR:
|
||||
click.echo(f"❌ Push failed: {event.message}")
|
||||
raise click.Abort()
|
||||
|
||||
elif event.event_type == 'deployment':
|
||||
if event.status == EventStatus.STARTED:
|
||||
click.echo("🚀 Deploying to Kubernetes...")
|
||||
elif event.status == EventStatus.PROGRESS:
|
||||
click.echo(f" {event.message}")
|
||||
elif event.status == EventStatus.COMPLETED:
|
||||
click.echo(f"✅ Deployment ready: {event.message}")
|
||||
elif event.status == EventStatus.ERROR:
|
||||
click.echo(f"❌ Deployment failed: {event.message}")
|
||||
raise click.Abort()
|
||||
except StopIteration as e:
|
||||
# Capture the return value from the generator
|
||||
deployment = e.value
|
||||
|
||||
if deployment:
|
||||
click.echo("\n🎉 Test deployment successful!")
|
||||
click.echo(f" Name: {deployment.name}")
|
||||
click.echo(f" Image: {deployment.image_url}")
|
||||
click.echo(f" Namespace: {deployment.namespace}")
|
||||
click.echo("\n💡 Use 'jockey list-instances' to check status")
|
||||
else:
|
||||
click.echo("⚠️ Deployment completed but no final deployment object returned")
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.option('--namespace', default='default', help='Kubernetes namespace to search')
|
||||
def list_alb_ingresses(namespace):
|
||||
"""List all ingresses using the shared ALB."""
|
||||
try:
|
||||
from .backend.models.service import Ingress
|
||||
|
||||
click.echo(f"🔍 Searching for ingresses using shared ALB: {ALB_SHARED_GROUP_NAME}")
|
||||
click.echo(f" Namespace: {namespace}")
|
||||
click.echo()
|
||||
|
||||
ingresses = Ingress.filter(namespace=namespace)
|
||||
shared_alb_ingresses = []
|
||||
|
||||
for ingress in ingresses:
|
||||
annotations = ingress.data.metadata.annotations or {}
|
||||
group_name = annotations.get('alb.ingress.kubernetes.io/group.name', '')
|
||||
if group_name == ALB_SHARED_GROUP_NAME:
|
||||
shared_alb_ingresses.append(ingress)
|
||||
|
||||
if not shared_alb_ingresses:
|
||||
click.echo(f"No ingresses found using shared ALB group: {ALB_SHARED_GROUP_NAME}")
|
||||
return
|
||||
|
||||
click.echo(f"Found {len(shared_alb_ingresses)} ingress(es) using shared ALB:")
|
||||
click.echo()
|
||||
|
||||
for ingress in shared_alb_ingresses:
|
||||
annotations = ingress.data.metadata.annotations or {}
|
||||
hostname = ingress.hostname or "N/A"
|
||||
alb_hostname = ingress.load_balancer_hostname or "Pending"
|
||||
tags = annotations.get('alb.ingress.kubernetes.io/tags', 'N/A')
|
||||
|
||||
click.echo(f"📋 {ingress.name}")
|
||||
click.echo(f" Hostname: {hostname}")
|
||||
click.echo(f" ALB Hostname: {alb_hostname}")
|
||||
click.echo(f" Tags: {tags}")
|
||||
click.echo(f" Namespace: {ingress.namespace}")
|
||||
click.echo()
|
||||
|
||||
except Exception as e:
|
||||
click.echo(f"❌ Error listing ALB ingresses: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
@cli.command()
|
||||
def alb_status():
|
||||
"""Check the status of the shared ALB configuration."""
|
||||
try:
|
||||
from .backend.models.service import Ingress
|
||||
|
||||
click.echo(f"🔍 Checking shared ALB status: {ALB_SHARED_GROUP_NAME}")
|
||||
click.echo()
|
||||
|
||||
# Get all ingresses across all namespaces
|
||||
all_ingresses = []
|
||||
namespaces = ['default', 'kube-system', 'agentops-deploy'] # Common namespaces
|
||||
|
||||
for namespace in namespaces:
|
||||
try:
|
||||
ingresses = Ingress.filter(namespace=namespace)
|
||||
all_ingresses.extend(ingresses)
|
||||
except:
|
||||
continue # Skip if namespace doesn't exist or no access
|
||||
|
||||
shared_alb_ingresses = []
|
||||
for ingress in all_ingresses:
|
||||
annotations = ingress.data.metadata.annotations or {}
|
||||
group_name = annotations.get('alb.ingress.kubernetes.io/group.name', '')
|
||||
if group_name == ALB_SHARED_GROUP_NAME:
|
||||
shared_alb_ingresses.append(ingress)
|
||||
|
||||
if not shared_alb_ingresses:
|
||||
click.echo(f"⚠️ No ingresses found using shared ALB group: {ALB_SHARED_GROUP_NAME}")
|
||||
click.echo(" This means the shared ALB is not yet provisioned.")
|
||||
return
|
||||
|
||||
# Check ALB status
|
||||
alb_hostnames = set()
|
||||
ready_count = 0
|
||||
|
||||
for ingress in shared_alb_ingresses:
|
||||
alb_hostname = ingress.load_balancer_hostname
|
||||
if alb_hostname:
|
||||
alb_hostnames.add(alb_hostname)
|
||||
ready_count += 1
|
||||
|
||||
click.echo(f"✅ Shared ALB Status:")
|
||||
click.echo(f" Group Name: {ALB_SHARED_GROUP_NAME}")
|
||||
click.echo(f" Total Ingresses: {len(shared_alb_ingresses)}")
|
||||
click.echo(f" Ready Ingresses: {ready_count}")
|
||||
click.echo(f" ALB Hostnames: {len(alb_hostnames)}")
|
||||
|
||||
if alb_hostnames:
|
||||
click.echo(" ALB Endpoints:")
|
||||
for hostname in alb_hostnames:
|
||||
click.echo(f" - {hostname}")
|
||||
|
||||
# Show ingresses by namespace
|
||||
namespace_counts = {}
|
||||
for ingress in shared_alb_ingresses:
|
||||
ns = ingress.namespace
|
||||
namespace_counts[ns] = namespace_counts.get(ns, 0) + 1
|
||||
|
||||
click.echo(" Ingresses by namespace:")
|
||||
for ns, count in namespace_counts.items():
|
||||
click.echo(f" - {ns}: {count}")
|
||||
|
||||
except Exception as e:
|
||||
click.echo(f"❌ Error checking ALB status: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.option('--namespace', default='default', help='Kubernetes namespace')
|
||||
@click.argument('hostname')
|
||||
def validate_alb_routing(namespace, hostname):
|
||||
"""Validate that ALB routing is configured correctly for a hostname."""
|
||||
try:
|
||||
from .backend.models.service import Ingress
|
||||
|
||||
click.echo(f"🔍 Validating ALB routing for hostname: {hostname}")
|
||||
click.echo(f" Namespace: {namespace}")
|
||||
click.echo(f" Shared ALB Group: {ALB_SHARED_GROUP_NAME}")
|
||||
click.echo()
|
||||
|
||||
ingresses = Ingress.filter(namespace=namespace)
|
||||
matching_ingresses = []
|
||||
|
||||
for ingress in ingresses:
|
||||
if ingress.hostname == hostname:
|
||||
matching_ingresses.append(ingress)
|
||||
|
||||
if not matching_ingresses:
|
||||
click.echo(f"❌ No ingresses found for hostname: {hostname}")
|
||||
return
|
||||
|
||||
ingress = matching_ingresses[0]
|
||||
annotations = ingress.data.metadata.annotations or {}
|
||||
|
||||
# Check ALB configuration
|
||||
group_name = annotations.get('alb.ingress.kubernetes.io/group.name', '')
|
||||
scheme = annotations.get('alb.ingress.kubernetes.io/scheme', '')
|
||||
target_type = annotations.get('alb.ingress.kubernetes.io/target-type', '')
|
||||
tags = annotations.get('alb.ingress.kubernetes.io/tags', '')
|
||||
|
||||
click.echo(f"✅ Ingress Configuration:")
|
||||
click.echo(f" Name: {ingress.name}")
|
||||
click.echo(f" Hostname: {ingress.hostname}")
|
||||
click.echo(f" ALB Group: {group_name}")
|
||||
click.echo(f" Scheme: {scheme}")
|
||||
click.echo(f" Target Type: {target_type}")
|
||||
click.echo(f" Tags: {tags}")
|
||||
click.echo(f" ALB Hostname: {ingress.load_balancer_hostname or 'Pending'}")
|
||||
|
||||
# Validation checks
|
||||
issues = []
|
||||
if group_name != ALB_SHARED_GROUP_NAME:
|
||||
issues.append(f"Group name mismatch: expected {ALB_SHARED_GROUP_NAME}, got {group_name}")
|
||||
if scheme != 'internet-facing':
|
||||
issues.append(f"Scheme should be 'internet-facing', got '{scheme}'")
|
||||
if target_type != 'ip':
|
||||
issues.append(f"Target type should be 'ip', got '{target_type}'")
|
||||
if not tags:
|
||||
issues.append("No ALB tags configured")
|
||||
|
||||
if issues:
|
||||
click.echo()
|
||||
click.echo("⚠️ Configuration Issues:")
|
||||
for issue in issues:
|
||||
click.echo(f" - {issue}")
|
||||
else:
|
||||
click.echo()
|
||||
click.echo("✅ All validations passed!")
|
||||
|
||||
except Exception as e:
|
||||
click.echo(f"❌ Error validating ALB routing: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
cli()
|
||||
@@ -0,0 +1,5 @@
|
||||
from .main import app
|
||||
|
||||
__all__ = [
|
||||
"app",
|
||||
]
|
||||
@@ -0,0 +1,36 @@
|
||||
from fastapi import FastAPI
|
||||
from jockey import __version__
|
||||
from jockey.worker import queue
|
||||
|
||||
|
||||
app = FastAPI(title="Internal Deployment Status API", version=__version__)
|
||||
|
||||
|
||||
@app.get("/queue/status")
|
||||
async def get_queue_status():
|
||||
"""Get deployment queue status."""
|
||||
try:
|
||||
# Get queue length
|
||||
queue_length = queue.get_queue_length()
|
||||
processing_count = queue.get_processing_count()
|
||||
|
||||
return {
|
||||
"queue_length": queue_length,
|
||||
"processing_count": processing_count,
|
||||
"status": "active" if queue_length > 0 or processing_count > 0 else "idle",
|
||||
}
|
||||
except Exception as e:
|
||||
return {"error": str(e)}
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
"""Health check endpoint."""
|
||||
try:
|
||||
# Test Redis connection
|
||||
if queue.health_check():
|
||||
return {"status": "healthy", "redis": "connected"}
|
||||
else:
|
||||
return {"status": "unhealthy", "redis": "disconnected"}
|
||||
except Exception as e:
|
||||
return {"status": "unhealthy", "redis": "disconnected", "error": str(e)}
|
||||
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Startup script for the Jockey Deployment API."""
|
||||
|
||||
import uvicorn
|
||||
import os
|
||||
|
||||
|
||||
def main():
|
||||
"""Run the API server."""
|
||||
try:
|
||||
from jockey.api.main import app
|
||||
|
||||
host = os.getenv("API_HOST", "0.0.0.0")
|
||||
port = int(os.getenv("API_PORT", "8000"))
|
||||
reload = os.getenv("API_RELOAD", "true").lower() == "true"
|
||||
|
||||
print(f"Starting Jockey Deployment API on {host}:{port}")
|
||||
print(f"Redis host: {os.getenv('DEPLOY_REDIS_HOST', 'localhost')}")
|
||||
print(f"Redis port: {os.getenv('DEPLOY_REDIS_PORT', '6379')}")
|
||||
|
||||
if reload:
|
||||
# Use import string for reload mode
|
||||
uvicorn.run("jockey.api.main:app", host=host, port=port, reload=reload)
|
||||
else:
|
||||
uvicorn.run(app, host=host, port=port, reload=reload)
|
||||
|
||||
except ImportError as e:
|
||||
print(f"Import error: {e}")
|
||||
print("Make sure you're running this from the correct directory")
|
||||
return 1
|
||||
except Exception as e:
|
||||
print(f"Error starting API: {e}")
|
||||
return 1
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
exit(main())
|
||||
@@ -0,0 +1,73 @@
|
||||
from pathlib import Path
|
||||
from .client import get_client
|
||||
from .models.base import BaseModel
|
||||
from .models.configmap import ConfigMap
|
||||
from .models.deployment import Deployment
|
||||
from .models.job import Job
|
||||
from .models.pod import Pod
|
||||
from .models.secret import Secret
|
||||
from .models.service import Service
|
||||
from jockey.environment import WORKING_DIRECTORY
|
||||
|
||||
__all__ = [
|
||||
"get_client",
|
||||
"BaseModel",
|
||||
"ConfigMap",
|
||||
"Deployment",
|
||||
"Job",
|
||||
"Pod",
|
||||
"Secret",
|
||||
"Service",
|
||||
]
|
||||
|
||||
|
||||
def get_namespace_directory(namespace: str) -> Path:
|
||||
"""Get the working directory for a specific namespace.
|
||||
|
||||
Args:
|
||||
namespace: The namespace name
|
||||
|
||||
Returns:
|
||||
Path: Absolute path to the namespace directory
|
||||
"""
|
||||
return Path(WORKING_DIRECTORY) / namespace
|
||||
|
||||
|
||||
def get_repository_path(namespace: str, repository_name: str) -> Path:
|
||||
"""Get the full path to a cloned repository.
|
||||
|
||||
Args:
|
||||
namespace: The namespace name
|
||||
repository_name: The repository directory name
|
||||
|
||||
Returns:
|
||||
Path: Absolute path to the repository directory
|
||||
"""
|
||||
return get_namespace_directory(namespace) / repository_name
|
||||
|
||||
|
||||
def ensure_namespace_directory(namespace: str) -> Path:
|
||||
"""Ensure the namespace directory exists and return its path.
|
||||
|
||||
Args:
|
||||
namespace: The namespace name
|
||||
|
||||
Returns:
|
||||
Path: Absolute path to the namespace directory
|
||||
"""
|
||||
namespace_dir = get_namespace_directory(namespace)
|
||||
namespace_dir.mkdir(parents=True, exist_ok=True)
|
||||
return namespace_dir
|
||||
|
||||
|
||||
def cleanup_namespace_directory(namespace: str) -> None:
|
||||
"""Clean up all files in the namespace directory.
|
||||
|
||||
Args:
|
||||
namespace: The namespace name
|
||||
"""
|
||||
import shutil
|
||||
|
||||
namespace_dir = get_namespace_directory(namespace)
|
||||
if namespace_dir.exists():
|
||||
shutil.rmtree(namespace_dir)
|
||||
@@ -0,0 +1,71 @@
|
||||
from typing import Optional
|
||||
from kubernetes import client, config # type: ignore
|
||||
from ..environment import KUBECONFIG_PATH, KUBERNETES_CONTEXT
|
||||
|
||||
|
||||
_client_instance: Optional["Client"] = None
|
||||
|
||||
|
||||
def get_client() -> "Client":
|
||||
"""Get the singleton client instance, creating it if necessary."""
|
||||
global _client_instance
|
||||
|
||||
if _client_instance is None:
|
||||
_client_instance = Client()
|
||||
return _client_instance
|
||||
|
||||
|
||||
class Client:
|
||||
"""Kubernetes client wrapper with configuration management."""
|
||||
|
||||
_core: Optional[client.CoreV1Api] = None
|
||||
_apps: Optional[client.AppsV1Api] = None
|
||||
_networking: Optional[client.NetworkingV1Api] = None
|
||||
_autoscaling: Optional[client.AutoscalingV1Api] = None
|
||||
_batch: Optional[client.BatchV1Api] = None
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Initialize Kubernetes client with configuration."""
|
||||
|
||||
try:
|
||||
config.load_kube_config(
|
||||
config_file=KUBECONFIG_PATH,
|
||||
context=KUBERNETES_CONTEXT,
|
||||
)
|
||||
except config.ConfigException as e:
|
||||
raise RuntimeError(f"Failed to configure Kubernetes client: {e}") from e
|
||||
|
||||
@property
|
||||
def core(self) -> client.CoreV1Api:
|
||||
"""Get CoreV1Api client for core resources (pods, services, etc.)."""
|
||||
if self._core is None:
|
||||
self._core = client.CoreV1Api()
|
||||
return self._core
|
||||
|
||||
@property
|
||||
def apps(self) -> client.AppsV1Api:
|
||||
"""Get AppsV1Api client for application resources (deployments, etc.)."""
|
||||
if self._apps is None:
|
||||
self._apps = client.AppsV1Api()
|
||||
return self._apps
|
||||
|
||||
@property
|
||||
def networking(self) -> client.NetworkingV1Api:
|
||||
"""Get NetworkingV1Api client for networking resources (ingress, etc.)."""
|
||||
if self._networking is None:
|
||||
self._networking = client.NetworkingV1Api()
|
||||
return self._networking
|
||||
|
||||
@property
|
||||
def autoscaling(self) -> client.AutoscalingV1Api:
|
||||
"""Get AutoscalingV1Api client for autoscaling resources (HPA, etc.)."""
|
||||
if self._autoscaling is None:
|
||||
self._autoscaling = client.AutoscalingV1Api()
|
||||
return self._autoscaling
|
||||
|
||||
@property
|
||||
def batch(self) -> client.BatchV1Api:
|
||||
"""Get BatchV1Api client for batch resources (jobs, etc.)."""
|
||||
if self._batch is None:
|
||||
self._batch = client.BatchV1Api()
|
||||
return self._batch
|
||||
@@ -0,0 +1,155 @@
|
||||
from __future__ import annotations
|
||||
from typing import Optional, Any, ClassVar, TypedDict, Type
|
||||
from abc import ABC, abstractmethod
|
||||
from enum import Enum
|
||||
from datetime import datetime, UTC
|
||||
|
||||
|
||||
_registry: dict[str, Type['BaseEvent']] = {}
|
||||
|
||||
|
||||
class SerializedEvent(TypedDict):
|
||||
"""Type definition for serialized event data."""
|
||||
|
||||
event_type: str
|
||||
status: str
|
||||
timestamp: str
|
||||
message: str
|
||||
payload: dict[str, Any] # The original payload dict from the event
|
||||
kwargs: dict[str, Any] # Class attributes that were set on the event instance
|
||||
|
||||
|
||||
class EventStatus(Enum):
|
||||
STARTED = "started"
|
||||
PROGRESS = "progress"
|
||||
WAITING = "waiting"
|
||||
COMPLETED = "completed"
|
||||
ERROR = "error"
|
||||
TIMEOUT = "timeout"
|
||||
|
||||
|
||||
class BaseEvent(ABC):
|
||||
"""Abstract base event class for all operations.
|
||||
|
||||
Provides consistent status and message handling across all operation types.
|
||||
Subclasses must define an 'event_type' class variable and can add operation-specific fields.
|
||||
|
||||
The message field is used for all communication - both success and error states.
|
||||
When status is ERROR, the message contains the error description.
|
||||
|
||||
The payload field can contain structured data relevant to the operation.
|
||||
The exception field can contain an exception instance for error events.
|
||||
The event_type class variable identifies the specific event type for easy string matching.
|
||||
"""
|
||||
|
||||
event_type: ClassVar[str] # Must be defined in subclasses
|
||||
|
||||
status: EventStatus
|
||||
timestamp: datetime
|
||||
payload: dict[str, Any]
|
||||
exception: Optional[Exception]
|
||||
_message: Optional[str] # Pre-computed message
|
||||
|
||||
def __init__(self, status: EventStatus, /, **kwargs) -> None:
|
||||
"""Initialize with status as positional argument and any additional fields.
|
||||
|
||||
Args:
|
||||
status: The event status (positional-only)
|
||||
**kwargs: Additional fields to set as attributes including optional 'message'
|
||||
"""
|
||||
self.status = status
|
||||
|
||||
if 'timestamp' in kwargs:
|
||||
self.timestamp = datetime.fromisoformat(kwargs.pop('timestamp')).astimezone(UTC)
|
||||
else:
|
||||
self.timestamp = datetime.now(UTC)
|
||||
|
||||
self.payload = kwargs.pop('payload', {})
|
||||
self.exception = kwargs.pop('exception', None)
|
||||
self._message = kwargs.pop('message', None) # Store pre-computed message if provided
|
||||
|
||||
# Set any additional fields from kwargs
|
||||
for key, value in kwargs.items():
|
||||
setattr(self, key, value)
|
||||
|
||||
@abstractmethod
|
||||
def format_message(self) -> str:
|
||||
"""Generate a human-readable message based on the event's status and attributes.
|
||||
|
||||
This method must be implemented by all subclasses to provide context-specific
|
||||
messages that are generated dynamically from the event's state.
|
||||
"""
|
||||
pass
|
||||
|
||||
@property
|
||||
def message(self) -> str:
|
||||
"""Get the event message, using stored message if available, otherwise format dynamically."""
|
||||
if self._message is not None:
|
||||
return self._message
|
||||
return self.format_message()
|
||||
|
||||
def serialize(self) -> SerializedEvent:
|
||||
"""Serialize the event to a dictionary for storage or transmission.
|
||||
|
||||
Returns:
|
||||
SerializedEvent
|
||||
"""
|
||||
kwargs = {}
|
||||
for key, value in self.__dict__.items():
|
||||
if key not in ["status", "payload", "exception", "_message"] and not key.startswith('_'):
|
||||
if isinstance(value, (str, int, float, bool, list, dict, type(None))):
|
||||
kwargs[key] = value # type: ignore
|
||||
elif hasattr(value, 'value'): # Handle enums
|
||||
kwargs[key] = value.value # type: ignore
|
||||
else:
|
||||
kwargs[key] = str(value)
|
||||
|
||||
return SerializedEvent(
|
||||
event_type=self.event_type,
|
||||
status=self.status.value,
|
||||
timestamp=self.timestamp.isoformat(),
|
||||
message=self.message,
|
||||
payload=self.payload,
|
||||
kwargs=kwargs,
|
||||
)
|
||||
|
||||
|
||||
def register_event(event_class: Type['BaseEvent']) -> None:
|
||||
"""Register an event class in the global event registry.
|
||||
|
||||
Args:
|
||||
event_class: The event class to register
|
||||
"""
|
||||
global _registry
|
||||
|
||||
_registry[event_class.event_type] = event_class
|
||||
|
||||
|
||||
def deserialize_event(serialized: SerializedEvent) -> Optional[BaseEvent]:
|
||||
"""Deserialize a serialized event back to a BaseEvent object.
|
||||
|
||||
Args:
|
||||
serialized: The serialized event data
|
||||
|
||||
Returns:
|
||||
BaseEvent instance of the appropriate type, or None if unknown event type
|
||||
"""
|
||||
global _registry
|
||||
|
||||
event_type = serialized["event_type"]
|
||||
event_class = _registry.get(event_type)
|
||||
|
||||
if not event_class:
|
||||
# TODO we could be nicer
|
||||
raise ValueError(f"Unknown event type: {event_type}")
|
||||
|
||||
# The `kwargs` contain the class attributes from event subclasses
|
||||
# The `payload` contains the original payload dict
|
||||
# Pass the pre-computed `message` to preserve exact error details
|
||||
# TODO we do not re-instantiate the `exception` here and rely on the precomputed message
|
||||
return event_class(
|
||||
EventStatus(serialized["status"]),
|
||||
message=serialized["message"],
|
||||
payload=serialized["payload"],
|
||||
**serialized["kwargs"],
|
||||
)
|
||||
@@ -0,0 +1,80 @@
|
||||
from typing import Any, Optional, TypeVar
|
||||
from abc import abstractmethod
|
||||
from dataclasses import dataclass
|
||||
|
||||
from jockey.backend import get_client
|
||||
|
||||
|
||||
class classproperty:
|
||||
"""Descriptor for class properties."""
|
||||
|
||||
def __init__(self, func):
|
||||
self.func = func
|
||||
|
||||
def __get__(self, instance, owner):
|
||||
return self.func(owner)
|
||||
|
||||
|
||||
T = TypeVar('T', bound='BaseModel')
|
||||
|
||||
|
||||
class BaseModel:
|
||||
"""Base model for Kubernetes resources.
|
||||
|
||||
Supports both configuration-based models (ConfigMap, Secret, etc.)
|
||||
and data-wrapper models (Pod, Service from existing k8s objects).
|
||||
"""
|
||||
|
||||
@classproperty
|
||||
def client(cls):
|
||||
"""Get the Kubernetes client instance."""
|
||||
return get_client()
|
||||
|
||||
@classmethod
|
||||
def get(cls: type[T], name: str, namespace: str) -> Optional[T]:
|
||||
"""Get a resource by name and namespace. Override in subclasses."""
|
||||
raise NotImplementedError(f"{cls.__name__} doesn't support get()")
|
||||
|
||||
@classmethod
|
||||
def filter(cls: type[T], namespace: str, **kwargs) -> list[T]:
|
||||
"""Filter resources in the namespace. Override in subclasses."""
|
||||
raise NotImplementedError(f"{cls.__name__} doesn't support filter()")
|
||||
|
||||
|
||||
@dataclass
|
||||
class KubernetesResourceWrapper(BaseModel):
|
||||
"""Base class for models that wrap existing Kubernetes objects."""
|
||||
|
||||
_data: Optional[Any] = None
|
||||
|
||||
def __init__(self, data: Any) -> None:
|
||||
"""Initialize model with k8s data."""
|
||||
self._data = data
|
||||
|
||||
def __repr__(self) -> str:
|
||||
"""String representation of the resource."""
|
||||
class_name = self.__class__.__name__
|
||||
return f"{class_name}(name='{self.name}', namespace='{self.namespace}')"
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
"""Get the resource name from data."""
|
||||
return str(self.data.metadata.name)
|
||||
|
||||
@property
|
||||
def namespace(self) -> str:
|
||||
"""Get the resource namespace from data."""
|
||||
return str(self.data.metadata.namespace)
|
||||
|
||||
@property
|
||||
def data(self) -> Any:
|
||||
"""Get the underlying Kubernetes object data."""
|
||||
if self._data is None:
|
||||
raise RuntimeError(f"No data loaded for {self.__class__.__name__}")
|
||||
return self._data
|
||||
|
||||
@classmethod
|
||||
@abstractmethod
|
||||
def create(cls: type[T], namespace: str, body: Any) -> T:
|
||||
"""Create a new resource."""
|
||||
...
|
||||
@@ -0,0 +1,129 @@
|
||||
from __future__ import annotations
|
||||
from typing import Optional
|
||||
from dataclasses import dataclass, field
|
||||
from kubernetes import client as k8s # type: ignore
|
||||
from kubernetes.client.rest import ApiException # type: ignore
|
||||
from .base import BaseModel
|
||||
from jockey.log import logger
|
||||
|
||||
|
||||
@dataclass
|
||||
class ConfigMapRef:
|
||||
"""Reference to a configmap key."""
|
||||
|
||||
name: str
|
||||
key: str
|
||||
|
||||
def to_env_var(self, env_name: str) -> k8s.V1EnvVar:
|
||||
"""Generate Kubernetes V1EnvVar for this configmap reference."""
|
||||
return k8s.V1EnvVar(
|
||||
name=env_name,
|
||||
value_from=k8s.V1EnvVarSource(
|
||||
config_map_key_ref=k8s.V1ConfigMapKeySelector(
|
||||
name=self.name,
|
||||
key=self.key,
|
||||
)
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ConfigMap(BaseModel):
|
||||
"""Model-style interface for Kubernetes ConfigMaps."""
|
||||
|
||||
# Configuration attributes (required)
|
||||
name: str
|
||||
namespace: str
|
||||
data: dict[str, str] = field(default_factory=dict)
|
||||
binary_data: dict[str, bytes] = field(default_factory=dict)
|
||||
labels: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
# Metadata attributes (populated from k8s data)
|
||||
uid: Optional[str] = None
|
||||
metadata: Optional[k8s.V1ObjectMeta] = None
|
||||
creation_timestamp: Optional[str] = None
|
||||
deletion_timestamp: Optional[str] = None
|
||||
|
||||
def get_value(self, key: str) -> Optional[str]:
|
||||
"""Get a specific value from the ConfigMap data."""
|
||||
return self.data.get(key)
|
||||
|
||||
def get_binary_value(self, key: str) -> Optional[bytes]:
|
||||
"""Get a specific binary value from the ConfigMap."""
|
||||
return self.binary_data.get(key)
|
||||
|
||||
def to_k8s_configmap(self) -> k8s.V1ConfigMap:
|
||||
"""Convert to Kubernetes V1ConfigMap object for API calls."""
|
||||
default_labels = {"app": self.name}
|
||||
all_labels = {**default_labels, **self.labels}
|
||||
|
||||
return k8s.V1ConfigMap(
|
||||
api_version="v1",
|
||||
kind="ConfigMap",
|
||||
metadata=k8s.V1ObjectMeta(name=self.name, namespace=self.namespace, labels=all_labels),
|
||||
data=self.data,
|
||||
binary_data=self.binary_data,
|
||||
)
|
||||
|
||||
def to_k8s_volume(self, volume_name: str) -> k8s.V1Volume:
|
||||
"""Create a Kubernetes V1Volume that mounts this ConfigMap."""
|
||||
return k8s.V1Volume(
|
||||
name=volume_name,
|
||||
config_map=k8s.V1ConfigMapVolumeSource(name=self.name),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_k8s_data(cls, data: k8s.V1ConfigMap) -> ConfigMap:
|
||||
"""Create a ConfigMap instance from Kubernetes API data."""
|
||||
return cls(
|
||||
name=data.metadata.name,
|
||||
namespace=data.metadata.namespace,
|
||||
data=data.data,
|
||||
binary_data=data.binary_data,
|
||||
labels=data.metadata.labels or {},
|
||||
uid=data.metadata.uid,
|
||||
metadata=data.metadata,
|
||||
creation_timestamp=data.metadata.creation_timestamp,
|
||||
deletion_timestamp=data.metadata.deletion_timestamp,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get(cls, name: str, namespace: str) -> Optional[ConfigMap]:
|
||||
"""Get a ConfigMap by name."""
|
||||
try:
|
||||
k8s_configmap = cls.client.core.read_namespaced_config_map(name=name, namespace=namespace)
|
||||
return cls.from_k8s_data(k8s_configmap)
|
||||
except ApiException as e:
|
||||
logger.debug(f"Get ConfigMap {name} returned empty (status {e.status})")
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def filter(cls, namespace: str, **kwargs) -> list[ConfigMap]:
|
||||
"""Filter ConfigMaps in the namespace."""
|
||||
try:
|
||||
result = cls.client.core.list_namespaced_config_map(namespace=namespace, **kwargs)
|
||||
return [cls.from_k8s_data(item) for item in result.items]
|
||||
except ApiException as e:
|
||||
logger.debug(f"Filter ConfigMaps returned empty (status {e.status})")
|
||||
return []
|
||||
|
||||
def delete(self) -> bool:
|
||||
"""Delete this ConfigMap."""
|
||||
try:
|
||||
self.client.core.delete_namespaced_config_map(name=self.name, namespace=self.namespace)
|
||||
return True
|
||||
except ApiException as e:
|
||||
logger.debug(f"Delete ConfigMap {self.name} failed (status {e.status})")
|
||||
return False
|
||||
|
||||
def create(self) -> ConfigMap:
|
||||
"""Create this ConfigMap in the cluster."""
|
||||
try:
|
||||
k8s_configmap = self.client.core.create_namespaced_config_map(
|
||||
body=self.to_k8s_configmap(),
|
||||
namespace=self.namespace,
|
||||
)
|
||||
return self.from_k8s_data(k8s_configmap)
|
||||
except ApiException as e:
|
||||
logger.debug(f"Create ConfigMap failed (status {e.status})")
|
||||
raise
|
||||
@@ -0,0 +1,664 @@
|
||||
from __future__ import annotations
|
||||
from typing import Any, Optional, Generator, ClassVar, Union
|
||||
from dataclasses import dataclass, field
|
||||
import time
|
||||
import threading
|
||||
from queue import Queue, Empty
|
||||
|
||||
from kubernetes import client as k8s, watch # type: ignore
|
||||
from kubernetes.client.rest import ApiException # type: ignore
|
||||
|
||||
from jockey.log import logger
|
||||
from jockey.environment import (
|
||||
CPU_LIMIT,
|
||||
MEMORY_LIMIT,
|
||||
CPU_REQUEST,
|
||||
MEMORY_REQUEST,
|
||||
LIVENESS_PROBE_PATH,
|
||||
READINESS_PROBE_PATH,
|
||||
)
|
||||
from jockey.backend.event import BaseEvent, EventStatus, register_event
|
||||
from .base import BaseModel
|
||||
from .configmap import ConfigMapRef
|
||||
from .secret import SecretRef
|
||||
|
||||
|
||||
DEFAULT_TIMEOUT: int = 900 # 15 minutes
|
||||
|
||||
DeploymentEventStream = Generator['DeploymentEvent', None, Optional['Deployment']]
|
||||
NativeEvent = dict[str, Any] # k8s native event data
|
||||
EventData = Union[NativeEvent, 'DeploymentEvent', Exception]
|
||||
|
||||
|
||||
def default_resources() -> k8s.V1ResourceRequirements:
|
||||
"""Create default resource requirements from environment constants."""
|
||||
return k8s.V1ResourceRequirements(
|
||||
requests={"cpu": CPU_REQUEST, "memory": MEMORY_REQUEST},
|
||||
limits={"cpu": CPU_LIMIT, "memory": MEMORY_LIMIT},
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class WatchEvent:
|
||||
"""Event from deployment or pod watchers."""
|
||||
|
||||
DEPLOYMENT: ClassVar[str] = "deployment"
|
||||
POD: ClassVar[str] = "pod"
|
||||
ERROR: ClassVar[str] = "error"
|
||||
|
||||
type: str
|
||||
data: EventData
|
||||
|
||||
|
||||
class DeploymentEvent(BaseEvent):
|
||||
"""Event for deployment operations."""
|
||||
|
||||
event_type = "deployment"
|
||||
|
||||
available_replicas: int = 0
|
||||
ready_replicas: int = 0
|
||||
desired_replicas: int = 0
|
||||
phase: Optional[str] = None
|
||||
|
||||
def format_message(self) -> str:
|
||||
"""Dynamically format the message based on event data."""
|
||||
match self.status:
|
||||
case EventStatus.STARTED:
|
||||
return "Starting deployment"
|
||||
case EventStatus.PROGRESS:
|
||||
if self.available_replicas < self.desired_replicas:
|
||||
return "Scaling deployment: %s/%s replicas available" % (
|
||||
self.available_replicas,
|
||||
self.desired_replicas,
|
||||
)
|
||||
elif self.ready_replicas < self.desired_replicas:
|
||||
return "Pods starting: %s/%s replicas ready" % (
|
||||
self.ready_replicas,
|
||||
self.desired_replicas,
|
||||
)
|
||||
else:
|
||||
return "Deployment status: %s/%s available, %s/%s ready" % (
|
||||
self.available_replicas,
|
||||
self.desired_replicas,
|
||||
self.ready_replicas,
|
||||
self.desired_replicas,
|
||||
)
|
||||
case EventStatus.COMPLETED:
|
||||
return "Deployment ready: %s/%s replicas available" % (
|
||||
self.available_replicas,
|
||||
self.desired_replicas,
|
||||
)
|
||||
case EventStatus.ERROR:
|
||||
if self.exception:
|
||||
return str(self.exception)
|
||||
return "Deployment failed"
|
||||
case EventStatus.TIMEOUT:
|
||||
return "Deployment timed out"
|
||||
case EventStatus.WAITING:
|
||||
return "Waiting for pods: 0/%s replicas available" % (self.desired_replicas,)
|
||||
case _: # fallback
|
||||
return "Deployment: %s" % (self.status.value,)
|
||||
|
||||
|
||||
register_event(DeploymentEvent)
|
||||
|
||||
|
||||
class DeployManager:
|
||||
"""Manages deployment watching and event processing.
|
||||
|
||||
The DeployManager handles the complex orchestration of watching both Kubernetes
|
||||
deployment and pod events, processing them into a unified stream of DeploymentEvents.
|
||||
|
||||
It manages:
|
||||
- Starting deployment and pod watchers in separate threads
|
||||
- Collecting events from both watchers into a unified queue
|
||||
- Processing events and translating them to DeploymentEvents
|
||||
- Tracking deployment readiness state
|
||||
- Handling timeout conditions
|
||||
|
||||
Example usage:
|
||||
```python
|
||||
# Create a deployment
|
||||
deployment = Deployment(
|
||||
name="my-app",
|
||||
image_url="my-registry/my-app:v1.0.0",
|
||||
namespace="default"
|
||||
)
|
||||
|
||||
# Create deployment manager
|
||||
manager = DeployManager(deployment, timeout=600) # 10 minute timeout
|
||||
|
||||
# Watch deployment progress
|
||||
for event in manager.watch_and_yield_events():
|
||||
print(f"Status: {event.status}, Message: {event.message}")
|
||||
if event.status == EventStatus.COMPLETED:
|
||||
print("Deployment ready!")
|
||||
break
|
||||
elif event.status == EventStatus.ERROR:
|
||||
print(f"Deployment failed: {event.exception}")
|
||||
break
|
||||
|
||||
# Access final deployment object
|
||||
if manager.final_deployment:
|
||||
final_dep = Deployment.from_k8s_data(manager.final_deployment)
|
||||
```
|
||||
"""
|
||||
|
||||
deployment: Deployment
|
||||
timeout: int
|
||||
|
||||
event_queue: Queue[WatchEvent]
|
||||
deployment_ready: bool = False
|
||||
final_deployment: Optional[k8s.V1Deployment] = None
|
||||
start_time: float
|
||||
|
||||
def __init__(self, deployment: Deployment, timeout: int = DEFAULT_TIMEOUT):
|
||||
self.deployment = deployment
|
||||
self.timeout = timeout
|
||||
self.event_queue = Queue[WatchEvent]()
|
||||
self.start_time = time.time()
|
||||
|
||||
def watch_and_yield_events(self) -> DeploymentEventStream:
|
||||
"""Start watchers and process events until deployment is ready."""
|
||||
self._start_watchers()
|
||||
|
||||
while not self.deployment_ready:
|
||||
if self._is_timed_out:
|
||||
yield DeploymentEvent(EventStatus.TIMEOUT)
|
||||
return None
|
||||
|
||||
if event := self._get_next_event():
|
||||
yield from self._process_event(event)
|
||||
|
||||
return self.deployment
|
||||
|
||||
def _start_watchers(self) -> None:
|
||||
"""Start deployment and pod watchers in separate threads."""
|
||||
# late import to avoid circular dependencies
|
||||
from .pod import Pod
|
||||
|
||||
def watch_deployment():
|
||||
"""Watch deployment events and put them in the queue."""
|
||||
try:
|
||||
w = watch.Watch()
|
||||
for event in w.stream(
|
||||
self.deployment.client.apps.list_namespaced_deployment,
|
||||
namespace=self.deployment.namespace,
|
||||
field_selector=self.deployment.deployment_selector,
|
||||
timeout_seconds=self.timeout,
|
||||
):
|
||||
self.event_queue.put(WatchEvent(WatchEvent.DEPLOYMENT, event))
|
||||
except Exception as e:
|
||||
self.event_queue.put(WatchEvent(WatchEvent.ERROR, e))
|
||||
|
||||
def watch_pods():
|
||||
"""Watch pod events and put them in the queue."""
|
||||
try:
|
||||
for pod_event in Pod.watch(
|
||||
namespace=self.deployment.namespace,
|
||||
label_selector=self.deployment.pod_selector,
|
||||
timeout=self.timeout,
|
||||
):
|
||||
self.event_queue.put(WatchEvent(WatchEvent.POD, pod_event))
|
||||
except Exception as e:
|
||||
self.event_queue.put(WatchEvent(WatchEvent.ERROR, e))
|
||||
|
||||
deployment_thread = threading.Thread(target=watch_deployment, daemon=True)
|
||||
pod_thread = threading.Thread(target=watch_pods, daemon=True)
|
||||
deployment_thread.start()
|
||||
pod_thread.start()
|
||||
|
||||
@property
|
||||
def _is_timed_out(self) -> bool:
|
||||
"""Check if we've exceeded the timeout."""
|
||||
return time.time() - self.start_time > self.timeout
|
||||
|
||||
def _get_next_event(self) -> Optional[WatchEvent]:
|
||||
"""Get the next event from the queue with a short timeout."""
|
||||
try:
|
||||
return self.event_queue.get(timeout=1)
|
||||
except Empty:
|
||||
return None
|
||||
|
||||
def _process_event(self, event: WatchEvent) -> DeploymentEventStream: # type: ignore[return]
|
||||
"""Process a single event and yield appropriate DeploymentEvents."""
|
||||
match event.type:
|
||||
case WatchEvent.ERROR:
|
||||
assert isinstance(event.data, Exception)
|
||||
yield DeploymentEvent(EventStatus.ERROR, exception=event.data)
|
||||
|
||||
case WatchEvent.POD:
|
||||
# convert `PodEvent` to `DeploymentEvent`
|
||||
yield from self._process_pod_event(event.data)
|
||||
|
||||
case WatchEvent.DEPLOYMENT:
|
||||
assert isinstance(event.data, dict)
|
||||
yield from self._process_deployment_event(event.data)
|
||||
|
||||
def _process_deployment_event(self, event_data: NativeEvent) -> DeploymentEventStream:
|
||||
"""Process a deployment event and yield appropriate DeploymentEvents."""
|
||||
phase, obj = event_data['type'], event_data['object']
|
||||
|
||||
if phase == 'DELETED':
|
||||
yield DeploymentEvent(EventStatus.COMPLETED, phase=phase)
|
||||
|
||||
spec_replicas = obj.spec.replicas or 0
|
||||
available_replicas = obj.status.available_replicas or 0
|
||||
ready_replicas = obj.status.ready_replicas or 0
|
||||
|
||||
# Check for deployment condition errors
|
||||
yield from self._check_deployment_conditions(obj)
|
||||
|
||||
if available_replicas == 0:
|
||||
event_status = EventStatus.WAITING
|
||||
elif available_replicas < spec_replicas:
|
||||
event_status = EventStatus.PROGRESS
|
||||
elif ready_replicas < spec_replicas:
|
||||
event_status = EventStatus.PROGRESS
|
||||
elif ready_replicas == spec_replicas and available_replicas == spec_replicas:
|
||||
event_status = EventStatus.COMPLETED
|
||||
else:
|
||||
event_status = EventStatus.PROGRESS
|
||||
|
||||
if event_status == EventStatus.COMPLETED:
|
||||
self.deployment_ready = True
|
||||
self.final_deployment = obj
|
||||
|
||||
yield DeploymentEvent(
|
||||
event_status,
|
||||
phase=phase,
|
||||
available_replicas=available_replicas,
|
||||
ready_replicas=ready_replicas,
|
||||
desired_replicas=spec_replicas,
|
||||
)
|
||||
|
||||
return obj # type: ignore
|
||||
|
||||
def _process_pod_event(self, pod_event) -> DeploymentEventStream:
|
||||
"""Process a pod event and convert it to deployment-level events."""
|
||||
from .pod import PodEvent
|
||||
|
||||
# Handle exception case
|
||||
if isinstance(pod_event, Exception):
|
||||
yield DeploymentEvent(EventStatus.ERROR, exception=pod_event)
|
||||
return None
|
||||
|
||||
if not isinstance(pod_event, PodEvent):
|
||||
return None
|
||||
|
||||
# Convert pod-level events to deployment-level events
|
||||
if pod_event.status == EventStatus.ERROR:
|
||||
# Pod errors indicate deployment problems - use the pod event's message
|
||||
yield DeploymentEvent(EventStatus.ERROR, exception=Exception(pod_event.message))
|
||||
elif pod_event.status == EventStatus.PROGRESS:
|
||||
# Pod progress contributes to deployment progress
|
||||
yield DeploymentEvent(EventStatus.PROGRESS, phase=pod_event.phase)
|
||||
# Note: We don't yield COMPLETED for individual pods since deployment
|
||||
# completion depends on all pods being ready, which is handled by
|
||||
# deployment events
|
||||
return None
|
||||
|
||||
def _check_deployment_conditions(self, obj: k8s.V1Deployment) -> DeploymentEventStream:
|
||||
"""Check deployment conditions for error states."""
|
||||
if obj.status.conditions:
|
||||
for condition in obj.status.conditions:
|
||||
if condition.type == "Progressing" and condition.status == "False":
|
||||
yield DeploymentEvent(
|
||||
EventStatus.ERROR,
|
||||
exception=Exception(
|
||||
f"Deployment not progressing: {condition.reason} - {condition.message}"
|
||||
),
|
||||
)
|
||||
elif condition.type == "ReplicaFailure" and condition.status == "True":
|
||||
yield DeploymentEvent(
|
||||
EventStatus.ERROR,
|
||||
exception=Exception(
|
||||
f"Replica creation failed: {condition.reason} - {condition.message}"
|
||||
),
|
||||
)
|
||||
|
||||
return obj # type: ignore
|
||||
|
||||
|
||||
@dataclass
|
||||
class Deployment(BaseModel):
|
||||
"""Model-style interface for Kubernetes deployments.
|
||||
|
||||
Can be used to create new deployments or represent existing ones.
|
||||
Create with configuration parameters, or from existing k8s data.
|
||||
|
||||
Resource Lookup Strategy:
|
||||
- Uses field selector (metadata.name) for finding specific deployment instances
|
||||
- Uses label selector (app=name) for finding pods created by this deployment
|
||||
- This creates a "group membership" relationship where multiple pods belong to one deployment
|
||||
- The deployment selector uses match_labels to claim ownership of pods with those labels
|
||||
|
||||
Missing features compared to host:
|
||||
- Image pull secrets support (host uses 'docker-credentials')
|
||||
- Deployment update/patch functionality
|
||||
- Deployment watching and status monitoring
|
||||
"""
|
||||
|
||||
# Configuration attributes (required for new deployments)
|
||||
name: str
|
||||
image_url: str # Full image URL from Image.url (e.g., 'ghcr.io/myorg/myapp:v1.0.0')
|
||||
namespace: str # Required namespace for multi-tenant isolation
|
||||
|
||||
# Optional configuration attributes (with defaults)
|
||||
replicas: int = 1
|
||||
resources: k8s.V1ResourceRequirements = field(default_factory=default_resources)
|
||||
secret_refs: list[SecretRef] = field(default_factory=list) # SecretRef
|
||||
configmap_refs: list[ConfigMapRef] = field(default_factory=list) # ConfigMapRef
|
||||
ports: list[int] = field(default_factory=list)
|
||||
enable_health_checks: bool = True # Whether to add liveness/readiness probes
|
||||
|
||||
# Metadata attributes (populated from k8s data)
|
||||
uid: Optional[str] = None
|
||||
metadata: Optional[k8s.V1ObjectMeta] = None
|
||||
labels: dict[str, str] = field(default_factory=dict)
|
||||
creation_timestamp: Optional[str] = None
|
||||
deletion_timestamp: Optional[str] = None
|
||||
|
||||
def __post_init__(self):
|
||||
"""Sanitize name for Kubernetes compatibility after initialization."""
|
||||
self.name = self.name.replace("/", "-").replace(":", "-")
|
||||
|
||||
@property
|
||||
def match_labels(self) -> dict[str, str]:
|
||||
"""Get the match labels used by this deployment's selector."""
|
||||
return {"app": self.name}
|
||||
|
||||
@property
|
||||
def deployment_selector(self) -> str:
|
||||
"""Get the field selector for watching this specific deployment."""
|
||||
return f"metadata.name={self.name}"
|
||||
|
||||
@property
|
||||
def pod_selector(self) -> str:
|
||||
"""Get the label selector for watching pods created by this deployment."""
|
||||
return f"app={self.name}"
|
||||
|
||||
def to_k8s_deployment(self) -> k8s.V1Deployment:
|
||||
"""Convert to Kubernetes V1Deployment object for API calls."""
|
||||
|
||||
env_vars = []
|
||||
for secret_ref in self.secret_refs:
|
||||
env_vars.append(secret_ref.to_env_var())
|
||||
# just use Secrets for all environment variables
|
||||
# for env_name, configmap_ref in self.configmap_refs.items():
|
||||
# env_vars.append(configmap_ref.to_env_var(env_name))
|
||||
|
||||
health_checks: dict[str, k8s.V1Probe] = {}
|
||||
if self.enable_health_checks:
|
||||
health_check_port = self.ports[0] if self.ports else 8080
|
||||
health_checks["liveness_probe"] = k8s.V1Probe(
|
||||
http_get=k8s.V1HTTPGetAction(path=LIVENESS_PROBE_PATH, port=health_check_port),
|
||||
initial_delay_seconds=30,
|
||||
period_seconds=10,
|
||||
timeout_seconds=5,
|
||||
failure_threshold=3,
|
||||
)
|
||||
health_checks["readiness_probe"] = k8s.V1Probe(
|
||||
http_get=k8s.V1HTTPGetAction(path=READINESS_PROBE_PATH, port=health_check_port),
|
||||
initial_delay_seconds=5,
|
||||
period_seconds=5,
|
||||
timeout_seconds=3,
|
||||
failure_threshold=3,
|
||||
)
|
||||
|
||||
container = k8s.V1Container(
|
||||
name=self.name,
|
||||
image=self.image_url,
|
||||
image_pull_policy="Always",
|
||||
resources=self.resources,
|
||||
env=env_vars,
|
||||
ports=[k8s.V1ContainerPort(container_port=port) for port in self.ports],
|
||||
**health_checks,
|
||||
)
|
||||
labels = {**self.match_labels, **self.labels}
|
||||
|
||||
# Add restart annotation to force rolling update
|
||||
# This ensures pods are recreated even when using the same image tag
|
||||
import datetime
|
||||
|
||||
restart_time = datetime.datetime.utcnow().isoformat() + "Z"
|
||||
annotations = {"kubectl.kubernetes.io/restartedAt": restart_time}
|
||||
|
||||
return k8s.V1Deployment(
|
||||
api_version="apps/v1",
|
||||
kind="Deployment",
|
||||
metadata=k8s.V1ObjectMeta(
|
||||
name=self.name,
|
||||
namespace=self.namespace,
|
||||
labels=labels,
|
||||
),
|
||||
spec=k8s.V1DeploymentSpec(
|
||||
replicas=self.replicas,
|
||||
selector=k8s.V1LabelSelector(match_labels=self.match_labels),
|
||||
template=k8s.V1PodTemplateSpec(
|
||||
metadata=k8s.V1ObjectMeta(labels=labels, annotations=annotations),
|
||||
spec=k8s.V1PodSpec(containers=[container]),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_k8s_data(cls, data: k8s.V1Deployment) -> Deployment:
|
||||
"""Create a Deployment instance from Kubernetes API data."""
|
||||
# Note: We only support single-container pods for simplicity
|
||||
container = data.spec.template.spec.containers[0]
|
||||
assert container, "Deployment expected to have at least one container"
|
||||
|
||||
secret_refs: list[SecretRef] = []
|
||||
configmap_refs: list[ConfigMapRef] = []
|
||||
if container and container.env:
|
||||
for env_var in container.env:
|
||||
if env_var.value_from and env_var.value_from.secret_key_ref:
|
||||
# The secret name is the Kubernetes secret name (lowercase with dashes)
|
||||
# The env_var.name is the environment variable name (uppercase with underscores)
|
||||
secret_refs.append(
|
||||
SecretRef(
|
||||
key=env_var.value_from.secret_key_ref.name, # Kubernetes secret name
|
||||
env_var_name=env_var.name, # Environment variable name
|
||||
)
|
||||
)
|
||||
elif env_var.value_from and env_var.value_from.config_map_key_ref:
|
||||
configmap_refs.append(
|
||||
ConfigMapRef(
|
||||
key=env_var.value_from.config_map_key_ref.key,
|
||||
)
|
||||
)
|
||||
|
||||
return cls(
|
||||
name=data.metadata.name,
|
||||
image_url=container.image if container else "",
|
||||
namespace=data.metadata.namespace,
|
||||
replicas=data.spec.replicas or 1,
|
||||
resources=container.resources,
|
||||
secret_refs=secret_refs,
|
||||
configmap_refs=configmap_refs,
|
||||
ports=[port.container_port for port in container.ports] if container and container.ports else [],
|
||||
# Metadata
|
||||
uid=data.metadata.uid,
|
||||
metadata=data.metadata,
|
||||
labels=data.metadata.labels or {},
|
||||
creation_timestamp=data.metadata.creation_timestamp,
|
||||
deletion_timestamp=data.metadata.deletion_timestamp,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get(cls, name: str, namespace: str) -> Optional[Deployment]:
|
||||
"""Get a deployment by name."""
|
||||
try:
|
||||
k8s_deployment = cls.client.apps.read_namespaced_deployment(name=name, namespace=namespace)
|
||||
return cls.from_k8s_data(k8s_deployment)
|
||||
except ApiException as e:
|
||||
logger.debug(f"Get deployment {name} returned empty (status {e.status})")
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def filter(cls, namespace: str, **kwargs) -> list[Deployment]:
|
||||
"""Filter deployments in the namespace."""
|
||||
try:
|
||||
result = cls.client.apps.list_namespaced_deployment(namespace=namespace, **kwargs)
|
||||
return [cls.from_k8s_data(item) for item in result.items]
|
||||
except ApiException as e:
|
||||
logger.debug(f"Filter deployments returned empty (status {e.status})")
|
||||
return []
|
||||
|
||||
def delete(self) -> bool:
|
||||
"""Delete this deployment."""
|
||||
try:
|
||||
self.client.apps.delete_namespaced_deployment(name=self.name, namespace=self.namespace)
|
||||
return True
|
||||
except ApiException as e:
|
||||
logger.debug(f"Delete deployment {self.name} failed (status {e.status})")
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def delete_by_name(cls, name: str, namespace: str) -> bool:
|
||||
"""Delete a deployment by name (for CLI usage)."""
|
||||
try:
|
||||
cls.client.apps.delete_namespaced_deployment(name=name, namespace=namespace)
|
||||
return True
|
||||
except ApiException as e:
|
||||
logger.debug(f"Delete deployment {name} failed (status {e.status})")
|
||||
return False
|
||||
|
||||
def deploy(self, timeout: int = DEFAULT_TIMEOUT) -> DeploymentEventStream:
|
||||
"""Deploy this deployment to the cluster and watch until ready.
|
||||
|
||||
Args:
|
||||
timeout: Timeout in seconds (default 15 minutes)
|
||||
|
||||
Yields:
|
||||
DeploymentEvent: Status events during deployment and watching
|
||||
|
||||
Returns:
|
||||
Deployment: The deployed Kubernetes deployment when ready
|
||||
"""
|
||||
try:
|
||||
yield DeploymentEvent(EventStatus.STARTED)
|
||||
|
||||
k8s_deployment = self.to_k8s_deployment()
|
||||
yield DeploymentEvent(EventStatus.PROGRESS)
|
||||
|
||||
self.client.apps.create_namespaced_deployment(
|
||||
body=k8s_deployment,
|
||||
namespace=self.namespace,
|
||||
)
|
||||
manager = DeployManager(self, timeout)
|
||||
yield from manager.watch_and_yield_events()
|
||||
|
||||
if manager.final_deployment:
|
||||
return self.from_k8s_data(manager.final_deployment)
|
||||
else:
|
||||
raise ApiException(f"Deployment {self.name} did not become ready within timeout")
|
||||
|
||||
except ApiException as e:
|
||||
yield DeploymentEvent(EventStatus.ERROR, exception=e)
|
||||
logger.debug(f"Deploy deployment failed (status {e.status})")
|
||||
raise
|
||||
|
||||
def deploy_sync(self, timeout: int = DEFAULT_TIMEOUT) -> "Deployment":
|
||||
"""Deploy this deployment synchronously (convenience method).
|
||||
|
||||
Args:
|
||||
timeout: Timeout in seconds (default 15 minutes)
|
||||
|
||||
Returns:
|
||||
Deployment: The deployed Kubernetes deployment when ready
|
||||
"""
|
||||
for event in self.deploy(timeout=timeout):
|
||||
if event.status == EventStatus.COMPLETED:
|
||||
return self
|
||||
|
||||
raise ApiException(f"Deployment {self.name} did not complete successfully within timeout")
|
||||
|
||||
def deploy_or_upgrade(
|
||||
self,
|
||||
timeout: int = DEFAULT_TIMEOUT,
|
||||
force_recreate: bool = False,
|
||||
) -> DeploymentEventStream:
|
||||
"""Deploy this deployment or upgrade existing one with same name.
|
||||
|
||||
This method checks if a deployment with the same name already exists:
|
||||
- If exists and force_recreate=False: Updates/patches it with new configuration (rolling update)
|
||||
- If exists and force_recreate=True: Deletes existing deployment and creates new one
|
||||
- If doesn't exist: Creates a new deployment
|
||||
|
||||
Args:
|
||||
timeout: Timeout in seconds (default 15 minutes)
|
||||
force_recreate: If True, delete existing deployment and recreate instead of patching
|
||||
|
||||
Yields:
|
||||
DeploymentEvent: Status events during deployment/upgrade and watching
|
||||
|
||||
Returns:
|
||||
Deployment: The deployed/upgraded Kubernetes deployment when ready
|
||||
"""
|
||||
try:
|
||||
existing_deployment = self.client.apps.read_namespaced_deployment(
|
||||
name=self.name,
|
||||
namespace=self.namespace,
|
||||
)
|
||||
|
||||
if force_recreate:
|
||||
yield from self._force_recreate(timeout)
|
||||
else:
|
||||
yield from self._update_existing(timeout)
|
||||
|
||||
except ApiException as e:
|
||||
if e.status == 404:
|
||||
logger.info(f"No existing deployment {self.name} found, creating new one...")
|
||||
yield from self.deploy(timeout=timeout)
|
||||
return self
|
||||
else:
|
||||
yield DeploymentEvent(EventStatus.ERROR, exception=e)
|
||||
raise
|
||||
|
||||
def _update_existing(self, timeout: int) -> DeploymentEventStream:
|
||||
"""
|
||||
Update existing deployment path: patch and watch rollout.
|
||||
|
||||
This is the preferred way to update deployments.
|
||||
"""
|
||||
logger.info(f"Found existing deployment {self.name}, updating it...")
|
||||
yield DeploymentEvent(EventStatus.PROGRESS, phase="updating")
|
||||
|
||||
logger.info(f"Updating deployment {self.name} with new image: {self.image_url}")
|
||||
self.client.apps.patch_namespaced_deployment(
|
||||
name=self.name,
|
||||
namespace=self.namespace,
|
||||
body=self.to_k8s_deployment(),
|
||||
)
|
||||
logger.info(f"Deployment {self.name} updated successfully, waiting for rollout...")
|
||||
|
||||
manager = DeployManager(self, timeout)
|
||||
yield from manager.watch_and_yield_events()
|
||||
|
||||
if manager.final_deployment:
|
||||
logger.info(f"Deployment {self.name} rollout completed successfully!")
|
||||
return self.from_k8s_data(manager.final_deployment)
|
||||
else:
|
||||
raise ApiException(f"Deployment {self.name} update did not complete within timeout")
|
||||
|
||||
def _force_recreate(self, timeout: int) -> DeploymentEventStream:
|
||||
"""
|
||||
Force recreate path: delete existing and create new.
|
||||
|
||||
In production, it is much better to patch existing deployments, but if the
|
||||
configuration changes significantly you may need to re-create the deployment.
|
||||
"""
|
||||
logger.info(f"Found existing deployment {self.name}, deleting and recreating...")
|
||||
yield DeploymentEvent(EventStatus.PROGRESS, phase="deleting")
|
||||
|
||||
self.client.apps.delete_namespaced_deployment(
|
||||
name=self.name,
|
||||
namespace=self.namespace,
|
||||
)
|
||||
logger.info(f"Deployment {self.name} deleted, waiting 15 seconds before recreating...")
|
||||
|
||||
time.sleep(15)
|
||||
logger.info(f"Creating new deployment {self.name}...")
|
||||
yield from self.deploy(timeout=timeout)
|
||||
@@ -0,0 +1,439 @@
|
||||
from __future__ import annotations
|
||||
from typing import Optional, Generator
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from kubernetes import client as k8s, watch # type: ignore
|
||||
from kubernetes.client.rest import ApiException # type: ignore
|
||||
|
||||
from jockey.environment import (
|
||||
IMAGE_REGISTRY,
|
||||
IMAGE_REPOSITORY,
|
||||
AWS_DEFAULT_REGION,
|
||||
BUILDER_CPU_LIMIT,
|
||||
BUILDER_MEMORY_LIMIT,
|
||||
BUILDER_CPU_REQUEST,
|
||||
BUILDER_MEMORY_REQUEST,
|
||||
S3_BUCKET_NAME,
|
||||
S3_BUILD_CACHE_PREFIX,
|
||||
)
|
||||
import boto3
|
||||
from jockey.log import logger
|
||||
from jockey.template import render_template
|
||||
from jockey.backend.event import BaseEvent, EventStatus, register_event
|
||||
from .base import BaseModel
|
||||
from .configmap import ConfigMap
|
||||
import hashlib
|
||||
|
||||
|
||||
BUILDER_IMAGE = 'gcr.io/kaniko-project/executor:latest'
|
||||
CLEANUP_DELAY_SECONDS = 300 # Time to keep completed jobs before cleanup
|
||||
|
||||
BuildEventStream = Generator['BuildEvent', None, str]
|
||||
|
||||
|
||||
class BuildEvent(BaseEvent):
|
||||
"""Log event for Docker build operations.
|
||||
|
||||
Accepts any fields from Docker API responses via constructor.
|
||||
"""
|
||||
|
||||
event_type = "build"
|
||||
stream: Optional[str]
|
||||
|
||||
def format_message(self) -> str:
|
||||
"""Dynamically format the message based on event data."""
|
||||
match self.status:
|
||||
case EventStatus.STARTED:
|
||||
return "Starting image build"
|
||||
case EventStatus.PROGRESS:
|
||||
if self.stream:
|
||||
# Clean up Docker build stream output
|
||||
if stream_msg := self.stream.strip():
|
||||
return stream_msg
|
||||
return "Building image..."
|
||||
case EventStatus.COMPLETED:
|
||||
return "Build completed"
|
||||
case EventStatus.ERROR:
|
||||
if self.exception:
|
||||
return f"Build failed: {self.exception}"
|
||||
return "Build failed"
|
||||
case _:
|
||||
# Fallback
|
||||
return f"Build: {self.status.value}"
|
||||
|
||||
|
||||
register_event(BuildEvent)
|
||||
|
||||
|
||||
def ensure_ecr_repository(repository_name: str) -> bool:
|
||||
"""Ensure ECR repository exists, create if it doesn't.
|
||||
|
||||
Args:
|
||||
repository_name: Name of the ECR repository (e.g., 'hosting/project-id')
|
||||
|
||||
Returns:
|
||||
bool: True if repository exists or was created successfully
|
||||
"""
|
||||
try:
|
||||
# Extract region from IMAGE_REGISTRY
|
||||
# Format: 315680545607.dkr.ecr.us-west-1.amazonaws.com
|
||||
registry_parts = IMAGE_REGISTRY.split('.')
|
||||
if len(registry_parts) >= 4 and 'ecr' in registry_parts:
|
||||
region = registry_parts[3] # us-west-1
|
||||
else:
|
||||
region = AWS_DEFAULT_REGION
|
||||
|
||||
ecr_client = boto3.client('ecr', region_name=region)
|
||||
|
||||
# Check if repository exists
|
||||
try:
|
||||
ecr_client.describe_repositories(repositoryNames=[repository_name])
|
||||
logger.info(f"ECR repository {repository_name} already exists")
|
||||
return True
|
||||
except ecr_client.exceptions.RepositoryNotFoundException:
|
||||
# Repository doesn't exist, create it
|
||||
logger.info(f"Creating ECR repository {repository_name}")
|
||||
ecr_client.create_repository(
|
||||
repositoryName=repository_name,
|
||||
imageTagMutability='MUTABLE',
|
||||
imageScanningConfiguration={'scanOnPush': False},
|
||||
)
|
||||
logger.info(f"ECR repository {repository_name} created successfully")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to ensure ECR repository {repository_name}: {e}")
|
||||
return False
|
||||
|
||||
|
||||
@dataclass
|
||||
class Image(BaseModel):
|
||||
"""Model for building and managing Docker images.
|
||||
|
||||
Handles Dockerfile generation, image building, and registry pushing.
|
||||
|
||||
Simple usage (with automatic logging):
|
||||
image = Image(name="myapp", tag="v1.0.0")
|
||||
image.build_sync()
|
||||
image_url = image.push_sync("ghcr.io/agentops")
|
||||
deployment = Deployment(name="myapp", image=image_url)
|
||||
|
||||
Progress monitoring usage:
|
||||
from jockey.backend.event import EventStatus
|
||||
|
||||
image = Image(name="myapp", tag="v1.0.0")
|
||||
|
||||
# Build with structured progress events
|
||||
for event in image.build():
|
||||
if event.status == EventStatus.STARTED:
|
||||
# Handle start event
|
||||
pass
|
||||
elif event.status == EventStatus.PROGRESS:
|
||||
# Handle progress event
|
||||
pass
|
||||
elif event.status == EventStatus.COMPLETED:
|
||||
# Handle completion event
|
||||
final_image = self.image_name
|
||||
|
||||
# Push with structured progress events
|
||||
for event in image.push("ghcr.io/agentops"):
|
||||
if event.status == EventStatus.STARTED:
|
||||
# Handle start event
|
||||
pass
|
||||
elif event.status == EventStatus.PROGRESS:
|
||||
# Handle progress event
|
||||
pass
|
||||
elif event.status == EventStatus.COMPLETED:
|
||||
image_url = event.image_url
|
||||
"""
|
||||
|
||||
namespace: str
|
||||
dockerfile_template: str
|
||||
tag: str = "latest"
|
||||
name: str = IMAGE_REPOSITORY # Uses shared ECR repository, individual deployments differentiated by tags
|
||||
dockerfile_vars: dict[str, str] = field(default_factory=dict)
|
||||
repository_name: Optional[str] = None # Repository directory name for COPY commands
|
||||
build_files: dict[str, str] = field(
|
||||
default_factory=dict
|
||||
) # Additional files to make available during build
|
||||
|
||||
@property
|
||||
def image_name(self) -> str:
|
||||
"""Get the image name with tag (repository:tag)."""
|
||||
return f"{self.name}:{self.tag}"
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
"""Get the full image URL for deployment."""
|
||||
return f"{IMAGE_REGISTRY}/{self.image_name}"
|
||||
|
||||
@staticmethod
|
||||
def _generate_job_name(job_id: str) -> str:
|
||||
"""Generate a Kubernetes job name from a job_id."""
|
||||
return f"builder-{job_id}".lower().replace(":", "-").replace("/", "-")
|
||||
|
||||
@property
|
||||
def job_name(self) -> str:
|
||||
"""Get the job name for Kubernetes build job."""
|
||||
return self._generate_job_name(self.name.replace('/', '-'))
|
||||
|
||||
def generate_dockerfile(self) -> str:
|
||||
"""Generate a Dockerfile using the specified template from templates/docker/ directory."""
|
||||
template_vars = {
|
||||
'base_image': 'python:3.12-slim-bookworm',
|
||||
'requirements_file': 'pyproject.toml',
|
||||
'install_agentstack': True,
|
||||
'agentstack_branch': 'deploy-command',
|
||||
'port': 6969,
|
||||
'run_command': ["/app/.venv/bin/agentstack", "run"],
|
||||
'repository_name': self.repository_name, # Repository directory for COPY commands
|
||||
}
|
||||
|
||||
template_vars.update(self.dockerfile_vars)
|
||||
template_path = f"docker/{self.dockerfile_template}.j2"
|
||||
return render_template(template_path, template_vars)
|
||||
|
||||
def _get_env_vars(self) -> list[k8s.V1EnvVar]:
|
||||
"""Get environment variables for the Kaniko builder container."""
|
||||
return [
|
||||
k8s.V1EnvVar(name='DOCKER_CONFIG', value='/kaniko/.docker'),
|
||||
k8s.V1EnvVar(
|
||||
name='AWS_ACCESS_KEY_ID',
|
||||
value_from=k8s.V1EnvVarSource(
|
||||
secret_key_ref=k8s.V1SecretKeySelector(name='aws-credentials', key='access-key')
|
||||
),
|
||||
),
|
||||
k8s.V1EnvVar(
|
||||
name='AWS_SECRET_ACCESS_KEY',
|
||||
value_from=k8s.V1EnvVarSource(
|
||||
secret_key_ref=k8s.V1SecretKeySelector(name='aws-credentials', key='secret-key')
|
||||
),
|
||||
),
|
||||
k8s.V1EnvVar(name='AWS_DEFAULT_REGION', value=AWS_DEFAULT_REGION),
|
||||
]
|
||||
|
||||
def build(self, job_id: Optional[str] = None) -> BuildEventStream:
|
||||
"""Build and push the image using builder in Kubernetes cluster.
|
||||
|
||||
Yields:
|
||||
BuildEvent: Structured log events during build and push
|
||||
|
||||
Returns:
|
||||
str: Full image URL that can be used in Deployment.image field
|
||||
"""
|
||||
try:
|
||||
yield BuildEvent(EventStatus.STARTED)
|
||||
|
||||
# Ensure ECR repository exists before building
|
||||
if not ensure_ecr_repository(self.name):
|
||||
raise Exception(f"Failed to create ECR repository {self.name}")
|
||||
|
||||
# Use job_id for builder job name if provided, otherwise fall back to self.job_name
|
||||
builder_job_name = self._generate_job_name(job_id) if job_id else self.job_name
|
||||
|
||||
# Instance files are handled via ConfigMap (no EFS needed)
|
||||
|
||||
# Create ConfigMap with Dockerfile content using our model
|
||||
# TODO: Optimize ConfigMap reuse pattern - currently we recreate on every build
|
||||
# but we could hash the Dockerfile content and reuse existing ConfigMaps if unchanged.
|
||||
# This would reduce K8s API calls and improve performance for repeated deployments
|
||||
# with identical Dockerfiles. Consider using content hash in ConfigMap name.
|
||||
configmap = ConfigMap(
|
||||
name=f"dockerfile-{builder_job_name}",
|
||||
namespace=self.namespace,
|
||||
data={"Dockerfile": self.generate_dockerfile()},
|
||||
)
|
||||
|
||||
# Try to create, if it already exists, delete and recreate
|
||||
try:
|
||||
configmap.create()
|
||||
except ApiException as e:
|
||||
if e.status == 409: # Already exists
|
||||
logger.info(f"ConfigMap {configmap.name} already exists, recreating...")
|
||||
configmap.delete()
|
||||
configmap.create()
|
||||
else:
|
||||
raise
|
||||
|
||||
# Setup basic volume mounts for Dockerfile
|
||||
volume_mounts = [k8s.V1VolumeMount(name="dockerfile", mount_path="/workspace", read_only=True)]
|
||||
volumes = [configmap.to_k8s_volume("dockerfile")]
|
||||
|
||||
# Get S3 cache configuration
|
||||
cache_args = self._get_cache_args()
|
||||
|
||||
# Build Kaniko arguments with S3 cache support
|
||||
kaniko_args = [
|
||||
'--dockerfile=/workspace/Dockerfile',
|
||||
'--context=/workspace',
|
||||
f'--destination={self.url}',
|
||||
f'--build-arg=JOB_ID={job_id or builder_job_name}',
|
||||
]
|
||||
kaniko_args.extend(cache_args)
|
||||
|
||||
# Handle build_files with ConfigMap
|
||||
if self.build_files:
|
||||
# Create a tar archive with all the files
|
||||
import tarfile
|
||||
import io
|
||||
import base64
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
temp_path = Path(temp_dir)
|
||||
|
||||
# Write files to temp directory
|
||||
for file_path, content in self.build_files.items():
|
||||
full_path = temp_path / file_path
|
||||
full_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
full_path.write_text(content)
|
||||
|
||||
# Create tar archive
|
||||
tar_buffer = io.BytesIO()
|
||||
with tarfile.open(fileobj=tar_buffer, mode='w:gz') as tar:
|
||||
for file_path in self.build_files.keys():
|
||||
tar.add(temp_path / file_path, arcname=file_path)
|
||||
|
||||
tar_data = base64.b64encode(tar_buffer.getvalue()).decode('utf-8')
|
||||
|
||||
# Use tar content hash to prevent stale ConfigMaps
|
||||
tar_hash = hashlib.md5(tar_data.encode()).hexdigest()[:8]
|
||||
|
||||
# Create ConfigMap with hash-based name to ensure fresh content
|
||||
instance_configmap = ConfigMap(
|
||||
name=f"instance-{tar_hash}",
|
||||
namespace=self.namespace,
|
||||
data={"instance-src.tar.gz": tar_data},
|
||||
)
|
||||
|
||||
instance_configmap.create()
|
||||
volume_mounts.append(
|
||||
k8s.V1VolumeMount(name="build-files", mount_path="/mnt/build_files", read_only=True)
|
||||
)
|
||||
volumes.append(instance_configmap.to_k8s_volume("build-files"))
|
||||
logger.info(f"ConfigMap {instance_configmap.name} created successfully")
|
||||
|
||||
pod = k8s.V1PodSpec(
|
||||
containers=[
|
||||
k8s.V1Container(
|
||||
name="builder",
|
||||
image=BUILDER_IMAGE,
|
||||
args=kaniko_args,
|
||||
env=self._get_env_vars(),
|
||||
volume_mounts=volume_mounts,
|
||||
resources=k8s.V1ResourceRequirements(
|
||||
limits={"cpu": BUILDER_CPU_LIMIT, "memory": BUILDER_MEMORY_LIMIT},
|
||||
requests={"cpu": BUILDER_CPU_REQUEST, "memory": BUILDER_MEMORY_REQUEST},
|
||||
),
|
||||
)
|
||||
],
|
||||
restart_policy="Never",
|
||||
volumes=volumes,
|
||||
)
|
||||
|
||||
job = k8s.V1Job(
|
||||
api_version="batch/v1",
|
||||
kind="Job",
|
||||
metadata=k8s.V1ObjectMeta(name=builder_job_name, namespace=self.namespace),
|
||||
spec=k8s.V1JobSpec(
|
||||
template=k8s.V1PodTemplateSpec(spec=pod),
|
||||
backoff_limit=1,
|
||||
ttl_seconds_after_finished=CLEANUP_DELAY_SECONDS,
|
||||
),
|
||||
)
|
||||
|
||||
# Try to create job, if it already exists, delete and recreate
|
||||
try:
|
||||
self.client.batch.create_namespaced_job(body=job, namespace=self.namespace)
|
||||
logger.info("Builder job created")
|
||||
except ApiException as e:
|
||||
if e.status == 409: # Already exists
|
||||
self.client.batch.delete_namespaced_job(name=builder_job_name, namespace=self.namespace)
|
||||
# Wait a moment for deletion to complete
|
||||
import time
|
||||
|
||||
time.sleep(2)
|
||||
self.client.batch.create_namespaced_job(body=job, namespace=self.namespace)
|
||||
logger.info("Builder job re-created")
|
||||
else:
|
||||
raise
|
||||
|
||||
logger.info(f"Building {builder_job_name}...")
|
||||
|
||||
w = watch.Watch()
|
||||
for event in w.stream(
|
||||
self.client.batch.list_namespaced_job,
|
||||
namespace=self.namespace,
|
||||
field_selector=f"metadata.name={builder_job_name}",
|
||||
timeout_seconds=600,
|
||||
):
|
||||
obj = event['object']
|
||||
status = obj.status
|
||||
|
||||
if status.succeeded and status.succeeded > 0:
|
||||
yield BuildEvent(EventStatus.COMPLETED)
|
||||
return self.url
|
||||
elif status.failed and status.failed > 0:
|
||||
yield BuildEvent(EventStatus.ERROR)
|
||||
raise Exception("Image build failed")
|
||||
else:
|
||||
yield BuildEvent(
|
||||
EventStatus.PROGRESS,
|
||||
stream="Building and pushing image...",
|
||||
)
|
||||
|
||||
except ApiException as e:
|
||||
yield BuildEvent(EventStatus.ERROR, exception=e)
|
||||
raise Exception(f"Image build failed: {e}")
|
||||
finally:
|
||||
try:
|
||||
self.client.batch.delete_namespaced_job(name=builder_job_name, namespace=self.namespace)
|
||||
configmap.delete()
|
||||
except:
|
||||
pass # Ignore cleanup errors
|
||||
logger.info(f"Job {builder_job_name} complete")
|
||||
|
||||
return self.url
|
||||
|
||||
def build_sync(self) -> str:
|
||||
"""Build and push the image synchronously (convenience method).
|
||||
|
||||
Returns:
|
||||
str: Full image URL that can be used in Deployment.image field
|
||||
"""
|
||||
result = None
|
||||
for event in self.build():
|
||||
if event.status == EventStatus.COMPLETED:
|
||||
result = self.url
|
||||
return result or self.url
|
||||
|
||||
def _get_cache_args(self) -> list[str]:
|
||||
"""Get Kaniko cache arguments for S3 cache.
|
||||
|
||||
Returns:
|
||||
List of Kaniko arguments for cache configuration
|
||||
"""
|
||||
# Create cache key based on repository name (project-specific)
|
||||
cache_key = hashlib.sha256(self.name.encode()).hexdigest()[:16]
|
||||
cache_path = f"s3://{S3_BUCKET_NAME}/{S3_BUILD_CACHE_PREFIX}/{cache_key}"
|
||||
|
||||
return [
|
||||
"--cache=true",
|
||||
f"--cache-repo={cache_path}",
|
||||
"--cache-ttl=24h",
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def get_builder_pod(cls, namespace: str, job_id: str) -> Optional['Pod']:
|
||||
"""Get a builder pod by job_id."""
|
||||
from .pod import Pod
|
||||
|
||||
builder_job_name = cls._generate_job_name(job_id)
|
||||
all_pods = Pod.filter(namespace)
|
||||
|
||||
for pod in all_pods:
|
||||
if pod.name.startswith(f"{builder_job_name}-") or pod.name == builder_job_name:
|
||||
return pod
|
||||
|
||||
return None
|
||||
@@ -0,0 +1,434 @@
|
||||
from __future__ import annotations
|
||||
from typing import Optional, Generator, ClassVar
|
||||
from dataclasses import dataclass, field
|
||||
import time
|
||||
import threading
|
||||
from queue import Queue, Empty
|
||||
|
||||
from kubernetes import client as k8s, watch # type: ignore
|
||||
from kubernetes.client.rest import ApiException # type: ignore
|
||||
|
||||
from jockey.log import logger
|
||||
from jockey.environment import (
|
||||
CPU_LIMIT,
|
||||
MEMORY_LIMIT,
|
||||
CPU_REQUEST,
|
||||
MEMORY_REQUEST,
|
||||
)
|
||||
from jockey.backend.event import BaseEvent, EventStatus, register_event
|
||||
from .base import BaseModel
|
||||
from .secret import SecretRef
|
||||
|
||||
DEFAULT_TIMEOUT: int = 3600 # 1 hour for job completion
|
||||
|
||||
JobEventStream = Generator['JobEvent', None, Optional['Job']]
|
||||
|
||||
|
||||
@dataclass
|
||||
class WatchEvent:
|
||||
"""Event from job or pod watchers."""
|
||||
|
||||
JOB: ClassVar[str] = "job"
|
||||
POD: ClassVar[str] = "pod"
|
||||
ERROR: ClassVar[str] = "error"
|
||||
|
||||
type: str
|
||||
data: any
|
||||
|
||||
|
||||
class JobEvent(BaseEvent):
|
||||
"""Event for job operations."""
|
||||
|
||||
event_type = "job"
|
||||
|
||||
active_pods: int = 0
|
||||
succeeded_pods: int = 0
|
||||
failed_pods: int = 0
|
||||
phase: Optional[str] = None
|
||||
|
||||
def format_message(self) -> str:
|
||||
"""Dynamically format the message based on event data."""
|
||||
match self.status:
|
||||
case EventStatus.STARTED:
|
||||
return "Starting job"
|
||||
case EventStatus.PROGRESS:
|
||||
if self.active_pods > 0:
|
||||
return f"Job running: {self.active_pods} active pods"
|
||||
else:
|
||||
return "Job preparing to start"
|
||||
case EventStatus.COMPLETED:
|
||||
return f"Job completed successfully: {self.succeeded_pods} pods succeeded"
|
||||
case EventStatus.ERROR:
|
||||
if self.exception:
|
||||
return str(self.exception)
|
||||
return f"Job failed: {self.failed_pods} pods failed"
|
||||
case EventStatus.TIMEOUT:
|
||||
return "Job timed out"
|
||||
case _: # fallback
|
||||
return f"Job: {self.status.value}"
|
||||
|
||||
|
||||
register_event(JobEvent)
|
||||
|
||||
|
||||
class JobManager:
|
||||
"""Manages job watching and event processing.
|
||||
|
||||
Similar to DeployManager but for Kubernetes Jobs.
|
||||
"""
|
||||
|
||||
job: Job
|
||||
timeout: int
|
||||
event_queue: Queue[WatchEvent]
|
||||
job_completed: bool = False
|
||||
final_job: Optional[k8s.V1Job] = None
|
||||
start_time: float
|
||||
|
||||
def __init__(self, job: Job, timeout: int = DEFAULT_TIMEOUT):
|
||||
self.job = job
|
||||
self.timeout = timeout
|
||||
self.event_queue = Queue[WatchEvent]()
|
||||
self.start_time = time.time()
|
||||
|
||||
def watch_and_yield_events(self) -> JobEventStream:
|
||||
"""Start watchers and process events until job is complete."""
|
||||
self._start_watchers()
|
||||
|
||||
while not self.job_completed:
|
||||
if self._is_timed_out:
|
||||
yield JobEvent(EventStatus.TIMEOUT)
|
||||
return None
|
||||
|
||||
if event := self._get_next_event():
|
||||
yield from self._process_event(event)
|
||||
|
||||
return self.job
|
||||
|
||||
def _start_watchers(self) -> None:
|
||||
"""Start job and pod watchers in separate threads."""
|
||||
# late import to avoid circular dependencies
|
||||
from .pod import Pod
|
||||
|
||||
def watch_job():
|
||||
"""Watch job events and put them in the queue."""
|
||||
try:
|
||||
w = watch.Watch()
|
||||
for event in w.stream(
|
||||
self.job.client.batch.list_namespaced_job,
|
||||
namespace=self.job.namespace,
|
||||
field_selector=self.job.job_selector,
|
||||
timeout_seconds=self.timeout,
|
||||
):
|
||||
self.event_queue.put(WatchEvent(WatchEvent.JOB, event))
|
||||
except Exception as e:
|
||||
self.event_queue.put(WatchEvent(WatchEvent.ERROR, e))
|
||||
|
||||
def watch_pods():
|
||||
"""Watch pod events and put them in the queue."""
|
||||
try:
|
||||
for pod_event in Pod.watch(
|
||||
namespace=self.job.namespace,
|
||||
label_selector=self.job.pod_selector,
|
||||
timeout=self.timeout,
|
||||
):
|
||||
self.event_queue.put(WatchEvent(WatchEvent.POD, pod_event))
|
||||
except Exception as e:
|
||||
self.event_queue.put(WatchEvent(WatchEvent.ERROR, e))
|
||||
|
||||
job_thread = threading.Thread(target=watch_job, daemon=True)
|
||||
pod_thread = threading.Thread(target=watch_pods, daemon=True)
|
||||
job_thread.start()
|
||||
pod_thread.start()
|
||||
|
||||
@property
|
||||
def _is_timed_out(self) -> bool:
|
||||
"""Check if we've exceeded the timeout."""
|
||||
return time.time() - self.start_time > self.timeout
|
||||
|
||||
def _get_next_event(self) -> Optional[WatchEvent]:
|
||||
"""Get the next event from the queue with a short timeout."""
|
||||
try:
|
||||
return self.event_queue.get(timeout=1)
|
||||
except Empty:
|
||||
return None
|
||||
|
||||
def _process_event(self, event: WatchEvent) -> JobEventStream:
|
||||
"""Process a single event and yield appropriate JobEvents."""
|
||||
match event.type:
|
||||
case WatchEvent.ERROR:
|
||||
assert isinstance(event.data, Exception)
|
||||
yield JobEvent(EventStatus.ERROR, exception=event.data)
|
||||
|
||||
case WatchEvent.POD:
|
||||
# convert `PodEvent` to `JobEvent`
|
||||
yield from self._process_pod_event(event.data)
|
||||
|
||||
case WatchEvent.JOB:
|
||||
assert isinstance(event.data, dict)
|
||||
yield from self._process_job_event(event.data)
|
||||
|
||||
def _process_job_event(self, event_data: dict) -> JobEventStream:
|
||||
"""Process a job event and yield appropriate JobEvents."""
|
||||
phase, obj = event_data['type'], event_data['object']
|
||||
|
||||
if phase == 'DELETED':
|
||||
yield JobEvent(EventStatus.ERROR, exception=Exception("Job was deleted"))
|
||||
return
|
||||
|
||||
status = obj.status
|
||||
active = status.active or 0
|
||||
succeeded = status.succeeded or 0
|
||||
failed = status.failed or 0
|
||||
|
||||
if succeeded > 0:
|
||||
self.job_completed = True
|
||||
self.final_job = obj
|
||||
yield JobEvent(
|
||||
EventStatus.COMPLETED,
|
||||
phase=phase,
|
||||
active_pods=active,
|
||||
succeeded_pods=succeeded,
|
||||
failed_pods=failed,
|
||||
)
|
||||
elif failed > 0:
|
||||
self.job_completed = True
|
||||
yield JobEvent(
|
||||
EventStatus.ERROR,
|
||||
phase=phase,
|
||||
active_pods=active,
|
||||
succeeded_pods=succeeded,
|
||||
failed_pods=failed,
|
||||
exception=Exception(f"Job failed with {failed} failed pods"),
|
||||
)
|
||||
elif active > 0:
|
||||
yield JobEvent(
|
||||
EventStatus.PROGRESS,
|
||||
phase=phase,
|
||||
active_pods=active,
|
||||
succeeded_pods=succeeded,
|
||||
failed_pods=failed,
|
||||
)
|
||||
else:
|
||||
yield JobEvent(
|
||||
EventStatus.PROGRESS,
|
||||
phase=phase,
|
||||
active_pods=active,
|
||||
succeeded_pods=succeeded,
|
||||
failed_pods=failed,
|
||||
)
|
||||
|
||||
return obj
|
||||
|
||||
def _process_pod_event(self, pod_event) -> JobEventStream:
|
||||
"""Process a pod event and convert it to job-level events."""
|
||||
from .pod import PodEvent
|
||||
|
||||
# Handle exception case
|
||||
if isinstance(pod_event, Exception):
|
||||
yield JobEvent(EventStatus.ERROR, exception=pod_event)
|
||||
return None
|
||||
|
||||
if not isinstance(pod_event, PodEvent):
|
||||
return None
|
||||
|
||||
# Convert pod-level events to job-level events
|
||||
if pod_event.status == EventStatus.ERROR:
|
||||
yield JobEvent(EventStatus.ERROR, exception=Exception(pod_event.message))
|
||||
elif pod_event.status == EventStatus.PROGRESS:
|
||||
yield JobEvent(EventStatus.PROGRESS, phase=pod_event.phase)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
@dataclass
|
||||
class Job(BaseModel):
|
||||
"""Model-style interface for Kubernetes jobs.
|
||||
|
||||
Jobs are for short-running tasks that need to complete and then terminate.
|
||||
Perfect for one-time executions like running agents with input data.
|
||||
"""
|
||||
|
||||
# Configuration attributes (required for new jobs)
|
||||
name: str
|
||||
image_url: str # Full image URL from Image.url
|
||||
namespace: str # Required namespace for multi-tenant isolation
|
||||
|
||||
# Job-specific configuration
|
||||
command: list[str] = field(default_factory=list) # Command to run
|
||||
args: list[str] = field(default_factory=list) # Arguments to command
|
||||
env_vars: dict[str, str] = field(default_factory=dict) # Environment variables
|
||||
|
||||
# Optional configuration attributes (with defaults)
|
||||
resources: k8s.V1ResourceRequirements = field(
|
||||
default_factory=lambda: k8s.V1ResourceRequirements(
|
||||
requests={"cpu": CPU_REQUEST, "memory": MEMORY_REQUEST},
|
||||
limits={"cpu": CPU_LIMIT, "memory": MEMORY_LIMIT},
|
||||
)
|
||||
)
|
||||
secret_refs: list[SecretRef] = field(default_factory=list)
|
||||
|
||||
# Job-specific settings
|
||||
backoff_limit: int = 0 # Don't retry failed jobs by default
|
||||
ttl_seconds_after_finished: int = 3600 # Clean up after 1 hour
|
||||
restart_policy: str = "Never" # Jobs should never restart
|
||||
|
||||
# Metadata attributes (populated from k8s data)
|
||||
uid: Optional[str] = None
|
||||
metadata: Optional[k8s.V1ObjectMeta] = None
|
||||
labels: dict[str, str] = field(default_factory=dict)
|
||||
creation_timestamp: Optional[str] = None
|
||||
completion_timestamp: Optional[str] = None
|
||||
|
||||
def __post_init__(self):
|
||||
"""Sanitize name for Kubernetes compatibility after initialization."""
|
||||
self.name = self.name.replace("/", "-").replace(":", "-").lower()
|
||||
|
||||
@property
|
||||
def match_labels(self) -> dict[str, str]:
|
||||
"""Get the match labels used by this job's selector."""
|
||||
return {"job-name": self.name}
|
||||
|
||||
@property
|
||||
def job_selector(self) -> str:
|
||||
"""Get the field selector for watching this specific job."""
|
||||
return f"metadata.name={self.name}"
|
||||
|
||||
@property
|
||||
def pod_selector(self) -> str:
|
||||
"""Get the label selector for watching pods created by this job."""
|
||||
return f"job-name={self.name}"
|
||||
|
||||
def to_k8s_job(self) -> k8s.V1Job:
|
||||
"""Convert to Kubernetes V1Job object for API calls."""
|
||||
|
||||
env_vars = []
|
||||
|
||||
# Add environment variables
|
||||
for key, value in self.env_vars.items():
|
||||
env_vars.append(k8s.V1EnvVar(name=key, value=value))
|
||||
|
||||
# Add secret references
|
||||
for secret_ref in self.secret_refs:
|
||||
env_vars.append(secret_ref.to_env_var())
|
||||
|
||||
container = k8s.V1Container(
|
||||
name=self.name,
|
||||
image=self.image_url,
|
||||
image_pull_policy="Always",
|
||||
resources=self.resources,
|
||||
env=env_vars,
|
||||
command=self.command if self.command else None,
|
||||
args=self.args if self.args else None,
|
||||
)
|
||||
|
||||
labels = {**self.match_labels, **self.labels}
|
||||
|
||||
return k8s.V1Job(
|
||||
api_version="batch/v1",
|
||||
kind="Job",
|
||||
metadata=k8s.V1ObjectMeta(
|
||||
name=self.name,
|
||||
namespace=self.namespace,
|
||||
labels=labels,
|
||||
),
|
||||
spec=k8s.V1JobSpec(
|
||||
backoff_limit=self.backoff_limit,
|
||||
ttl_seconds_after_finished=self.ttl_seconds_after_finished,
|
||||
template=k8s.V1PodTemplateSpec(
|
||||
metadata=k8s.V1ObjectMeta(labels=labels),
|
||||
spec=k8s.V1PodSpec(
|
||||
containers=[container],
|
||||
restart_policy=self.restart_policy,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
def create_and_watch(self, timeout: int = DEFAULT_TIMEOUT) -> JobEventStream:
|
||||
"""Create this job and watch until completion."""
|
||||
try:
|
||||
yield JobEvent(EventStatus.STARTED)
|
||||
|
||||
k8s_job = self.to_k8s_job()
|
||||
yield JobEvent(EventStatus.PROGRESS, phase="creating")
|
||||
|
||||
self.client.batch.create_namespaced_job(
|
||||
body=k8s_job,
|
||||
namespace=self.namespace,
|
||||
)
|
||||
|
||||
manager = JobManager(self, timeout)
|
||||
yield from manager.watch_and_yield_events()
|
||||
|
||||
if manager.final_job:
|
||||
return self.from_k8s_data(manager.final_job)
|
||||
else:
|
||||
raise ApiException(f"Job {self.name} did not complete within timeout")
|
||||
|
||||
except ApiException as e:
|
||||
yield JobEvent(EventStatus.ERROR, exception=e)
|
||||
logger.debug(f"Create job failed (status {e.status})")
|
||||
raise
|
||||
|
||||
@classmethod
|
||||
def from_k8s_data(cls, data: k8s.V1Job) -> Job:
|
||||
"""Create a Job instance from Kubernetes API data."""
|
||||
container = data.spec.template.spec.containers[0]
|
||||
|
||||
# Extract environment variables
|
||||
env_vars = {}
|
||||
secret_refs = []
|
||||
|
||||
if container.env:
|
||||
for env_var in container.env:
|
||||
if env_var.value:
|
||||
env_vars[env_var.name] = env_var.value
|
||||
elif env_var.value_from and env_var.value_from.secret_key_ref:
|
||||
secret_refs.append(
|
||||
SecretRef(
|
||||
key=env_var.value_from.secret_key_ref.name,
|
||||
env_var_name=env_var.name,
|
||||
)
|
||||
)
|
||||
|
||||
return cls(
|
||||
name=data.metadata.name,
|
||||
image_url=container.image,
|
||||
namespace=data.metadata.namespace,
|
||||
command=container.command or [],
|
||||
args=container.args or [],
|
||||
env_vars=env_vars,
|
||||
resources=container.resources,
|
||||
secret_refs=secret_refs,
|
||||
backoff_limit=data.spec.backoff_limit or 0,
|
||||
ttl_seconds_after_finished=data.spec.ttl_seconds_after_finished or 3600,
|
||||
# Metadata
|
||||
uid=data.metadata.uid,
|
||||
metadata=data.metadata,
|
||||
labels=data.metadata.labels or {},
|
||||
creation_timestamp=data.metadata.creation_timestamp,
|
||||
completion_timestamp=data.status.completion_time if data.status else None,
|
||||
)
|
||||
|
||||
def get_logs(self) -> str:
|
||||
"""Get logs from the job's pod(s)."""
|
||||
try:
|
||||
# Find pods created by this job
|
||||
from .pod import Pod
|
||||
|
||||
pods = Pod.filter(namespace=self.namespace, label_selector=self.pod_selector)
|
||||
|
||||
if not pods:
|
||||
return "No pods found for job"
|
||||
|
||||
# Get logs from the first pod (jobs typically have one pod)
|
||||
pod = pods[0]
|
||||
return pod.get_logs()
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to get logs for job {self.name}: {e}")
|
||||
return f"Failed to get logs: {e}"
|
||||
|
||||
def to_string(self) -> str:
|
||||
"""Convert to string representation."""
|
||||
return f"Job(name={self.name}, image_url={self.image_url}, namespace={self.namespace})"
|
||||
@@ -0,0 +1,318 @@
|
||||
from __future__ import annotations
|
||||
from typing import Optional, Generator, Union, Literal
|
||||
from datetime import datetime
|
||||
|
||||
from kubernetes import watch, client as k8s # type: ignore
|
||||
from kubernetes.client.rest import ApiException # type: ignore
|
||||
|
||||
from jockey.log import logger
|
||||
from jockey.backend.event import BaseEvent, EventStatus, register_event
|
||||
from .base import KubernetesResourceWrapper
|
||||
|
||||
|
||||
NativeContainerState = Union[
|
||||
k8s.V1ContainerStateWaiting,
|
||||
k8s.V1ContainerStateRunning,
|
||||
k8s.V1ContainerStateTerminated,
|
||||
]
|
||||
PodEventPhase = Literal["ADDED", "MODIFIED", "DELETED"]
|
||||
PodStreamEvent = Generator['PodEvent', None, None]
|
||||
|
||||
|
||||
class PodEvent(BaseEvent):
|
||||
"""Event for pod operations."""
|
||||
|
||||
event_type = "pod"
|
||||
|
||||
phase: PodEventPhase
|
||||
container_name: Optional[str]
|
||||
container_state: Optional[NativeContainerState]
|
||||
|
||||
def _format_waiting_message(self, container_state: NativeContainerState) -> str:
|
||||
"""Format a waiting message based on the container state."""
|
||||
reason = container_state.reason or "Unknown"
|
||||
message = container_state.message or ""
|
||||
|
||||
if "exec format error" in message.lower():
|
||||
return "Architecture mismatch - Container image may be built for wrong architecture (ARM64 vs AMD64)."
|
||||
|
||||
if reason == "CrashLoopBackOff":
|
||||
return f"Container '{self.container_name}' is crash looping. {message}"
|
||||
elif reason == "ImagePullBackOff":
|
||||
return f"Failed to pull image for container '{self.container_name}'. {message}"
|
||||
elif reason == "ErrImagePull":
|
||||
return f"Error pulling image for container '{self.container_name}'. {message}"
|
||||
elif reason == "ContainerCreating":
|
||||
return f"Container '{self.container_name}' is being created"
|
||||
elif reason == "PodInitializing":
|
||||
return "Pod is initializing"
|
||||
else:
|
||||
return f"Container '{self.container_name}' waiting: {reason}. {message}"
|
||||
|
||||
def format_message(self) -> str:
|
||||
"""Dynamically format the message based on event data."""
|
||||
if self.phase == 'ADDED':
|
||||
return "Pod created"
|
||||
elif self.phase == 'DELETED':
|
||||
return "Pod deleted"
|
||||
|
||||
if self.container_state:
|
||||
if isinstance(self.container_state, k8s.V1ContainerStateWaiting):
|
||||
return self._format_waiting_message(self.container_state)
|
||||
|
||||
elif isinstance(self.container_state, k8s.V1ContainerStateTerminated):
|
||||
exit_code = self.container_state.exit_code
|
||||
terminated_reason = self.container_state.reason or "Unknown"
|
||||
|
||||
if exit_code == 0:
|
||||
return f"Container '{self.container_name}' completed successfully"
|
||||
else:
|
||||
return f"Container '{self.container_name}' failed with exit code {exit_code} ({terminated_reason})"
|
||||
|
||||
elif isinstance(self.container_state, k8s.V1ContainerStateRunning):
|
||||
return f"Container '{self.container_name}' is running"
|
||||
|
||||
return f"Pod status: {self.status.value}"
|
||||
|
||||
@classmethod
|
||||
def from_native_state(
|
||||
cls,
|
||||
phase: PodEventPhase,
|
||||
container_name: str,
|
||||
container_state: NativeContainerState,
|
||||
) -> PodEvent:
|
||||
"""Create a PodEvent from native Kubernetes container state."""
|
||||
if isinstance(container_state, k8s.V1ContainerStateWaiting):
|
||||
if container_state.reason in ("CrashLoopBackOff", "ImagePullBackOff", "ErrImagePull"):
|
||||
event_status = EventStatus.ERROR
|
||||
else: # "ContainerCreating", "PodInitializing", etc.
|
||||
event_status = EventStatus.PROGRESS
|
||||
|
||||
elif isinstance(container_state, k8s.V1ContainerStateTerminated):
|
||||
event_status = EventStatus.ERROR if container_state.exit_code != 0 else EventStatus.COMPLETED
|
||||
|
||||
elif isinstance(container_state, k8s.V1ContainerStateRunning):
|
||||
event_status = EventStatus.PROGRESS
|
||||
|
||||
else:
|
||||
raise ValueError(f"Unknown container state type: {type(container_state)}")
|
||||
|
||||
return cls(
|
||||
event_status,
|
||||
phase=phase,
|
||||
container_name=container_name,
|
||||
container_state=container_state,
|
||||
)
|
||||
|
||||
|
||||
register_event(PodEvent)
|
||||
|
||||
|
||||
class Pod(KubernetesResourceWrapper):
|
||||
"""Model-style interface for Kubernetes Pods."""
|
||||
|
||||
@property
|
||||
def phase(self) -> Optional[str]:
|
||||
"""Get the Pod phase (Pending, Running, Succeeded, Failed, Unknown)."""
|
||||
return self.data.status.phase if self.data else None
|
||||
|
||||
@property
|
||||
def ready(self) -> bool:
|
||||
"""Check if the Pod is ready."""
|
||||
if self.data and self.data.status.conditions:
|
||||
for condition in self.data.status.conditions:
|
||||
if condition.type == "Ready":
|
||||
return bool(condition.status == "True")
|
||||
return False
|
||||
|
||||
@property
|
||||
def restart_count(self) -> int:
|
||||
"""Get the total restart count for all containers."""
|
||||
if self.data and self.data.status.container_statuses:
|
||||
return sum(status.restart_count for status in self.data.status.container_statuses)
|
||||
return 0
|
||||
|
||||
@property
|
||||
def node_name(self) -> Optional[str]:
|
||||
"""Get the name of the node where the Pod is running."""
|
||||
return self.data.spec.node_name if self.data else None
|
||||
|
||||
@property
|
||||
def pod_ip(self) -> Optional[str]:
|
||||
"""Get the Pod IP address."""
|
||||
return self.data.status.pod_ip if self.data else None
|
||||
|
||||
@property
|
||||
def labels(self) -> dict[str, str]:
|
||||
"""Get the Pod labels."""
|
||||
if self.data and self.data.metadata.labels:
|
||||
return self.data.metadata.labels # type: ignore
|
||||
return {}
|
||||
|
||||
@property
|
||||
def annotations(self) -> dict[str, str]:
|
||||
"""Get the Pod annotations."""
|
||||
if self.data and self.data.metadata.annotations:
|
||||
return self.data.metadata.annotations # type: ignore
|
||||
return {}
|
||||
|
||||
@property
|
||||
def creation_timestamp(self) -> Optional[datetime]:
|
||||
"""Get the Pod creation timestamp."""
|
||||
return self.data.metadata.creation_timestamp if self.data else None
|
||||
|
||||
@property
|
||||
def containers(self) -> list[str]:
|
||||
"""Get the list of container names in the Pod."""
|
||||
if self.data and self.data.spec.containers:
|
||||
return [container.name for container in self.data.spec.containers]
|
||||
return []
|
||||
|
||||
def get_logs(
|
||||
self,
|
||||
namespace: str,
|
||||
container: Optional[str] = None,
|
||||
tail_lines: Optional[int] = None,
|
||||
) -> str:
|
||||
"""Get logs for the Pod or a specific container."""
|
||||
try:
|
||||
return str(
|
||||
self.client.core.read_namespaced_pod_log(
|
||||
name=self.name,
|
||||
namespace=namespace,
|
||||
container=container,
|
||||
tail_lines=tail_lines,
|
||||
)
|
||||
)
|
||||
except ApiException:
|
||||
logger.debug(f"Get logs for Pod {self.name} returned empty")
|
||||
return ""
|
||||
|
||||
def stream_logs(self, namespace: str) -> Generator[str, None, None]:
|
||||
"""Stream logs for the Pod or a specific container."""
|
||||
try:
|
||||
w = watch.Watch()
|
||||
for event in w.stream(
|
||||
self.client.core.read_namespaced_pod_log,
|
||||
name=self.name,
|
||||
namespace=namespace,
|
||||
follow=True,
|
||||
_preload_content=False,
|
||||
):
|
||||
if event and isinstance(event, str):
|
||||
yield event
|
||||
except ApiException as e:
|
||||
logger.debug(f"Stream logs for Pod {self.name} failed: {e}")
|
||||
yield f"Error streaming logs: {e}"
|
||||
except Exception as e:
|
||||
logger.debug(f"Stream logs for Pod {self.name} unexpected error: {e}")
|
||||
yield f"Unexpected error: {e}"
|
||||
|
||||
@classmethod
|
||||
def create(cls, namespace: str, body) -> Pod:
|
||||
raise NotImplementedError("Pods are typically created by deployments, not directly")
|
||||
|
||||
def delete(self) -> bool:
|
||||
"""Delete this Pod."""
|
||||
try:
|
||||
self.client.core.delete_namespaced_pod(name=self.name, namespace=self.namespace)
|
||||
return True
|
||||
except ApiException as e:
|
||||
logger.debug(f"Delete Pod {self.name} failed (status {e.status})")
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def delete_by_name(cls, name: str, namespace: str) -> bool:
|
||||
"""Delete a Pod by name (for CLI usage)."""
|
||||
try:
|
||||
cls.client.core.delete_namespaced_pod(name=name, namespace=namespace)
|
||||
return True
|
||||
except ApiException as e:
|
||||
logger.debug(f"Delete Pod {name} failed (status {e.status})")
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def get(cls, name: str, namespace: str) -> Optional[Pod]:
|
||||
"""Get a Pod by name."""
|
||||
try:
|
||||
return cls(cls.client.core.read_namespaced_pod(name=name, namespace=namespace))
|
||||
except ApiException as e:
|
||||
logger.debug(f"Get Pod {name} returned empty (status {e.status})")
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def filter(cls, namespace: str, label_selector: Optional[str] = None, **kwargs) -> list[Pod]:
|
||||
"""Filter Pods in the namespace, optionally filtered by label selector."""
|
||||
try:
|
||||
result = cls.client.core.list_namespaced_pod(
|
||||
namespace=namespace,
|
||||
label_selector=label_selector,
|
||||
)
|
||||
return [cls(item) for item in result.items]
|
||||
except ApiException as e:
|
||||
logger.debug(f"Filter Pods returned empty (status {e.status})")
|
||||
return []
|
||||
|
||||
def watch_status(self, timeout: int = 900) -> PodStreamEvent:
|
||||
"""Watch this specific pod for status changes."""
|
||||
yield from self.__class__.watch(
|
||||
namespace=self.namespace,
|
||||
field_selector=f"metadata.name={self.name}",
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def watch(
|
||||
cls,
|
||||
namespace: str,
|
||||
label_selector: Optional[str] = None,
|
||||
field_selector: Optional[str] = None,
|
||||
timeout: int = 900,
|
||||
) -> PodStreamEvent:
|
||||
"""Watch pods matching the selectors and yield events for status changes."""
|
||||
try:
|
||||
w = watch.Watch()
|
||||
for event in w.stream(
|
||||
cls.client.core.list_namespaced_pod,
|
||||
namespace=namespace,
|
||||
timeout_seconds=timeout,
|
||||
label_selector=label_selector,
|
||||
field_selector=field_selector,
|
||||
):
|
||||
obj, phase = event['object'], event['type']
|
||||
|
||||
if phase == 'ADDED':
|
||||
yield PodEvent(EventStatus.PROGRESS, phase=phase)
|
||||
elif phase == 'DELETED':
|
||||
yield PodEvent(EventStatus.PROGRESS, phase=phase)
|
||||
|
||||
if not obj.status or not obj.status.container_statuses:
|
||||
continue
|
||||
|
||||
for container_status in obj.status.container_statuses:
|
||||
if not container_status.state:
|
||||
continue
|
||||
|
||||
if container_status.state.waiting:
|
||||
yield PodEvent.from_native_state(
|
||||
phase,
|
||||
container_name=container_status.name,
|
||||
container_state=container_status.state.waiting,
|
||||
)
|
||||
|
||||
if container_status.state.terminated:
|
||||
yield PodEvent.from_native_state(
|
||||
phase,
|
||||
container_name=container_status.name,
|
||||
container_state=container_status.state.terminated,
|
||||
)
|
||||
|
||||
if container_status.state.running:
|
||||
yield PodEvent.from_native_state(
|
||||
phase,
|
||||
container_name=container_status.name,
|
||||
container_state=container_status.state.running,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"Pod watcher error: {e}")
|
||||
@@ -0,0 +1,149 @@
|
||||
from __future__ import annotations
|
||||
from typing import Optional, Generator
|
||||
from enum import Enum
|
||||
from dataclasses import dataclass
|
||||
import re
|
||||
|
||||
import git
|
||||
from git.exc import GitCommandError
|
||||
|
||||
from jockey.backend import (
|
||||
get_repository_path,
|
||||
ensure_namespace_directory,
|
||||
cleanup_namespace_directory,
|
||||
)
|
||||
from jockey.backend.event import BaseEvent, EventStatus, register_event
|
||||
|
||||
|
||||
class RepositoryEventStep(Enum):
|
||||
"""Specific steps in repository operations."""
|
||||
|
||||
INITIALIZING = "initializing"
|
||||
CLONING = "cloning"
|
||||
CHECKOUT = "checkout"
|
||||
COMPLETED = "completed"
|
||||
|
||||
|
||||
class RepositoryEvent(BaseEvent):
|
||||
"""Event for repository operations."""
|
||||
|
||||
event_type = "repository"
|
||||
step: Optional[RepositoryEventStep]
|
||||
|
||||
def format_message(self) -> str:
|
||||
"""Dynamically format the message based on step and status."""
|
||||
if self.status == EventStatus.STARTED:
|
||||
return "Starting repository clone"
|
||||
elif self.status == EventStatus.PROGRESS:
|
||||
match self.step:
|
||||
case RepositoryEventStep.INITIALIZING:
|
||||
return "Initializing clone directory"
|
||||
case RepositoryEventStep.CLONING:
|
||||
return "Cloning repository..."
|
||||
case RepositoryEventStep.CHECKOUT:
|
||||
return "Checking out branch"
|
||||
case _:
|
||||
return "Processing repository..."
|
||||
elif self.status == EventStatus.COMPLETED:
|
||||
return "Repository clone completed"
|
||||
elif self.status == EventStatus.ERROR:
|
||||
if self.exception:
|
||||
return f"Repository clone failed: {self.exception}"
|
||||
return "Repository clone failed"
|
||||
|
||||
# Fallback
|
||||
return f"Repository: {self.status.value}"
|
||||
|
||||
|
||||
register_event(RepositoryEvent)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Repository:
|
||||
"""Model for managing Git repositories.
|
||||
|
||||
Handles repository cloning, checkout, and cleanup in namespace-isolated directories.
|
||||
"""
|
||||
|
||||
url: str
|
||||
namespace: str # Required for directory isolation
|
||||
branch: str = "main" # Branch or commit hash to checkout
|
||||
local_name: Optional[str] = None # Directory name, defaults to repo name
|
||||
github_access_token: Optional[str] = None # GitHub access token for private repos
|
||||
|
||||
@property
|
||||
def repository_name(self) -> str:
|
||||
"""Extract repository name from URL using regex."""
|
||||
if self.local_name:
|
||||
return self.local_name
|
||||
|
||||
# Use regex to extract repo name from various Git URL formats:
|
||||
# https://github.com/user/repo.git
|
||||
# git@github.com:user/repo.git
|
||||
# https://gitlab.com/user/repo
|
||||
# /path/to/local/repo
|
||||
pattern = r'[/:]([^/]+?)(?:\.git)?/?$'
|
||||
match = re.search(pattern, self.url)
|
||||
|
||||
if match:
|
||||
return match.group(1)
|
||||
else:
|
||||
raise ValueError(f"Unable to extract repository name from URL: {self.url}")
|
||||
|
||||
@property
|
||||
def local_path(self) -> str:
|
||||
"""Get the full local path where repository will be cloned."""
|
||||
return str(get_repository_path(self.namespace, self.repository_name))
|
||||
|
||||
def _get_authenticated_url(self) -> str:
|
||||
"""Get the repository URL with authentication token if available."""
|
||||
if not self.github_access_token:
|
||||
return self.url
|
||||
|
||||
# Transform https://github.com/user/repo.git to https://token@github.com/user/repo.git
|
||||
return self.url.replace('https://github.com/', f'https://{self.github_access_token}@github.com/')
|
||||
|
||||
def clone(self) -> Generator[RepositoryEvent, None, str]:
|
||||
"""Clone the repository with progress events.
|
||||
|
||||
Yields:
|
||||
RepositoryEvent: Status events during cloning
|
||||
|
||||
Returns:
|
||||
str: Local path to the cloned repository
|
||||
"""
|
||||
try:
|
||||
yield RepositoryEvent(EventStatus.STARTED)
|
||||
yield RepositoryEvent(EventStatus.PROGRESS, step=RepositoryEventStep.INITIALIZING)
|
||||
cleanup_namespace_directory(self.namespace)
|
||||
ensure_namespace_directory(self.namespace)
|
||||
|
||||
yield RepositoryEvent(EventStatus.PROGRESS, step=RepositoryEventStep.CLONING)
|
||||
repo = git.Repo.clone_from(
|
||||
self._get_authenticated_url(),
|
||||
self.local_path,
|
||||
)
|
||||
|
||||
yield RepositoryEvent(EventStatus.PROGRESS, step=RepositoryEventStep.CHECKOUT)
|
||||
repo.git.checkout(self.branch)
|
||||
|
||||
yield RepositoryEvent(EventStatus.COMPLETED)
|
||||
return self.local_path
|
||||
|
||||
except GitCommandError as e:
|
||||
yield RepositoryEvent(EventStatus.ERROR, exception=e)
|
||||
except Exception as e:
|
||||
yield RepositoryEvent(EventStatus.ERROR, exception=e)
|
||||
finally:
|
||||
cleanup_namespace_directory(self.namespace)
|
||||
|
||||
def clone_sync(self) -> str:
|
||||
"""Clone the repository synchronously (convenience method).
|
||||
|
||||
Returns:
|
||||
str: Local path to the cloned repository
|
||||
"""
|
||||
for event in self.clone():
|
||||
if event.status == EventStatus.COMPLETED:
|
||||
return self.local_path
|
||||
return self.local_path
|
||||
@@ -0,0 +1,228 @@
|
||||
from __future__ import annotations
|
||||
from typing import Optional
|
||||
from dataclasses import dataclass, field
|
||||
import base64
|
||||
|
||||
from kubernetes import client as k8s # type: ignore
|
||||
from kubernetes.client.rest import ApiException # type: ignore
|
||||
|
||||
from .base import BaseModel
|
||||
from jockey.log import logger
|
||||
|
||||
|
||||
def _encode(value: str) -> str:
|
||||
"""Encode a string value to base64."""
|
||||
return base64.b64encode(value.encode('utf-8')).decode('utf-8')
|
||||
|
||||
|
||||
def _decode_bytes(value: str) -> bytes:
|
||||
"""Decode a base64 string value."""
|
||||
return base64.b64decode(value.encode('utf-8'))
|
||||
|
||||
|
||||
def _decode_str(value: str) -> str:
|
||||
"""Decode a base64 string value."""
|
||||
return _decode_bytes(value).decode('utf-8')
|
||||
|
||||
|
||||
def _safe_name(name: str) -> str:
|
||||
"""Transform name to lowercase with dashes for Kubernetes secret name."""
|
||||
return name.lower().replace('_', '-')
|
||||
|
||||
|
||||
@dataclass
|
||||
class SecretRef:
|
||||
"""Reference to a secret key."""
|
||||
|
||||
key: str # The key name (could be lowercase secret name or uppercase env var name)
|
||||
env_var_name: Optional[str] = None # Optional explicit environment variable name
|
||||
|
||||
@property
|
||||
def safe_name(self) -> str:
|
||||
"""Transform key to lowercase with dashes for Kubernetes secret name."""
|
||||
return _safe_name(self.key)
|
||||
|
||||
@property
|
||||
def env_name(self) -> str:
|
||||
"""Get the environment variable name (uppercase with underscores)."""
|
||||
# If env_var_name is explicitly set, use it
|
||||
if self.env_var_name:
|
||||
return self.env_var_name
|
||||
# Otherwise, transform the key to uppercase with underscores
|
||||
return self.key.upper().replace('-', '_')
|
||||
|
||||
def to_env_var(self) -> k8s.V1EnvVar:
|
||||
"""Generate Kubernetes V1EnvVar for this secret reference."""
|
||||
# TODO we just store a single value inside of each ref, which is less efficient;
|
||||
# we can improve this by grouping multiple keys into a single secret
|
||||
|
||||
return k8s.V1EnvVar(
|
||||
name=self.env_name, # Use uppercase env var name
|
||||
value_from=k8s.V1EnvVarSource(
|
||||
secret_key_ref=k8s.V1SecretKeySelector(
|
||||
name=self.safe_name, # Use safe name for Kubernetes secret name
|
||||
key=self.env_name, # Use uppercase key within the secret data
|
||||
)
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Secret(BaseModel):
|
||||
"""Model-style interface for Kubernetes Secrets."""
|
||||
|
||||
# Configuration attributes (required)
|
||||
name: str
|
||||
namespace: str
|
||||
|
||||
# Optional configuration attributes
|
||||
secret_type: str = "Opaque"
|
||||
data: dict[str, str] = field(default_factory=dict) # Plain text data that will be base64 encoded
|
||||
string_data: dict[str, str] = field(default_factory=dict) # Kubernetes handles encoding
|
||||
labels: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def safe_name(self) -> str:
|
||||
"""Transform name to lowercase with dashes for Kubernetes secret name."""
|
||||
return _safe_name(self.name)
|
||||
|
||||
# Metadata attributes (populated from k8s data)
|
||||
uid: Optional[str] = None
|
||||
metadata: Optional[k8s.V1ObjectMeta] = None
|
||||
creation_timestamp: Optional[str] = None
|
||||
deletion_timestamp: Optional[str] = None
|
||||
|
||||
def to_k8s_secret(self) -> k8s.V1Secret:
|
||||
"""Convert to Kubernetes V1Secret object for API calls."""
|
||||
default_labels = {"app": self.name}
|
||||
|
||||
# Encode data to base64 bytes
|
||||
encoded_data = None
|
||||
if self.data:
|
||||
encoded_data = {key: _encode(value) for key, value in self.data.items()}
|
||||
|
||||
return k8s.V1Secret(
|
||||
api_version="v1",
|
||||
kind="Secret",
|
||||
metadata=k8s.V1ObjectMeta(
|
||||
name=self.safe_name,
|
||||
namespace=self.namespace,
|
||||
labels={**default_labels, **self.labels},
|
||||
),
|
||||
type=self.secret_type,
|
||||
data=encoded_data,
|
||||
string_data=self.string_data if self.string_data else None,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_k8s_data(cls, data: k8s.V1Secret) -> Secret:
|
||||
"""Create a Secret instance from Kubernetes API data."""
|
||||
return cls(
|
||||
name=data.metadata.name,
|
||||
namespace=data.metadata.namespace,
|
||||
secret_type=data.type or "Opaque",
|
||||
data={}, # Don't expose the raw data for security
|
||||
string_data={}, # Don't expose the raw data for security
|
||||
labels=data.metadata.labels or {},
|
||||
uid=data.metadata.uid,
|
||||
metadata=data.metadata,
|
||||
creation_timestamp=data.metadata.creation_timestamp,
|
||||
deletion_timestamp=data.metadata.deletion_timestamp,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get(cls, name: str, namespace: str, label_selector: str = None) -> Optional[Secret]:
|
||||
"""Get a Secret by name with optional label selector validation.
|
||||
|
||||
Args:
|
||||
name: Secret name
|
||||
namespace: Kubernetes namespace
|
||||
label_selector: Optional label selector to validate the secret
|
||||
|
||||
Returns:
|
||||
Secret if found and matches label selector, None otherwise
|
||||
"""
|
||||
safe_name = _safe_name(name)
|
||||
try:
|
||||
if label_selector:
|
||||
# Use list API with field selector for name and label selector
|
||||
field_selector = f"metadata.name={safe_name}"
|
||||
result = cls.client.core.list_namespaced_secret(
|
||||
namespace=namespace, field_selector=field_selector, label_selector=label_selector
|
||||
)
|
||||
if result.items:
|
||||
return cls.from_k8s_data(result.items[0])
|
||||
return None
|
||||
else:
|
||||
# Use direct read API when no label selector needed
|
||||
k8s_secret = cls.client.core.read_namespaced_secret(name=safe_name, namespace=namespace)
|
||||
return cls.from_k8s_data(k8s_secret)
|
||||
except ApiException as e:
|
||||
logger.debug(f"Get Secret {name} returned empty (status {e.status})")
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def filter(cls, namespace: str, **kwargs) -> list[Secret]:
|
||||
"""Filter Secrets in the namespace."""
|
||||
try:
|
||||
result = cls.client.core.list_namespaced_secret(namespace=namespace, **kwargs)
|
||||
return [cls.from_k8s_data(item) for item in result.items]
|
||||
except ApiException as e:
|
||||
logger.debug(f"Filter Secrets returned empty (status {e.status})")
|
||||
return []
|
||||
|
||||
def delete(self) -> bool:
|
||||
"""Delete this Secret."""
|
||||
try:
|
||||
self.client.core.delete_namespaced_secret(name=self.safe_name, namespace=self.namespace)
|
||||
return True
|
||||
except ApiException as e:
|
||||
logger.debug(f"Delete Secret {self.name} failed (status {e.status})")
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def delete_by_name(cls, name: str, namespace: str) -> bool:
|
||||
"""Delete a Secret by name (for CLI usage)."""
|
||||
safe_name = _safe_name(name)
|
||||
try:
|
||||
cls.client.core.delete_namespaced_secret(name=safe_name, namespace=namespace)
|
||||
return True
|
||||
except ApiException as e:
|
||||
logger.debug(f"Delete Secret {name} failed (status {e.status})")
|
||||
return False
|
||||
|
||||
def create(self) -> Secret:
|
||||
"""Create this Secret in the cluster."""
|
||||
try:
|
||||
k8s_secret = self.client.core.create_namespaced_secret(
|
||||
body=self.to_k8s_secret(),
|
||||
namespace=self.namespace,
|
||||
)
|
||||
return self.from_k8s_data(k8s_secret)
|
||||
except ApiException as e:
|
||||
logger.debug(f"Create Secret failed (status {e.status})")
|
||||
raise
|
||||
|
||||
def get_value(self, key: str) -> Optional[str]:
|
||||
"""Get a decoded value from the Secret data (requires fetching from cluster)."""
|
||||
try:
|
||||
k8s_secret = self.client.core.read_namespaced_secret(
|
||||
name=self.safe_name, namespace=self.namespace
|
||||
)
|
||||
if k8s_secret.data and key in k8s_secret.data:
|
||||
return _decode_str(k8s_secret.data[key])
|
||||
except ApiException:
|
||||
pass
|
||||
return None
|
||||
|
||||
def get_binary_value(self, key: str) -> Optional[bytes]:
|
||||
"""Get a binary value from the Secret data (requires fetching from cluster)."""
|
||||
try:
|
||||
k8s_secret = self.client.core.read_namespaced_secret(
|
||||
name=self.safe_name, namespace=self.namespace
|
||||
)
|
||||
if k8s_secret.data and key in k8s_secret.data:
|
||||
return _decode_bytes(k8s_secret.data[key])
|
||||
except ApiException:
|
||||
pass
|
||||
return None
|
||||
@@ -0,0 +1,305 @@
|
||||
from __future__ import annotations
|
||||
from typing import Optional
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from kubernetes import client as k8s # type: ignore
|
||||
from kubernetes.client.rest import ApiException # type: ignore
|
||||
|
||||
from .base import KubernetesResourceWrapper
|
||||
from jockey.log import logger
|
||||
from jockey.environment import ALB_SHARED_GROUP_NAME
|
||||
|
||||
|
||||
@dataclass
|
||||
class ServiceConfig:
|
||||
"""Configuration for creating Kubernetes services."""
|
||||
|
||||
name: str
|
||||
port: int
|
||||
target_port: Optional[int] = None
|
||||
service_type: str = "ClusterIP" # ClusterIP, NodePort, LoadBalancer
|
||||
selector: dict[str, str] = field(default_factory=dict)
|
||||
labels: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
"""Set default values after initialization."""
|
||||
if self.target_port is None:
|
||||
self.target_port = self.port
|
||||
if not self.selector:
|
||||
self.selector = {"app": self.name}
|
||||
|
||||
def to_k8s_service(self, namespace: str) -> k8s.V1Service:
|
||||
"""Convert config to Kubernetes V1Service object."""
|
||||
default_labels = {"app": self.name}
|
||||
# default_annotations = {
|
||||
# "alb.ingress.kubernetes.io/target-group-attributes": "deregistration_delay.timeout_seconds=30",
|
||||
# "alb.ingress.kubernetes.io/healthcheck-path": "/health",
|
||||
# "alb.ingress.kubernetes.io/healthcheck-interval-seconds": "10",
|
||||
# "alb.ingress.kubernetes.io/healthcheck-timeout-seconds": "5",
|
||||
# "alb.ingress.kubernetes.io/healthy-threshold-count": "2",
|
||||
# "alb.ingress.kubernetes.io/unhealthy-threshold-count": "3",
|
||||
# }
|
||||
|
||||
return k8s.V1Service(
|
||||
api_version="v1",
|
||||
kind="Service",
|
||||
metadata=k8s.V1ObjectMeta(
|
||||
name=self.name,
|
||||
namespace=namespace,
|
||||
labels={**default_labels, **self.labels},
|
||||
# annotations=default_annotations,
|
||||
),
|
||||
spec=k8s.V1ServiceSpec(
|
||||
selector=self.selector,
|
||||
ports=[k8s.V1ServicePort(port=self.port, target_port=self.target_port)],
|
||||
type=self.service_type,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class Service(KubernetesResourceWrapper):
|
||||
"""Model-style interface for Kubernetes services."""
|
||||
|
||||
@classmethod
|
||||
def get(cls, name: str, namespace: str) -> Optional[Service]:
|
||||
"""Get a service by name."""
|
||||
try:
|
||||
return cls(cls.client.core.read_namespaced_service(name=name, namespace=namespace))
|
||||
except ApiException as e:
|
||||
logger.debug(f"Get service {name} returned empty (status {e.status})")
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def filter(cls, namespace: str, **kwargs) -> list[Service]:
|
||||
"""Filter services in the namespace."""
|
||||
try:
|
||||
result = cls.client.core.list_namespaced_service(namespace=namespace, **kwargs)
|
||||
return [cls(item) for item in result.items]
|
||||
except ApiException as e:
|
||||
logger.debug(f"Filter services returned empty (status {e.status})")
|
||||
return []
|
||||
|
||||
@classmethod
|
||||
def create(cls, namespace: str, body: ServiceConfig) -> Service:
|
||||
"""Create a new service from ServiceConfig."""
|
||||
try:
|
||||
return cls(
|
||||
cls.client.core.create_namespaced_service(
|
||||
body=body.to_k8s_service(namespace),
|
||||
namespace=namespace,
|
||||
)
|
||||
)
|
||||
except ApiException as e:
|
||||
logger.debug(f"Create service failed (status {e.status})")
|
||||
raise
|
||||
|
||||
@property
|
||||
def service_type(self) -> Optional[str]:
|
||||
"""Get the service type (ClusterIP, NodePort, LoadBalancer)."""
|
||||
return str(self.data.spec.type) or None
|
||||
|
||||
@property
|
||||
def cluster_ip(self) -> Optional[str]:
|
||||
"""Get the cluster IP address."""
|
||||
return str(self.data.spec.cluster_ip) or None
|
||||
|
||||
@property
|
||||
def external_ips(self) -> list[str]:
|
||||
"""Get external IP addresses."""
|
||||
return self.data.spec.external_i_ps or []
|
||||
|
||||
@property
|
||||
def ports(self) -> list[dict[str, Optional[int]]]:
|
||||
"""Get service ports."""
|
||||
return [
|
||||
{
|
||||
"name": port.name,
|
||||
"port": port.port,
|
||||
"target_port": port.target_port,
|
||||
"node_port": port.node_port,
|
||||
}
|
||||
for port in self.data.spec.ports
|
||||
]
|
||||
|
||||
@property
|
||||
def selector(self) -> dict[str, str]:
|
||||
"""Get the service selector labels."""
|
||||
return self.data.spec.selector or {}
|
||||
|
||||
|
||||
@dataclass
|
||||
class IngressConfig:
|
||||
"""Configuration for creating Kubernetes ingress with ALB."""
|
||||
|
||||
name: str
|
||||
hostname: str # e.g., "app1.yourdomain.com" or "{uuid}.apps.yourdomain.com"
|
||||
service_name: str
|
||||
service_port: int
|
||||
path: str = "/"
|
||||
path_type: str = "Prefix"
|
||||
labels: dict[str, str] = field(default_factory=dict)
|
||||
annotations: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
"""Set default ALB annotations."""
|
||||
default_annotations = {
|
||||
"kubernetes.io/ingress.class": "alb",
|
||||
"alb.ingress.kubernetes.io/scheme": "internet-facing",
|
||||
"alb.ingress.kubernetes.io/target-type": "ip",
|
||||
"alb.ingress.kubernetes.io/listen-ports": '[{"HTTP": 80}, {"HTTPS": 443}]',
|
||||
"alb.ingress.kubernetes.io/ssl-redirect": "443",
|
||||
"alb.ingress.kubernetes.io/group.name": ALB_SHARED_GROUP_NAME, # Use shared ALB for all deployments
|
||||
"alb.ingress.kubernetes.io/tags": f"deployment={self.name},hostname={self.hostname}", # Tag for routing
|
||||
"alb.ingress.kubernetes.io/target-group-attributes": "deregistration_delay.timeout_seconds=30", # Fast deregistration
|
||||
}
|
||||
self.annotations = {**default_annotations, **self.annotations}
|
||||
|
||||
def to_k8s_ingress(self, namespace: str) -> k8s.V1Ingress:
|
||||
"""Convert config to Kubernetes V1Ingress object."""
|
||||
default_labels = {"app": self.name}
|
||||
|
||||
return k8s.V1Ingress(
|
||||
api_version="networking.k8s.io/v1",
|
||||
kind="Ingress",
|
||||
metadata=k8s.V1ObjectMeta(
|
||||
name=self.name,
|
||||
namespace=namespace,
|
||||
labels={**default_labels, **self.labels},
|
||||
annotations=self.annotations,
|
||||
),
|
||||
spec=k8s.V1IngressSpec(
|
||||
rules=[
|
||||
k8s.V1IngressRule(
|
||||
host=self.hostname,
|
||||
http=k8s.V1HTTPIngressRuleValue(
|
||||
paths=[
|
||||
k8s.V1HTTPIngressPath(
|
||||
path=self.path,
|
||||
path_type=self.path_type,
|
||||
backend=k8s.V1IngressBackend(
|
||||
service=k8s.V1IngressServiceBackend(
|
||||
name=self.service_name,
|
||||
port=k8s.V1ServiceBackendPort(number=self.service_port),
|
||||
)
|
||||
),
|
||||
)
|
||||
]
|
||||
),
|
||||
)
|
||||
]
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class IngressService(Service):
|
||||
"""Service that automatically creates ingress for internet access."""
|
||||
|
||||
@classmethod
|
||||
def create_with_ingress(
|
||||
cls,
|
||||
namespace: str,
|
||||
service_config: ServiceConfig,
|
||||
ingress_config: IngressConfig,
|
||||
) -> tuple[Service, 'Ingress']:
|
||||
"""Create both Service and Ingress resources together."""
|
||||
# Create or get existing service
|
||||
existing_service = cls.get(service_config.name, namespace)
|
||||
if existing_service:
|
||||
logger.info(f"Using existing service: {service_config.name}")
|
||||
service = existing_service
|
||||
else:
|
||||
service = cls.create(namespace, service_config)
|
||||
|
||||
# Create or get existing ingress
|
||||
existing_ingress = Ingress.get(ingress_config.name, namespace)
|
||||
if existing_ingress:
|
||||
logger.info(f"Using existing ingress: {ingress_config.name}")
|
||||
ingress = existing_ingress
|
||||
else:
|
||||
ingress = Ingress.create(namespace, ingress_config)
|
||||
|
||||
return service, ingress
|
||||
|
||||
@classmethod
|
||||
def create_for_deployment(
|
||||
cls,
|
||||
deployment_name: str,
|
||||
namespace: str,
|
||||
hostname: str,
|
||||
port: int = 80,
|
||||
target_port: int = 8080,
|
||||
) -> tuple[Service, 'Ingress']:
|
||||
"""Convenience method to create service and ingress for a deployment."""
|
||||
# Ensure service name is DNS-1035 compliant (starts with letter, lowercase)
|
||||
service_name = f"svc-{deployment_name}"
|
||||
ingress_name = f"ing-{deployment_name}"
|
||||
|
||||
service_config = ServiceConfig(
|
||||
name=service_name,
|
||||
port=port,
|
||||
target_port=target_port,
|
||||
service_type="ClusterIP", # ALB uses ClusterIP, not LoadBalancer
|
||||
selector={"app": deployment_name},
|
||||
)
|
||||
|
||||
ingress_config = IngressConfig(
|
||||
name=ingress_name,
|
||||
hostname=hostname,
|
||||
service_name=service_name,
|
||||
service_port=port,
|
||||
)
|
||||
|
||||
return cls.create_with_ingress(namespace, service_config, ingress_config)
|
||||
|
||||
|
||||
class Ingress(KubernetesResourceWrapper):
|
||||
"""Model-style interface for Kubernetes ingress."""
|
||||
|
||||
@classmethod
|
||||
def get(cls, name: str, namespace: str) -> Optional['Ingress']:
|
||||
"""Get an ingress by name."""
|
||||
try:
|
||||
return cls(cls.client.networking.read_namespaced_ingress(name=name, namespace=namespace))
|
||||
except ApiException as e:
|
||||
logger.debug(f"Get ingress {name} returned empty (status {e.status})")
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def filter(cls, namespace: str, **kwargs) -> list['Ingress']:
|
||||
"""Filter ingresses in the namespace."""
|
||||
try:
|
||||
result = cls.client.networking.list_namespaced_ingress(namespace=namespace, **kwargs)
|
||||
return [cls(item) for item in result.items]
|
||||
except ApiException as e:
|
||||
logger.debug(f"Filter ingresses returned empty (status {e.status})")
|
||||
return []
|
||||
|
||||
@classmethod
|
||||
def create(cls, namespace: str, body: IngressConfig) -> 'Ingress':
|
||||
"""Create a new ingress from IngressConfig."""
|
||||
try:
|
||||
return cls(
|
||||
cls.client.networking.create_namespaced_ingress(
|
||||
body=body.to_k8s_ingress(namespace),
|
||||
namespace=namespace,
|
||||
)
|
||||
)
|
||||
except ApiException as e:
|
||||
logger.debug(f"Create ingress failed (status {e.status})")
|
||||
raise
|
||||
|
||||
@property
|
||||
def hostname(self) -> Optional[str]:
|
||||
"""Get the primary hostname for this ingress."""
|
||||
if self.data.spec.rules:
|
||||
return self.data.spec.rules[0].host
|
||||
return None
|
||||
|
||||
@property
|
||||
def load_balancer_hostname(self) -> Optional[str]:
|
||||
"""Get the ALB hostname from ingress status."""
|
||||
if self.data.status and self.data.status.load_balancer:
|
||||
ingress_list = self.data.status.load_balancer.ingress
|
||||
if ingress_list:
|
||||
return ingress_list[0].hostname
|
||||
return None
|
||||
@@ -0,0 +1,183 @@
|
||||
from __future__ import annotations
|
||||
from typing import Optional, Union, TypedDict
|
||||
from enum import Enum
|
||||
from dataclasses import dataclass, field, asdict
|
||||
from uuid import UUID
|
||||
from pathlib import Path
|
||||
from jockey.environment import JOCKEY_PATH, DEPLOYMENT_DOMAIN
|
||||
|
||||
|
||||
AGENTOPS_API_KEY_VARNAME = "AGENTOPS_API_KEY"
|
||||
|
||||
# code in this directory will get deployed to the container if it uses `build_files`
|
||||
# allow providing path explicitly because we symlink jockey in prod
|
||||
INSTANCE_BASE_PATH: Path = (Path(JOCKEY_PATH) if JOCKEY_PATH else Path(__file__).parent) / "instance"
|
||||
|
||||
|
||||
def _get_instance_build_files() -> dict[str, str]:
|
||||
"""List all of the file paths in the `instance` package for syncing with the container."""
|
||||
build_files = {}
|
||||
for file_path in INSTANCE_BASE_PATH.rglob("*.py"):
|
||||
relative_path = file_path.relative_to(INSTANCE_BASE_PATH)
|
||||
build_files[f"instance/{relative_path}"] = file_path.read_text()
|
||||
|
||||
return build_files
|
||||
|
||||
|
||||
class TaskType(Enum):
|
||||
"""
|
||||
Determines how to handle a queued task.
|
||||
|
||||
BUILD: Build container image from source code.
|
||||
SERVE: Serve existing image as persistent service.
|
||||
RUN: Run existing image as one-time job.
|
||||
"""
|
||||
|
||||
BUILD = "build"
|
||||
SERVE = "serve"
|
||||
RUN = "run"
|
||||
|
||||
|
||||
@dataclass
|
||||
class DeploymentPack:
|
||||
"""
|
||||
Deployment pack configuration.
|
||||
|
||||
Allows hardcoding configuration values for a DeploymentConfig that can be referenced
|
||||
when creating an instance. Use with `DeploymentConfig.from_pack()`.
|
||||
"""
|
||||
|
||||
dockerfile_template: str
|
||||
ports: list[int]
|
||||
build_files: dict[str, str]
|
||||
|
||||
|
||||
DEPLOYMENT_PACKS: dict[str, DeploymentPack] = {
|
||||
"FASTAPI": DeploymentPack(
|
||||
# this pack expects a FastAPI application to exist in the repository and will
|
||||
# serve the existing endpoints.
|
||||
dockerfile_template='fastapi-agent',
|
||||
ports=[8000], # TODO user should be able to configure the port their API is listening on
|
||||
build_files={},
|
||||
),
|
||||
"CREWAI": DeploymentPack(
|
||||
# this pack expects a CrewAI agent to exist in the repository and will search
|
||||
# inside the watch_path for the `kickoff` method and expose it as an API endpoint.
|
||||
dockerfile_template='crewai-agent',
|
||||
ports=[8080],
|
||||
build_files=_get_instance_build_files(),
|
||||
),
|
||||
"CREWAI_JOB": DeploymentPack(
|
||||
# this pack expects a CrewAI agent to exist in the repository and will run
|
||||
# the agent directly via job_runner.py for one-time execution without API.
|
||||
dockerfile_template='crewai-job',
|
||||
ports=[], # No ports needed for job execution
|
||||
build_files=_get_instance_build_files(),
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
class SerializedDeploymentConfig(TypedDict):
|
||||
"""Type definition for serialized deployment configuration."""
|
||||
|
||||
namespace: str
|
||||
project_id: str # Serialized as string
|
||||
dockerfile_template: str
|
||||
repository_url: Optional[str]
|
||||
branch: str
|
||||
github_access_token: Optional[str]
|
||||
entrypoint: Optional[str]
|
||||
watch_path: Optional[str]
|
||||
replicas: int
|
||||
ports: list[int]
|
||||
secret_names: list[str]
|
||||
build_files: dict[str, str]
|
||||
agentops_api_key: str
|
||||
create_ingress: bool
|
||||
force_recreate: bool
|
||||
tag: str
|
||||
hostname: str
|
||||
# configmap_refs: dict[str, ConfigMapRef]
|
||||
|
||||
|
||||
@dataclass
|
||||
class DeploymentConfig:
|
||||
"""Configuration for creating and deploying an application."""
|
||||
|
||||
namespace: str # Required for multi-tenant isolation
|
||||
project_id: Union[str, UUID] # Project ID (will be normalized to string in __post_init__)
|
||||
dockerfile_template: str = "fastapi-agent"
|
||||
|
||||
# Source code configuration (optional)
|
||||
repository_url: Optional[str] = None # Git repository URL (optional)
|
||||
branch: str = "main" # Branch or commit hash to checkout
|
||||
github_access_token: Optional[str] = None # GitHub access token for private repos
|
||||
entrypoint: Optional[str] = None # Application entrypoint file
|
||||
watch_path: Optional[str] = None # Subdirectory within repo to use as working directory
|
||||
|
||||
# Deployment configuration
|
||||
replicas: int = 1
|
||||
ports: list[int] = field(default_factory=list)
|
||||
secret_names: list[str] = field(default_factory=list)
|
||||
build_files: dict[str, str] = field(default_factory=dict) # Files to make available during build
|
||||
agentops_api_key: str = "" # AgentOps API key for automatic injection
|
||||
callback_url: Optional[str] = None # Callback URL for job completion notifications
|
||||
|
||||
create_ingress: bool = True # Whether to create ingress for internet access
|
||||
force_recreate: bool = False # Whether to delete and recreate deployment instead of patching
|
||||
|
||||
# Computed fields (will be set in __post_init__ if not provided)
|
||||
tag: Optional[str] = None
|
||||
hostname: Optional[str] = None
|
||||
|
||||
def __post_init__(self):
|
||||
"""Compute derived fields after initialization."""
|
||||
self.project_id = str(self.project_id)
|
||||
|
||||
if self.tag is None:
|
||||
self.tag = self.project_id
|
||||
|
||||
if self.hostname is None:
|
||||
self.hostname = f"{self.project_id}.{DEPLOYMENT_DOMAIN}"
|
||||
|
||||
def serialize(self) -> SerializedDeploymentConfig:
|
||||
"""Serialize the deployment configuration for storage.
|
||||
|
||||
Returns:
|
||||
SerializedDeploymentConfig containing all deployment config data
|
||||
"""
|
||||
return SerializedDeploymentConfig(**asdict(self)) # type: ignore
|
||||
|
||||
@classmethod
|
||||
def from_serialized(cls, data: SerializedDeploymentConfig) -> DeploymentConfig:
|
||||
"""Create a DeploymentConfig from serialized data.
|
||||
|
||||
Args:
|
||||
data: Serialized deployment configuration data
|
||||
|
||||
Returns:
|
||||
DeploymentConfig instance
|
||||
"""
|
||||
return cls(**data)
|
||||
|
||||
@classmethod
|
||||
def from_pack(cls, pack_name: Optional[str], /, **kwargs) -> DeploymentConfig:
|
||||
"""Create a DeploymentConfig from a deployment pack name.
|
||||
|
||||
Args:
|
||||
pack_name: Deployment pack name (FASTAPI, CREWAI, CREWAI_JOB) or None for FASTAPI default
|
||||
**kwargs: Configuration parameters including namespace and project_id
|
||||
|
||||
Returns:
|
||||
DeploymentConfig with pack-specific defaults applied
|
||||
"""
|
||||
if pack_name is not None and pack_name not in DEPLOYMENT_PACKS:
|
||||
raise ValueError(f"Invalid deployment pack name: {pack_name}")
|
||||
|
||||
# default to FASTAPI for quick backwards compatibility
|
||||
# TODO enforce that pack_name is always provided
|
||||
pack = DEPLOYMENT_PACKS.get(pack_name, DEPLOYMENT_PACKS["FASTAPI"])
|
||||
config_kwargs = asdict(pack) # get defaults from the pack
|
||||
config_kwargs.update(kwargs) # override with any provided kwargs
|
||||
|
||||
return cls(**config_kwargs)
|
||||
@@ -0,0 +1,97 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
|
||||
if os.getenv("LOCAL_DEV"):
|
||||
print("Loading environment variables from .env file for local development.")
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv(BASE_DIR / ".env")
|
||||
|
||||
_kubeconfig_path = os.getenv("KUBECONFIG", "config/kubeconfig")
|
||||
if _kubeconfig_path and not os.path.isabs(_kubeconfig_path):
|
||||
# make kubeconfig path absolute if it's relative
|
||||
KUBECONFIG_PATH: str = str(BASE_DIR / _kubeconfig_path)
|
||||
else:
|
||||
KUBECONFIG_PATH = _kubeconfig_path or ""
|
||||
|
||||
JOCKEY_PATH = os.getenv("JOCKEY_PATH")
|
||||
|
||||
KUBERNETES_INTERNAL_NAMESPACE = os.getenv("KUBERNETES_INTERNAL_NAMESPACE", "agentops-deploy")
|
||||
KUBERNETES_CONTEXT = os.getenv("KUBERNETES_CONTEXT")
|
||||
BUILDER_NAMESPACE = os.getenv("BUILDER_NAMESPACE", "builder")
|
||||
|
||||
# AWS and EKS configuration
|
||||
EKS_CLUSTER_NAME = os.getenv("EKS_CLUSTER_NAME")
|
||||
AWS_REGION = os.getenv("AWS_REGION")
|
||||
AWS_PROFILE = os.getenv("AWS_PROFILE")
|
||||
|
||||
# S3 configuration for build cache
|
||||
S3_BUCKET_NAME = os.getenv("S3_BUCKET_NAME", "agentops-deployment-storage")
|
||||
S3_BUILD_CACHE_PREFIX = os.getenv("S3_BUILD_CACHE_PREFIX", "build-cache")
|
||||
|
||||
# Deployment configuration
|
||||
DEPLOYMENT_NAME = os.getenv("DEPLOYMENT_NAME", "agentops")
|
||||
IMAGE_REGISTRY = os.getenv("IMAGE_REGISTRY", "315680545607.dkr.ecr.us-west-1.amazonaws.com")
|
||||
IMAGE_REPOSITORY = os.getenv("IMAGE_REPOSITORY", "hosting/agent-images")
|
||||
IMAGE_TAG = os.getenv("IMAGE_TAG", "latest")
|
||||
AWS_DEFAULT_REGION = os.getenv("AWS_DEFAULT_REGION", "us-west-1")
|
||||
|
||||
# Service configuration
|
||||
SERVICE_PORT = int(os.getenv("SERVICE_PORT", "8000"))
|
||||
SERVICE_TYPE = os.getenv("SERVICE_TYPE", "ClusterIP")
|
||||
|
||||
# Resource limits
|
||||
CPU_LIMIT = os.getenv("CPU_LIMIT", "1000m")
|
||||
MEMORY_LIMIT = os.getenv("MEMORY_LIMIT", "1Gi")
|
||||
CPU_REQUEST = os.getenv("CPU_REQUEST", "100m")
|
||||
MEMORY_REQUEST = os.getenv("MEMORY_REQUEST", "128Mi")
|
||||
|
||||
# Builder-specific resource limits
|
||||
BUILDER_CPU_LIMIT = os.getenv("BUILDER_CPU_LIMIT", "2000m")
|
||||
BUILDER_MEMORY_LIMIT = os.getenv("BUILDER_MEMORY_LIMIT", "4Gi")
|
||||
BUILDER_CPU_REQUEST = os.getenv("BUILDER_CPU_REQUEST", "1000m")
|
||||
BUILDER_MEMORY_REQUEST = os.getenv("BUILDER_MEMORY_REQUEST", "2Gi")
|
||||
|
||||
# Replica configuration
|
||||
REPLICA_COUNT = int(os.getenv("REPLICA_COUNT", "1"))
|
||||
MAX_REPLICAS = int(os.getenv("MAX_REPLICAS", "10"))
|
||||
MIN_REPLICAS = int(os.getenv("MIN_REPLICAS", "1"))
|
||||
|
||||
# Health check configuration
|
||||
HEALTH_CHECK_PATH = os.getenv("HEALTH_CHECK_PATH", "/health")
|
||||
READINESS_PROBE_PATH = os.getenv("READINESS_PROBE_PATH", "/health")
|
||||
LIVENESS_PROBE_PATH = os.getenv("LIVENESS_PROBE_PATH", "/health")
|
||||
|
||||
# Working directory configuration
|
||||
WORKING_DIRECTORY = os.getenv("JOCKEY_WORKING_DIR", "/tmp/jockey")
|
||||
|
||||
# Redis configuration
|
||||
REDIS_HOST = os.getenv("DEPLOY_REDIS_HOST", "localhost")
|
||||
REDIS_PORT = int(os.getenv("DEPLOY_REDIS_PORT", "6379"))
|
||||
REDIS_DB = int(os.getenv("DEPLOY_REDIS_DB", "0"))
|
||||
REDIS_USER = os.getenv("DEPLOY_REDIS_USER", "default")
|
||||
REDIS_PASSWORD = os.getenv("DEPLOY_REDIS_PASSWORD", "")
|
||||
|
||||
# Worker configuration
|
||||
WORKER_POLL_INTERVAL = int(os.getenv("WORKER_POLL_INTERVAL", "5"))
|
||||
|
||||
# Docker configuration
|
||||
DOCKER_HOST = os.getenv("DOCKER_HOST") # If not set, uses local Docker daemon
|
||||
|
||||
# Environment-specific settings
|
||||
ENVIRONMENT = os.getenv("ENVIRONMENT", "development")
|
||||
DEBUG = os.getenv("DEBUG", "false").lower() in ("true", "1", "yes")
|
||||
LOG_LEVEL = os.getenv("JOCKEY_LOG_LEVEL", "INFO").upper()
|
||||
|
||||
# Ingress configuration
|
||||
INGRESS_ENABLED = os.getenv("INGRESS_ENABLED", "false").lower() in ("true", "1", "yes")
|
||||
INGRESS_HOST = os.getenv("INGRESS_HOST")
|
||||
INGRESS_CLASS = os.getenv("INGRESS_CLASS", "nginx")
|
||||
|
||||
# ALB configuration
|
||||
ALB_SHARED_GROUP_NAME = os.getenv("ALB_SHARED_GROUP_NAME", "alb-deployments")
|
||||
|
||||
# Domain configuration for user deployments
|
||||
DEPLOYMENT_DOMAIN = os.getenv("DEPLOYMENT_DOMAIN", "deploy.agentops.ai")
|
||||
@@ -0,0 +1,338 @@
|
||||
from typing import Optional, Generator, Union
|
||||
from datetime import datetime
|
||||
import json
|
||||
from kubernetes import client as k8s
|
||||
from jockey.log import logger
|
||||
from jockey.environment import BUILDER_NAMESPACE
|
||||
from jockey.config import DeploymentConfig, AGENTOPS_API_KEY_VARNAME
|
||||
from jockey.secret import create_secret, delete_secret
|
||||
from jockey.backend.models.base import BaseModel
|
||||
from jockey.backend.models.image import Image, BuildEvent
|
||||
from jockey.backend.models.deployment import Deployment, DeploymentEvent
|
||||
from jockey.backend.models.job import Job, JobEvent
|
||||
from jockey.backend.models.repository import Repository, RepositoryEvent
|
||||
from jockey.backend.models.secret import SecretRef, Secret
|
||||
from jockey.backend.models.service import IngressService
|
||||
|
||||
|
||||
AggregatedEvent = Union[RepositoryEvent, BuildEvent, DeploymentEvent, JobEvent]
|
||||
|
||||
|
||||
def ensure_agentops_api_key_exists(config: DeploymentConfig) -> None:
|
||||
# API key can change between deployments, so always sync it.
|
||||
if not config.agentops_api_key:
|
||||
logger.debug("No agentops API key provided, skipping")
|
||||
return None
|
||||
|
||||
delete_secret(
|
||||
config.namespace,
|
||||
config.project_id,
|
||||
AGENTOPS_API_KEY_VARNAME,
|
||||
)
|
||||
create_secret(
|
||||
config.namespace,
|
||||
config.project_id,
|
||||
AGENTOPS_API_KEY_VARNAME,
|
||||
config.agentops_api_key,
|
||||
)
|
||||
|
||||
|
||||
def ensure_namespace_exists(namespace: str) -> None:
|
||||
"""Ensure a Kubernetes namespace exists, creating it if necessary."""
|
||||
|
||||
try:
|
||||
# Check if namespace exists
|
||||
BaseModel.client.core.read_namespace(name=namespace)
|
||||
logger.debug(f"Namespace {namespace} already exists")
|
||||
except Exception:
|
||||
# Namespace doesn't exist, create it
|
||||
logger.info(f"Creating namespace: {namespace}")
|
||||
namespace_obj = k8s.V1Namespace(metadata=k8s.V1ObjectMeta(name=namespace))
|
||||
BaseModel.client.core.create_namespace(body=namespace_obj)
|
||||
logger.info(f"Created namespace: {namespace}")
|
||||
|
||||
|
||||
def execute_build(
|
||||
config: DeploymentConfig,
|
||||
job_id: Optional[str] = None,
|
||||
) -> Generator[AggregatedEvent, None, Optional[Image]]:
|
||||
"""Build image only without deployment.
|
||||
|
||||
This function only builds and pushes the image, without creating any
|
||||
Kubernetes deployment resources.
|
||||
|
||||
Args:
|
||||
config: Deployment configuration (only build-related fields used)
|
||||
job_id: Optional job ID for tracking
|
||||
|
||||
Yields:
|
||||
BaseEvent: Progress events during the build process
|
||||
|
||||
Returns:
|
||||
Image: The built and pushed image
|
||||
"""
|
||||
# Ensure the builder namespace exists
|
||||
ensure_namespace_exists(BUILDER_NAMESPACE) # Builder namespace for image builds
|
||||
|
||||
repository = Repository(
|
||||
url=config.repository_url,
|
||||
namespace=config.namespace,
|
||||
branch=config.branch,
|
||||
github_access_token=config.github_access_token,
|
||||
)
|
||||
# repository checkout happens inside the builder image.
|
||||
|
||||
image = Image(
|
||||
name=f"hosting/{config.project_id}", # Use project_id as repository name
|
||||
tag="latest", # Always use latest tag for newest version
|
||||
namespace=BUILDER_NAMESPACE, # Use dedicated builder namespace for all builds
|
||||
repository_name=repository.repository_name if repository else None,
|
||||
dockerfile_template=config.dockerfile_template,
|
||||
build_files=config.build_files,
|
||||
dockerfile_vars={
|
||||
'watch_path': config.watch_path,
|
||||
'entrypoint': config.entrypoint,
|
||||
'repository_url': repository._get_authenticated_url(),
|
||||
},
|
||||
)
|
||||
|
||||
yield from image.build(job_id=job_id)
|
||||
return image
|
||||
|
||||
|
||||
def execute_serve(
|
||||
config: DeploymentConfig,
|
||||
job_id: Optional[str] = None,
|
||||
) -> Generator[AggregatedEvent, None, Optional[Deployment]]:
|
||||
"""Build and deploy with detailed progress events.
|
||||
|
||||
This function yields events during the build, push, and deployment process,
|
||||
allowing for real-time progress monitoring.
|
||||
|
||||
Args:
|
||||
config: Deployment configuration
|
||||
|
||||
Yields:
|
||||
BaseEvent: Progress events during the process
|
||||
Deployment: The final deployed Kubernetes deployment
|
||||
|
||||
Example:
|
||||
config = DeploymentConfig(namespace="default", ports=[8080])
|
||||
|
||||
deployment = None
|
||||
for event in build_and_deploy_with_events(config):
|
||||
if isinstance(event, BaseEvent):
|
||||
print(f"{event.event_type}: {event.message}")
|
||||
elif isinstance(event, Deployment):
|
||||
deployment = event
|
||||
print(f"Final deployment: {deployment.name}")
|
||||
"""
|
||||
ensure_namespace_exists(config.namespace)
|
||||
|
||||
if AGENTOPS_API_KEY_VARNAME not in config.secret_names:
|
||||
ensure_agentops_api_key_exists(config)
|
||||
config.secret_names.append(AGENTOPS_API_KEY_VARNAME)
|
||||
|
||||
image = yield from execute_build(config, job_id)
|
||||
if not image:
|
||||
raise Exception("Failed to build image")
|
||||
|
||||
deployment = Deployment(
|
||||
name=str(config.project_id),
|
||||
image_url=image.url,
|
||||
namespace=config.namespace,
|
||||
replicas=config.replicas,
|
||||
ports=config.ports,
|
||||
secret_refs=[SecretRef(key=name) for name in config.secret_names],
|
||||
# configmap_refs=config.configmap_refs,
|
||||
)
|
||||
|
||||
final_deployment = yield from deployment.deploy_or_upgrade(force_recreate=config.force_recreate)
|
||||
|
||||
if config.create_ingress and config.hostname:
|
||||
logger.info(f"Creating ingress for hostname: {config.hostname}")
|
||||
try:
|
||||
service, ingress = IngressService.create_for_deployment(
|
||||
deployment_name=deployment.name,
|
||||
namespace=config.namespace,
|
||||
hostname=config.hostname,
|
||||
port=80,
|
||||
target_port=config.ports[0] if config.ports else 8080,
|
||||
)
|
||||
logger.info(f"Created ingress: {ingress.hostname}")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to create ingress: {e}")
|
||||
# Don't fail the deployment if ingress creation fails
|
||||
|
||||
return final_deployment
|
||||
|
||||
|
||||
def execute_run(
|
||||
config: DeploymentConfig,
|
||||
input_data: dict,
|
||||
job_id: Optional[str] = None,
|
||||
) -> Generator[AggregatedEvent, None, Optional[str]]:
|
||||
"""Run a job using the latest existing image.
|
||||
|
||||
This function uses the existing latest image and runs it as a Kubernetes Job
|
||||
that executes once and terminates. Does not build a new image.
|
||||
|
||||
Args:
|
||||
config: Deployment configuration
|
||||
input_data: Input data to pass to the agent
|
||||
job_id: Optional job ID for tracking
|
||||
|
||||
Yields:
|
||||
BaseEvent: Progress events during the job execution process
|
||||
|
||||
Returns:
|
||||
str: Job logs/output from the execution
|
||||
"""
|
||||
# Ensure the project namespace exists for job execution
|
||||
ensure_namespace_exists(config.namespace)
|
||||
|
||||
if AGENTOPS_API_KEY_VARNAME not in config.secret_names:
|
||||
ensure_agentops_api_key_exists(config)
|
||||
config.secret_names.append(AGENTOPS_API_KEY_VARNAME)
|
||||
|
||||
image = Image(
|
||||
name=f"hosting/{config.project_id}",
|
||||
tag="latest",
|
||||
namespace=BUILDER_NAMESPACE,
|
||||
dockerfile_template=config.dockerfile_template,
|
||||
)
|
||||
|
||||
# Create job name with timestamp to ensure uniqueness
|
||||
timestamp = datetime.utcnow().strftime("%Y%m%d-%H%M%S")
|
||||
job_name = f"{config.project_id}-{timestamp}"
|
||||
|
||||
env_vars = {
|
||||
"INPUT_DATA": json.dumps(input_data), # Pass input data as JSON string
|
||||
"JOB_ID": job_id or "unknown",
|
||||
"CALLBACK_URL": config.callback_url or "",
|
||||
}
|
||||
|
||||
job = Job(
|
||||
name=job_name,
|
||||
image_url=image.url,
|
||||
namespace=config.namespace,
|
||||
command=["python", "/app/instance/job_runner.py"], # Use job runner entrypoint
|
||||
env_vars=env_vars,
|
||||
secret_refs=[SecretRef(key=name) for name in config.secret_names],
|
||||
# Jobs should complete relatively quickly for agent execution
|
||||
ttl_seconds_after_finished=1800, # Clean up after 30 minutes
|
||||
)
|
||||
|
||||
final_job = yield from job.create_and_watch()
|
||||
|
||||
if final_job:
|
||||
logs = job.get_logs()
|
||||
return logs
|
||||
else:
|
||||
raise Exception("Job did not complete successfully")
|
||||
|
||||
|
||||
def delete_deployment_resources(namespace: str, deployment_name: str, deployment_id: str) -> bool:
|
||||
"""Delete all Kubernetes resources associated with a deployment.
|
||||
|
||||
This function removes:
|
||||
- The deployment itself
|
||||
- Associated services
|
||||
- Associated ingress resources
|
||||
- Associated secrets
|
||||
- Any pods created by the deployment (handled automatically by k8s)
|
||||
|
||||
Args:
|
||||
namespace: Kubernetes namespace
|
||||
deployment_name: Name of the deployment to delete
|
||||
deployment_id: Deployment ID for finding associated resources
|
||||
|
||||
Returns:
|
||||
bool: True if deletion was successful or no resources were found, False otherwise
|
||||
"""
|
||||
from jockey.backend.models.deployment import Deployment
|
||||
from jockey.backend.models.service import Service, Ingress
|
||||
from kubernetes.client.rest import ApiException
|
||||
|
||||
success = True
|
||||
errors = []
|
||||
resources_found = False
|
||||
|
||||
try:
|
||||
# 1. Check if deployment exists and delete it
|
||||
existing_deployment = Deployment.get(name=deployment_name, namespace=namespace)
|
||||
if existing_deployment:
|
||||
resources_found = True
|
||||
logger.info(f"Deleting deployment: {deployment_name}")
|
||||
if not Deployment.delete_by_name(name=deployment_name, namespace=namespace):
|
||||
errors.append(f"Failed to delete deployment {deployment_name}")
|
||||
success = False
|
||||
else:
|
||||
logger.info(f"No deployment found: {deployment_name}")
|
||||
|
||||
# 2. Delete associated services
|
||||
services = Service.filter(namespace=namespace, label_selector=f"app={deployment_name}")
|
||||
if services:
|
||||
resources_found = True
|
||||
logger.info(f"Deleting {len(services)} services for deployment: {deployment_name}")
|
||||
for service in services:
|
||||
try:
|
||||
service.client.core.delete_namespaced_service(name=service.name, namespace=namespace)
|
||||
logger.info(f"Deleted service: {service.name}")
|
||||
except ApiException as e:
|
||||
if e.status != 404: # Ignore if already deleted
|
||||
errors.append(f"Failed to delete service {service.name}: {e}")
|
||||
success = False
|
||||
else:
|
||||
logger.info(f"No services found for deployment: {deployment_name}")
|
||||
|
||||
# 3. Delete associated ingress resources
|
||||
ingresses = Ingress.filter(namespace=namespace, label_selector=f"app={deployment_name}")
|
||||
if ingresses:
|
||||
resources_found = True
|
||||
logger.info(f"Deleting {len(ingresses)} ingress resources for deployment: {deployment_name}")
|
||||
for ingress in ingresses:
|
||||
try:
|
||||
ingress.client.networking.delete_namespaced_ingress(
|
||||
name=ingress.name, namespace=namespace
|
||||
)
|
||||
logger.info(f"Deleted ingress: {ingress.name}")
|
||||
except ApiException as e:
|
||||
if e.status != 404: # Ignore if already deleted
|
||||
errors.append(f"Failed to delete ingress {ingress.name}: {e}")
|
||||
success = False
|
||||
else:
|
||||
logger.info(f"No ingress resources found for deployment: {deployment_name}")
|
||||
|
||||
# 4. Delete associated secrets
|
||||
secrets = Secret.filter(namespace=namespace, label_selector=f"deployment={deployment_id}")
|
||||
if secrets:
|
||||
resources_found = True
|
||||
logger.info(f"Deleting {len(secrets)} secrets for deployment: {deployment_id}")
|
||||
for secret in secrets:
|
||||
try:
|
||||
secret.client.core.delete_namespaced_secret(name=secret.name, namespace=namespace)
|
||||
logger.info(f"Deleted secret: {secret.name}")
|
||||
except ApiException as e:
|
||||
if e.status != 404: # Ignore if already deleted
|
||||
errors.append(f"Failed to delete secret {secret.name}: {e}")
|
||||
success = False
|
||||
else:
|
||||
logger.info(f"No secrets found for deployment: {deployment_id}")
|
||||
|
||||
if not resources_found:
|
||||
logger.info(
|
||||
f"No Kubernetes resources found for deployment {deployment_name} - this is normal for projects that were never deployed"
|
||||
)
|
||||
return True # Consider this a success since there's nothing to delete
|
||||
|
||||
if errors:
|
||||
logger.warning(f"Deletion completed with errors: {errors}")
|
||||
else:
|
||||
logger.info(f"Successfully deleted all resources for deployment {deployment_name}")
|
||||
|
||||
return success
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error during deployment deletion: {e}")
|
||||
return False
|
||||
@@ -0,0 +1,69 @@
|
||||
from __future__ import annotations
|
||||
from typing import Literal
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
|
||||
def standardize_uuid(value: str | UUID) -> str:
|
||||
return str(value)
|
||||
|
||||
|
||||
def standardize_name(name: str) -> str:
|
||||
"""Standardize Kubernetes resource names consistently."""
|
||||
return name.replace("/", "-").replace(":", "-").replace("_", "-").lower()
|
||||
|
||||
|
||||
def build_name(project_id: str | UUID, resource_type: str, suffix: str = "") -> str:
|
||||
"""Build standardized resource names with project_id as base."""
|
||||
project_id = standardize_uuid(project_id)
|
||||
return "-".join([standardize_name(v) for v in (resource_type, project_id, suffix) if v])
|
||||
|
||||
|
||||
@dataclass
|
||||
class Label:
|
||||
"""Base label class for Kubernetes resources."""
|
||||
|
||||
resource_type: Literal["job", "deployment", "secret", "configmap", "service", "ingress"]
|
||||
project_id: str
|
||||
managed_by: str = "jockey"
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
"""Resource name for metadata.name"""
|
||||
return build_name(self.project_id, self.resource_type)
|
||||
|
||||
def as_dict(self) -> dict[str, str]:
|
||||
"""Labels dict for metadata.labels"""
|
||||
return {
|
||||
"project-id": self.project_id,
|
||||
"resource-type": self.resource_type,
|
||||
"managed-by": self.managed_by,
|
||||
}
|
||||
|
||||
@property
|
||||
def project_selector(self) -> str:
|
||||
"""Selector for all resources in project"""
|
||||
return f"project-id={self.project_id}"
|
||||
|
||||
@property
|
||||
def pod_selector(self) -> str:
|
||||
"""Selector for pods created by this resource"""
|
||||
return f"project-id={self.project_id}"
|
||||
|
||||
|
||||
@dataclass
|
||||
class TimestampedLabel(Label):
|
||||
"""Label class for resources that need timestamped names (Jobs)."""
|
||||
|
||||
timestamp: str = field(default_factory=lambda: datetime.utcnow().strftime("%Y%m%d-%H%M%S"))
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
"""Timestamped resource name"""
|
||||
return build_name(self.project_id, self.resource_type, self.timestamp)
|
||||
|
||||
@property
|
||||
def pod_selector(self) -> str:
|
||||
"""Selector for pods created by this specific job"""
|
||||
return f"job-name={self.name}"
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Simple logging configuration for jockey."""
|
||||
|
||||
import logging
|
||||
import sys
|
||||
from typing import Optional
|
||||
|
||||
from .environment import LOG_LEVEL
|
||||
|
||||
|
||||
def setup_logger(name: str = "jockey", level: Optional[str] = None) -> logging.Logger:
|
||||
"""Set up a simple logger with console output.
|
||||
|
||||
Args:
|
||||
name: Logger name
|
||||
level: Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
|
||||
|
||||
Returns:
|
||||
Configured logger instance
|
||||
"""
|
||||
logger = logging.getLogger(name)
|
||||
|
||||
# Don't add handlers if they already exist
|
||||
if logger.handlers:
|
||||
return logger
|
||||
|
||||
# Set level
|
||||
if level:
|
||||
logger.setLevel(getattr(logging, level.upper()))
|
||||
else:
|
||||
logger.setLevel(getattr(logging, LOG_LEVEL))
|
||||
|
||||
# Create console handler
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
handler.setLevel(logger.level)
|
||||
|
||||
# Create formatter
|
||||
formatter = logging.Formatter(
|
||||
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
)
|
||||
handler.setFormatter(formatter)
|
||||
|
||||
# Add handler to logger
|
||||
logger.addHandler(handler)
|
||||
|
||||
return logger
|
||||
|
||||
|
||||
# Default logger instance
|
||||
logger = setup_logger()
|
||||
@@ -0,0 +1,69 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=61.0", "wheel"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "jockey"
|
||||
version = "0.1.0"
|
||||
description = "Standalone Kubernetes deployment package for AgentOps"
|
||||
readme = "README.md"
|
||||
authors = [
|
||||
{name = "AgentOps", email = "support@agentops.ai"}
|
||||
]
|
||||
license = {text = "MIT"}
|
||||
classifiers = [
|
||||
"Development Status :: 3 - Alpha",
|
||||
"Intended Audience :: Developers",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
]
|
||||
requires-python = ">=3.9"
|
||||
dependencies = [
|
||||
"kubernetes>=28.0.0",
|
||||
"pyyaml>=6.0",
|
||||
"click>=8.0.0",
|
||||
"python-dotenv>=1.0.0",
|
||||
"docker>=6.0.0",
|
||||
"jinja2>=3.0.0",
|
||||
"redis>=5.0.0",
|
||||
"fastapi>=0.100.0",
|
||||
"uvicorn>=0.23.0",
|
||||
"gitpython>=3.1.0",
|
||||
"boto3>=1.39.4",
|
||||
]
|
||||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"pytest>=7.0.0",
|
||||
"pytest-cov>=4.0.0",
|
||||
"pytest-mock>=3.10.0",
|
||||
"docker>=6.0.0",
|
||||
"black>=23.0.0",
|
||||
"ruff>=0.1.0",
|
||||
"httpx>=0.24.0",
|
||||
]
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
python_files = ["test_*.py"]
|
||||
python_classes = ["Test*"]
|
||||
python_functions = ["test_*"]
|
||||
markers = [
|
||||
"integration: marks tests as integration tests (deselect with '-m \"not integration\"')"
|
||||
]
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.11"
|
||||
warn_return_any = true
|
||||
warn_unused_configs = true
|
||||
exclude = [
|
||||
"tests/",
|
||||
"test_*.py"
|
||||
]
|
||||
@@ -0,0 +1,50 @@
|
||||
# Select all pycodestyle ("E") and Pyflakes ("F") codes by default.
|
||||
select = ["E", "W", "F"]
|
||||
|
||||
# Allow unused variables that start with an underscore.
|
||||
# Useful for ignoring intentional unused variables (e.g., loop variables).
|
||||
# dummy-variable-rgx = "^_"
|
||||
|
||||
# Allow line lengths up to 100 characters (matches Prettier setting).
|
||||
line-length = 110
|
||||
|
||||
# Exclude common directories like virtual environments and caches.
|
||||
exclude = [
|
||||
".git",
|
||||
".env",
|
||||
".venv",
|
||||
"venv",
|
||||
"env",
|
||||
"__pycache__",
|
||||
"build",
|
||||
"dist",
|
||||
"*.egg-info",
|
||||
".bzr",
|
||||
".direnv",
|
||||
".eggs",
|
||||
".git-rewrite",
|
||||
".hg",
|
||||
".mypy_cache",
|
||||
".nox",
|
||||
".pants.d",
|
||||
".pytype",
|
||||
".ruff_cache",
|
||||
".svn",
|
||||
".tox",
|
||||
"__pypackages__",
|
||||
"_build",
|
||||
"buck-out",
|
||||
"node_modules"
|
||||
]
|
||||
|
||||
target-version = "py312"
|
||||
|
||||
[format]
|
||||
quote-style = "preserve"
|
||||
|
||||
[lint]
|
||||
# You can add specific ignores or configurations here if needed later.
|
||||
|
||||
[lint.isort]
|
||||
# Configuration for import sorting if needed.
|
||||
known-first-party = ["jockey"]
|
||||
@@ -0,0 +1,75 @@
|
||||
from uuid import UUID
|
||||
from jockey.backend.models.secret import Secret
|
||||
|
||||
|
||||
def create_secret(namespace: str, deployment_id: str | UUID, key: str, value: str) -> Secret:
|
||||
"""Create a new secret in the cluster.
|
||||
|
||||
Args:
|
||||
namespace: Kubernetes namespace
|
||||
deployment_id: Deployment ID to attach the secret to
|
||||
key: Secret key name (lowercase with dashes, e.g., 'agentops-api-key')
|
||||
value: Secret value to store
|
||||
|
||||
Returns:
|
||||
Secret: The created secret object
|
||||
"""
|
||||
# Transform key to uppercase with underscores for the data key
|
||||
data_key = key.upper().replace('-', '_')
|
||||
secret_data = {data_key: value}
|
||||
labels = {
|
||||
"deployment": str(deployment_id),
|
||||
"original-key": key, # Store original key name for retrieval
|
||||
}
|
||||
|
||||
secret = Secret(name=key, namespace=namespace, string_data=secret_data, labels=labels)
|
||||
return secret.create()
|
||||
|
||||
|
||||
def delete_secret(namespace: str, deployment_id: str | UUID, key: str) -> bool:
|
||||
"""Delete a secret by key name for a specific deployment.
|
||||
|
||||
Args:
|
||||
namespace: Kubernetes namespace
|
||||
deployment_id: Deployment ID to verify ownership
|
||||
key: Secret key name
|
||||
|
||||
Returns:
|
||||
True if deletion was successful, False otherwise
|
||||
"""
|
||||
# First verify the secret belongs to this deployment using label selector
|
||||
try:
|
||||
label_selector = f"deployment={deployment_id}"
|
||||
secret = Secret.get(key, namespace, label_selector=label_selector)
|
||||
if not secret:
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
return Secret.delete_by_name(key, namespace)
|
||||
|
||||
|
||||
def list_secrets(namespace: str, deployment_id: str) -> list[str]:
|
||||
"""List all secret names for a specific deployment.
|
||||
|
||||
Args:
|
||||
namespace: Kubernetes namespace
|
||||
deployment_id: Deployment ID to filter by
|
||||
|
||||
Returns:
|
||||
List of original secret key names for the deployment
|
||||
"""
|
||||
try:
|
||||
label_selector = f"deployment={deployment_id}"
|
||||
secrets = Secret.filter(namespace, label_selector=label_selector)
|
||||
# Try to get original key from label, otherwise reverse the transformation
|
||||
result = []
|
||||
for secret in secrets:
|
||||
if "original-key" in secret.labels:
|
||||
result.append(secret.labels["original-key"])
|
||||
else:
|
||||
# Reverse transformation: agentops-api-key -> AGENTOPS_API_KEY
|
||||
result.append(secret.name.upper().replace('-', '_'))
|
||||
return result
|
||||
except Exception:
|
||||
return []
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Template rendering utilities for Jockey.
|
||||
|
||||
Provides helpers for rendering Jinja2 templates from the templates directory.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any
|
||||
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
|
||||
TEMPLATES_DIR = Path(__file__).parent / 'templates'
|
||||
|
||||
|
||||
def render_template(template_path: str, template_vars: Dict[str, Any]) -> str:
|
||||
"""Render a template with the given variables.
|
||||
|
||||
Args:
|
||||
template_path: Path to template file relative to templates directory (e.g., 'docker/python-agent.j2')
|
||||
template_vars: Dictionary of variables to pass to the template
|
||||
|
||||
Returns:
|
||||
str: Rendered template content
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If the template file doesn't exist
|
||||
"""
|
||||
full_template_path = TEMPLATES_DIR / template_path
|
||||
|
||||
if not full_template_path.exists():
|
||||
raise FileNotFoundError(f"Template '{template_path}' not found in templates directory")
|
||||
|
||||
env = Environment(loader=FileSystemLoader(str(TEMPLATES_DIR)))
|
||||
template = env.get_template(template_path)
|
||||
|
||||
return template.render(**template_vars)
|
||||
@@ -0,0 +1,64 @@
|
||||
FROM --platform=linux/amd64 python:3.12-slim-bookworm
|
||||
|
||||
ARG JOB_ID
|
||||
|
||||
LABEL framework="crewai"
|
||||
LABEL agent.type="crewai"
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install system dependencies
|
||||
# Use --no-install-recommends to reduce package count and improve cache hit rate
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
git \
|
||||
curl \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install Python package managers
|
||||
RUN pip install --no-cache-dir uv
|
||||
|
||||
# Clone the repository inside the container
|
||||
{% if repository_url %}
|
||||
RUN git clone --depth 1 {{ repository_url }}
|
||||
{% endif %}
|
||||
|
||||
# Copy the entire repository to preserve structure and allow relative imports
|
||||
RUN cp -r {{ repository_name }}/* .
|
||||
|
||||
# Create virtual environment and install dependencies
|
||||
RUN uv venv
|
||||
RUN . .venv/bin/activate && \
|
||||
if [ -f pyproject.toml ]; then \
|
||||
uv pip install .; \
|
||||
elif [ -f requirements.txt ]; then \
|
||||
uv pip install -r requirements.txt; \
|
||||
fi
|
||||
|
||||
# Install CrewAI and required packages for the instance server
|
||||
# TODO make these part of the dependencies of the `instance` package.
|
||||
RUN . .venv/bin/activate && \
|
||||
uv pip install "crewai[tools]" fastapi uvicorn pydantic
|
||||
|
||||
# Copy instance files from ConfigMap mount into the image
|
||||
# The ConfigMap contains a base64-encoded tar.gz file with all instance files
|
||||
RUN if [ -f "/mnt/build_files/instance-src.tar.gz" ]; then \
|
||||
base64 -d /mnt/build_files/instance-src.tar.gz | tar -xz -C /app; \
|
||||
else \
|
||||
echo "No instance files archive found"; \
|
||||
fi
|
||||
|
||||
ENV PYTHONPATH=/app:/app/instance
|
||||
ENV PATH="/app/.venv/bin:$PATH"
|
||||
ENV APP_PATH="/app{{ watch_path | default('') }}"
|
||||
ENV JOB_ID=${JOB_ID}
|
||||
|
||||
# Health check for the FastAPI server
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
|
||||
CMD curl -f http://localhost:{{ port | default(8080) }}/docs || exit 1
|
||||
|
||||
# Expose application port
|
||||
EXPOSE {{ port | default(8080) }}
|
||||
|
||||
# `instance.server` comes from the build_files
|
||||
CMD ["sh", "-c", ". .venv/bin/activate && python -m instance.server"]
|
||||
@@ -0,0 +1,56 @@
|
||||
FROM --platform=linux/amd64 python:3.12-slim-bookworm
|
||||
|
||||
ARG JOB_ID
|
||||
|
||||
LABEL framework="crewai"
|
||||
LABEL agent.type="crewai-job"
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install system dependencies
|
||||
# Use --no-install-recommends to reduce package count and improve cache hit rate
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
git \
|
||||
curl \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install Python package managers
|
||||
RUN pip install --no-cache-dir uv
|
||||
|
||||
# Clone the repository inside the container
|
||||
{% if repository_url %}
|
||||
RUN git clone --depth 1 {{ repository_url }}
|
||||
{% endif %}
|
||||
|
||||
# Copy the entire repository to preserve structure and allow relative imports
|
||||
RUN cp -r {{ repository_name }}/* .
|
||||
|
||||
# Create virtual environment and install dependencies
|
||||
RUN uv venv
|
||||
RUN . .venv/bin/activate && \
|
||||
if [ -f pyproject.toml ]; then \
|
||||
uv pip install .; \
|
||||
elif [ -f requirements.txt ]; then \
|
||||
uv pip install -r requirements.txt; \
|
||||
fi
|
||||
|
||||
# Install CrewAI and required packages for the job runner
|
||||
RUN . .venv/bin/activate && \
|
||||
uv pip install "crewai[tools]"
|
||||
|
||||
# Copy instance files from ConfigMap mount into the image
|
||||
# The ConfigMap contains a base64-encoded tar.gz file with all instance files
|
||||
RUN if [ -f "/mnt/build_files/instance-src.tar.gz" ]; then \
|
||||
base64 -d /mnt/build_files/instance-src.tar.gz | tar -xz -C /app; \
|
||||
else \
|
||||
echo "No instance files archive found"; \
|
||||
fi
|
||||
|
||||
ENV PYTHONPATH=/app:/app/instance
|
||||
ENV PATH="/app/.venv/bin:$PATH"
|
||||
ENV APP_PATH="/app{{ watch_path | default('') }}"
|
||||
ENV JOB_ID=${JOB_ID}
|
||||
|
||||
# Run the job runner directly - this will execute once and exit
|
||||
CMD ["sh", "-c", ". .venv/bin/activate && python /app/instance/job_runner.py"]
|
||||
@@ -0,0 +1,74 @@
|
||||
FROM {{ base_image | default('python:3.12-slim-bookworm') }}
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install system dependencies
|
||||
RUN apt-get update && apt-get install -y \
|
||||
git \
|
||||
gcc \
|
||||
build-essential \
|
||||
curl \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install Python package managers
|
||||
RUN pip install --no-cache-dir uv psutil
|
||||
|
||||
# Clone the repository inside the container
|
||||
{% if repository_url %}
|
||||
RUN git clone --depth 1 {{ repository_url }}
|
||||
{% endif %}
|
||||
|
||||
# Copy the entire repository to preserve structure and allow relative imports
|
||||
RUN cp -r {{ repository_name }}/* .
|
||||
|
||||
# Copy dependency file from cloned repo to current directory
|
||||
{% if watch_path %}
|
||||
RUN if [ -f {{ repository_name }}/{{ watch_path }}/pyproject.toml ]; then \
|
||||
cp {{ repository_name }}/{{ watch_path }}/pyproject.toml .; \
|
||||
elif [ -f {{ repository_name }}/{{ watch_path }}/requirements.txt ]; then \
|
||||
cp {{ repository_name }}/{{ watch_path }}/requirements.txt .; \
|
||||
else \
|
||||
echo "No dependency file found in {{ repository_name }}/{{ watch_path }}"; exit 1; \
|
||||
fi
|
||||
{% else %}
|
||||
RUN if [ -f {{ repository_name }}/pyproject.toml ]; then \
|
||||
cp {{ repository_name }}/pyproject.toml .; \
|
||||
elif [ -f {{ repository_name }}/requirements.txt ]; then \
|
||||
cp {{ repository_name }}/requirements.txt .; \
|
||||
else \
|
||||
echo "No dependency file found in {{ repository_name }}"; exit 1; \
|
||||
fi
|
||||
{% endif %}
|
||||
|
||||
# Create virtual environment and install dependencies
|
||||
RUN uv venv
|
||||
RUN . .venv/bin/activate && \
|
||||
if [ -f pyproject.toml ]; then \
|
||||
uv sync; \
|
||||
elif [ -f requirements.txt ]; then \
|
||||
uv pip install -r requirements.txt; \
|
||||
fi
|
||||
|
||||
# Copy the application code from cloned repo
|
||||
{% if watch_path %}
|
||||
RUN cp -r {{ repository_name }}/{{ watch_path }}/* . 2>/dev/null || echo "No files in {{ repository_name }}/{{ watch_path }}"
|
||||
{% else %}
|
||||
RUN cp -r {{ repository_name }}/* . 2>/dev/null || echo "No files in {{ repository_name }}"
|
||||
{% endif %}
|
||||
|
||||
# Set environment variables
|
||||
ENV PYTHONPATH=/app
|
||||
ENV PATH="/app/.venv/bin:$PATH"
|
||||
|
||||
# Files are already copied to /app, so we stay in /app working directory
|
||||
|
||||
# Health check for Kubernetes
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
|
||||
CMD curl -f http://localhost:{{ port | default(8080) }}/health || exit 1
|
||||
|
||||
# Expose application port
|
||||
EXPOSE {{ port | default(8080) }}
|
||||
|
||||
# Run the entrypoint command
|
||||
CMD ["sh", "-c", "{{ entrypoint }}"]
|
||||
@@ -0,0 +1,43 @@
|
||||
# Dockerfile
|
||||
FROM {{ base_image | default('python:3.12-slim-bookworm') }}
|
||||
RUN rm /bin/sh && ln -s /bin/bash /bin/sh
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN apt update && apt install -y git gcc build-essential tree
|
||||
RUN apt clean
|
||||
|
||||
# Copy requirements first to leverage Docker cache
|
||||
{% if repository_name %}
|
||||
COPY {{ repository_name }}/{{ requirements_file | default('pyproject.toml') }} .
|
||||
{% else %}
|
||||
COPY {{ requirements_file | default('pyproject.toml') }} .
|
||||
{% endif %}
|
||||
RUN pip install --no-cache-dir uv
|
||||
RUN pip install psutil flask
|
||||
|
||||
{% if install_agentstack %}
|
||||
RUN #pip install agentstack
|
||||
RUN pip install git+https://github.com/AgentOps-AI/AgentStack.git@{{ agentstack_branch | default('deploy-command') }}
|
||||
RUN mkdir src
|
||||
RUN cp /usr/local/lib/python3.12/site-packages/agentstack/serve/serve.py ./src
|
||||
|
||||
RUN pip uninstall -y agentstack
|
||||
{% endif %}
|
||||
|
||||
RUN uv venv
|
||||
RUN source .venv/bin/activate
|
||||
RUN uv pip install --requirements {{ requirements_file | default('pyproject.toml') }}
|
||||
|
||||
# Copy the rest of the application
|
||||
{% if repository_name %}
|
||||
COPY {{ repository_name }}/ .
|
||||
{% else %}
|
||||
COPY . .
|
||||
{% endif %}
|
||||
|
||||
# Expose the port the app runs on
|
||||
EXPOSE {{ port | default(6969) }}
|
||||
|
||||
# Command to run the application
|
||||
CMD {{ run_command | default('["/app/.venv/bin/agentstack", "run"]') | tojson }}
|
||||
@@ -0,0 +1,10 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Create a simple HTTP server using Python
|
||||
RUN echo 'import http.server\nimport socketserver\nimport datetime\n\nclass HealthHandler(http.server.SimpleHTTPRequestHandler):\n def do_GET(self):\n self.send_response(200)\n self.send_header("Content-type", "text/plain")\n self.end_headers()\n message = f"Hello from test container - {datetime.datetime.now()}\\n"\n self.wfile.write(message.encode())\n\nPORT = 8080\nwith socketserver.TCPServer(("", PORT), HealthHandler) as httpd:\n print(f"Starting test HTTP server on port {PORT}...")\n httpd.serve_forever()' > server.py
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
CMD ["python", "server.py"]
|
||||
@@ -0,0 +1,16 @@
|
||||
# Simple Redis container for testing
|
||||
FROM redis:8-alpine
|
||||
|
||||
# Expose Redis port
|
||||
EXPOSE 6379
|
||||
|
||||
# Use a simple configuration optimized for testing
|
||||
RUN echo "bind 0.0.0.0" > /etc/redis.conf && \
|
||||
echo "port 6379" >> /etc/redis.conf && \
|
||||
echo "timeout 0" >> /etc/redis.conf && \
|
||||
echo "tcp-keepalive 300" >> /etc/redis.conf && \
|
||||
echo "save \"\"" >> /etc/redis.conf && \
|
||||
echo "appendonly no" >> /etc/redis.conf
|
||||
|
||||
# Start Redis with custom config
|
||||
CMD ["redis-server", "/etc/redis.conf"]
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Tests for ConfigMap model."""
|
||||
|
||||
from unittest.mock import patch, Mock
|
||||
from kubernetes import client as k8s
|
||||
from kubernetes.client.rest import ApiException
|
||||
|
||||
from jockey.backend.models.configmap import ConfigMap
|
||||
import jockey.backend.client
|
||||
|
||||
|
||||
class TestConfigMap:
|
||||
"""Test cases for ConfigMap model."""
|
||||
|
||||
def setup_method(self):
|
||||
"""Reset the singleton client instance before each test."""
|
||||
jockey.backend.client._client_instance = None
|
||||
|
||||
@patch('jockey.backend.models.base.get_client')
|
||||
def test_configmap_k8s_object_generation(self, mock_get_client):
|
||||
"""Test that ConfigMap generates correct Kubernetes objects and calls client with correct arguments."""
|
||||
# Create configmap with realistic data
|
||||
configmap = ConfigMap(
|
||||
name="app-config",
|
||||
namespace="production",
|
||||
data={
|
||||
"database.host": "postgres.prod.internal",
|
||||
"app.config.json": '{"debug": false, "log_level": "info"}',
|
||||
},
|
||||
binary_data={"logo.png": b"\x89PNG\r\n\x1a\n"},
|
||||
labels={"app": "myapp", "env": "prod", "component": "config"},
|
||||
)
|
||||
|
||||
# Test K8s object generation
|
||||
k8s_configmap = configmap.to_k8s_configmap()
|
||||
|
||||
# Verify K8s object structure
|
||||
assert isinstance(k8s_configmap, k8s.V1ConfigMap)
|
||||
assert k8s_configmap.metadata.name == "app-config"
|
||||
assert k8s_configmap.metadata.namespace == "production"
|
||||
|
||||
# Verify labels merge correctly (default + custom)
|
||||
expected_labels = {"app": "app-config", "app": "myapp", "env": "prod", "component": "config"}
|
||||
assert k8s_configmap.metadata.labels == expected_labels
|
||||
|
||||
# Verify data passthrough
|
||||
assert k8s_configmap.data["database.host"] == "postgres.prod.internal"
|
||||
assert k8s_configmap.data["app.config.json"] == '{"debug": false, "log_level": "info"}'
|
||||
|
||||
# Verify binary_data passthrough
|
||||
assert k8s_configmap.binary_data == {"logo.png": b"\x89PNG\r\n\x1a\n"}
|
||||
|
||||
# Test create() calls client with correct arguments
|
||||
mock_client = mock_get_client.return_value
|
||||
mock_k8s_response = Mock()
|
||||
mock_client.core.create_namespaced_config_map.return_value = mock_k8s_response
|
||||
|
||||
configmap.create()
|
||||
|
||||
# Verify client was called with our generated K8s object and correct namespace
|
||||
mock_client.core.create_namespaced_config_map.assert_called_once()
|
||||
call_args = mock_client.core.create_namespaced_config_map.call_args
|
||||
|
||||
assert call_args.kwargs['namespace'] == "production"
|
||||
passed_configmap = call_args.kwargs['body']
|
||||
assert passed_configmap.metadata.name == "app-config"
|
||||
assert passed_configmap.data["database.host"] == "postgres.prod.internal"
|
||||
|
||||
@patch('jockey.backend.models.base.get_client')
|
||||
def test_configmap_crud_operations_call_client_correctly(self, mock_get_client, mock_configmap_data):
|
||||
"""Test that CRUD operations call Kubernetes client with correct arguments."""
|
||||
# Setup mock responses
|
||||
mock_client = mock_get_client.return_value
|
||||
mock_client.core.read_namespaced_config_map.return_value = mock_configmap_data
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.items = [mock_configmap_data]
|
||||
mock_client.core.list_namespaced_config_map.return_value = mock_list_result
|
||||
|
||||
# Test get() calls client correctly
|
||||
result = ConfigMap.get("test-configmap", "test-namespace")
|
||||
mock_client.core.read_namespaced_config_map.assert_called_once_with(
|
||||
name="test-configmap", namespace="test-namespace"
|
||||
)
|
||||
assert result.name == "test-configmap" # Verify from_k8s_data works
|
||||
|
||||
# Test filter() calls client correctly
|
||||
ConfigMap.filter("test-namespace", label_selector="component=config")
|
||||
mock_client.core.list_namespaced_config_map.assert_called_once_with(
|
||||
namespace="test-namespace", label_selector="component=config"
|
||||
)
|
||||
|
||||
# Test delete() calls client correctly (instance method)
|
||||
configmap_instance = ConfigMap(name="test-configmap", namespace="test-namespace")
|
||||
configmap_instance.delete()
|
||||
mock_client.core.delete_namespaced_config_map.assert_called_once_with(
|
||||
name="test-configmap", namespace="test-namespace"
|
||||
)
|
||||
|
||||
# Test error handling returns expected values
|
||||
mock_client.core.read_namespaced_config_map.side_effect = ApiException(status=404)
|
||||
result = ConfigMap.get("nonexistent", "test")
|
||||
assert result is None
|
||||
|
||||
mock_client.core.delete_namespaced_config_map.side_effect = ApiException(status=404)
|
||||
nonexistent_configmap = ConfigMap(name="nonexistent", namespace="test")
|
||||
result = nonexistent_configmap.delete()
|
||||
assert result is False
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Tests for Secret model."""
|
||||
|
||||
from unittest.mock import patch, Mock
|
||||
from kubernetes import client as k8s
|
||||
from kubernetes.client.rest import ApiException
|
||||
|
||||
from jockey.backend.models.secret import Secret
|
||||
import jockey.backend.client
|
||||
|
||||
|
||||
class TestSecret:
|
||||
"""Test cases for Secret model."""
|
||||
|
||||
def setup_method(self):
|
||||
"""Reset the singleton client instance before each test."""
|
||||
jockey.backend.client._client_instance = None
|
||||
|
||||
@patch('jockey.backend.models.base.get_client')
|
||||
def test_secret_k8s_object_generation(self, mock_get_client):
|
||||
"""Test that Secret generates correct Kubernetes objects and calls client with correct arguments."""
|
||||
# Create secret with realistic data
|
||||
secret = Secret(
|
||||
name="app-credentials",
|
||||
namespace="production",
|
||||
data={"username": "admin", "password": "secret123"},
|
||||
string_data={"config": "plaintext"},
|
||||
labels={"app": "myapp", "env": "prod"},
|
||||
secret_type="kubernetes.io/tls",
|
||||
)
|
||||
|
||||
# Test K8s object generation
|
||||
k8s_secret = secret.to_k8s_secret()
|
||||
|
||||
# Verify K8s object structure
|
||||
assert isinstance(k8s_secret, k8s.V1Secret)
|
||||
assert k8s_secret.metadata.name == "app-credentials"
|
||||
assert k8s_secret.metadata.namespace == "production"
|
||||
assert k8s_secret.type == "kubernetes.io/tls"
|
||||
|
||||
# Verify labels merge correctly (default + custom)
|
||||
expected_labels = {"app": "app-credentials", "app": "myapp", "env": "prod"}
|
||||
assert k8s_secret.metadata.labels == expected_labels
|
||||
|
||||
# Verify data encoding happens
|
||||
assert k8s_secret.data is not None
|
||||
assert "username" in k8s_secret.data
|
||||
assert "password" in k8s_secret.data
|
||||
|
||||
# Verify string_data passthrough
|
||||
assert k8s_secret.string_data == {"config": "plaintext"}
|
||||
|
||||
# Test create() calls client with correct arguments
|
||||
mock_client = mock_get_client.return_value
|
||||
mock_k8s_response = Mock()
|
||||
mock_client.core.create_namespaced_secret.return_value = mock_k8s_response
|
||||
|
||||
secret.create()
|
||||
|
||||
# Verify client was called with our generated K8s object and correct namespace
|
||||
mock_client.core.create_namespaced_secret.assert_called_once()
|
||||
call_args = mock_client.core.create_namespaced_secret.call_args
|
||||
|
||||
assert call_args.kwargs['namespace'] == "production"
|
||||
passed_secret = call_args.kwargs['body']
|
||||
assert passed_secret.metadata.name == "app-credentials"
|
||||
assert passed_secret.type == "kubernetes.io/tls"
|
||||
|
||||
@patch('jockey.backend.models.base.get_client')
|
||||
def test_secret_crud_operations_call_client_correctly(self, mock_get_client, mock_secret_data):
|
||||
"""Test that CRUD operations call Kubernetes client with correct arguments."""
|
||||
# Setup mock responses
|
||||
mock_client = mock_get_client.return_value
|
||||
mock_client.core.read_namespaced_secret.return_value = mock_secret_data
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.items = [mock_secret_data]
|
||||
mock_client.core.list_namespaced_secret.return_value = mock_list_result
|
||||
|
||||
# Test get() calls client correctly
|
||||
result = Secret.get("test-secret", "test-namespace")
|
||||
mock_client.core.read_namespaced_secret.assert_called_once_with(
|
||||
name="test-secret", namespace="test-namespace"
|
||||
)
|
||||
assert result.name == "test-secret" # Verify from_k8s_data works
|
||||
|
||||
# Test filter() calls client correctly
|
||||
Secret.filter("test-namespace", label_selector="app=myapp")
|
||||
mock_client.core.list_namespaced_secret.assert_called_once_with(
|
||||
namespace="test-namespace", label_selector="app=myapp"
|
||||
)
|
||||
|
||||
# Test delete() calls client correctly (instance method)
|
||||
secret_instance = Secret(name="test-secret", namespace="test-namespace")
|
||||
secret_instance.delete()
|
||||
mock_client.core.delete_namespaced_secret.assert_called_once_with(
|
||||
name="test-secret", namespace="test-namespace"
|
||||
)
|
||||
|
||||
# Test error handling returns expected values
|
||||
mock_client.core.read_namespaced_secret.side_effect = ApiException(status=404)
|
||||
result = Secret.get("nonexistent", "test")
|
||||
assert result is None
|
||||
|
||||
mock_client.core.delete_namespaced_secret.side_effect = ApiException(status=404)
|
||||
nonexistent_secret = Secret(name="nonexistent", namespace="test")
|
||||
result = nonexistent_secret.delete()
|
||||
assert result is False
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Test to verify mocking is working correctly."""
|
||||
|
||||
from unittest.mock import patch, Mock
|
||||
import jockey.backend.client
|
||||
from jockey.backend.models.base import BaseModel
|
||||
|
||||
|
||||
class SimpleModel(BaseModel):
|
||||
"""Test model subclass for testing mocking."""
|
||||
|
||||
def __init__(self, name: str):
|
||||
self.name = name
|
||||
|
||||
def test_method(self):
|
||||
"""Test method that uses the client."""
|
||||
return self.client
|
||||
|
||||
|
||||
class TestMocking:
|
||||
"""Test cases to verify mocking is applied correctly."""
|
||||
|
||||
def setup_method(self):
|
||||
"""Reset the singleton client instance before each test."""
|
||||
jockey.backend.client._client_instance = None
|
||||
|
||||
@patch('jockey.backend.models.base.get_client')
|
||||
def test_mock_is_applied(self, mock_get_client):
|
||||
"""Test that the mock is properly applied and no real Kubernetes client is created."""
|
||||
# Setup mock
|
||||
mock_client = Mock()
|
||||
mock_get_client.return_value = mock_client
|
||||
|
||||
# Create a test model instance
|
||||
test_model = SimpleModel(name="test")
|
||||
|
||||
# Access the client property - this should use our mock
|
||||
client = test_model.client
|
||||
|
||||
# Verify we got our mock
|
||||
assert client is mock_client
|
||||
assert mock_get_client.called
|
||||
|
||||
# Verify no real Kubernetes connection was attempted
|
||||
mock_get_client.assert_called_once()
|
||||
|
||||
@patch('jockey.backend.models.base.get_client')
|
||||
def test_client_property_uses_mock(self, mock_get_client):
|
||||
"""Test that the client property uses the mocked get_client function."""
|
||||
# Setup mock
|
||||
mock_client = Mock()
|
||||
mock_get_client.return_value = mock_client
|
||||
|
||||
# Create test model and access client through test method
|
||||
test_model = SimpleModel(name="test")
|
||||
result = test_model.test_method()
|
||||
|
||||
# Verify mock was used
|
||||
mock_get_client.assert_called_once()
|
||||
assert result is mock_client
|
||||
|
||||
def test_without_mock_fails_in_ci(self):
|
||||
"""Test that without mocking, we would get a Kubernetes config error in CI."""
|
||||
# This test should pass locally (if you have k8s config) but fail in CI
|
||||
# We're not actually calling anything that would trigger the error,
|
||||
# just verifying the setup
|
||||
|
||||
# Reset singleton to force new client creation
|
||||
jockey.backend.client._client_instance = None
|
||||
|
||||
# In CI environment, this would fail when accessing client property
|
||||
# But we can't test that directly without actually triggering the error
|
||||
# So we just verify the singleton is reset
|
||||
assert jockey.backend.client._client_instance is None
|
||||
@@ -0,0 +1,186 @@
|
||||
"""
|
||||
Pytest configuration and fixtures for the API tests.
|
||||
|
||||
This module provides fixtures for managing Redis containers during testing.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import docker
|
||||
import time
|
||||
import redis
|
||||
import socket
|
||||
from contextlib import closing
|
||||
|
||||
|
||||
def find_free_port():
|
||||
"""Find a free port on localhost."""
|
||||
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
|
||||
s.bind(('', 0))
|
||||
s.listen(1)
|
||||
port = s.getsockname()[1]
|
||||
return port
|
||||
|
||||
|
||||
def wait_for_redis(host='localhost', port=6379, timeout=30):
|
||||
"""Wait for Redis to be ready."""
|
||||
start_time = time.time()
|
||||
while time.time() - start_time < timeout:
|
||||
try:
|
||||
client = redis.Redis(host=host, port=port, socket_timeout=1)
|
||||
client.ping()
|
||||
return True
|
||||
except (redis.ConnectionError, redis.TimeoutError):
|
||||
print('.', end='', flush=True)
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def docker_client():
|
||||
"""Create a Docker client for container management."""
|
||||
try:
|
||||
client = docker.from_env()
|
||||
# Test Docker connection
|
||||
client.ping()
|
||||
return client
|
||||
except Exception as e:
|
||||
pytest.skip(f"Docker not available: {e}")
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def redis_container(docker_client):
|
||||
"""Start a Redis container for testing."""
|
||||
print("Starting Redis Docker container for tests...")
|
||||
|
||||
# Find a free port
|
||||
redis_port = find_free_port()
|
||||
print(f"Using Redis port: {redis_port}")
|
||||
|
||||
# Build the Redis image from our Dockerfile
|
||||
print("Building Redis Docker image...")
|
||||
import os
|
||||
|
||||
tests_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
image, build_logs = docker_client.images.build(
|
||||
path=tests_dir, dockerfile="Dockerfile.redis", tag="test-redis:latest", rm=True
|
||||
)
|
||||
|
||||
# Start the Redis container
|
||||
print("Starting Redis container...")
|
||||
container = docker_client.containers.run(
|
||||
"test-redis:latest",
|
||||
ports={'6379/tcp': redis_port},
|
||||
detach=True,
|
||||
remove=True,
|
||||
name=f"test-redis-{redis_port}",
|
||||
)
|
||||
|
||||
# Wait for Redis to be ready
|
||||
print(f"Waiting for Redis to be ready at localhost:{redis_port}...")
|
||||
if not wait_for_redis('localhost', redis_port):
|
||||
container.stop()
|
||||
pytest.fail("Redis container failed to start")
|
||||
|
||||
print("Redis is ready!")
|
||||
|
||||
try:
|
||||
yield {'host': 'localhost', 'port': redis_port, 'container': container}
|
||||
finally:
|
||||
# Cleanup: stop and remove container
|
||||
print("Stopping Redis Docker container...")
|
||||
try:
|
||||
container.stop(timeout=5)
|
||||
print("Redis container stopped successfully")
|
||||
except Exception:
|
||||
print("Redis container was already stopped") # Container might already be stopped
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def redis_client_with_container(redis_container, monkeypatch):
|
||||
"""Create a Redis client connected to the test container."""
|
||||
from jockey.worker import queue
|
||||
|
||||
# Patch Redis settings in the queue module's imported variables
|
||||
monkeypatch.setattr('jockey.worker.queue.REDIS_HOST', redis_container['host']) # This references the actual env var import
|
||||
monkeypatch.setattr('jockey.worker.queue.REDIS_PORT', redis_container['port']) # This references the actual env var import
|
||||
monkeypatch.setattr('jockey.worker.queue.REDIS_DB', 0) # This references the actual env var import
|
||||
|
||||
# Reset the module-level Redis client so it picks up new env vars
|
||||
queue._redis_client = None
|
||||
|
||||
# Create a direct Redis client with test container settings
|
||||
client = queue._get_redis_client()
|
||||
|
||||
# Ensure clean state
|
||||
client.flushdb()
|
||||
|
||||
yield client
|
||||
|
||||
# Cleanup after test
|
||||
try:
|
||||
client.flushdb()
|
||||
except Exception:
|
||||
pass # Ignore cleanup errors
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def clean_redis(redis_client_with_container):
|
||||
"""Provide a clean Redis client and track keys for cleanup."""
|
||||
from jockey.worker import queue
|
||||
|
||||
tracked_keys = []
|
||||
|
||||
# Helper function to track keys
|
||||
def track_key(key):
|
||||
tracked_keys.append(key)
|
||||
return key
|
||||
|
||||
redis_client_with_container.track_key = track_key
|
||||
|
||||
# Add queue functions as methods
|
||||
redis_client_with_container.store_event = queue.store_event
|
||||
redis_client_with_container.get_task_status = queue.get_task_status
|
||||
redis_client_with_container.get_task_events = queue.get_task_events
|
||||
|
||||
yield redis_client_with_container
|
||||
|
||||
# Cleanup tracked keys
|
||||
if tracked_keys:
|
||||
try:
|
||||
redis_client_with_container.delete(*tracked_keys)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_configmap_data():
|
||||
"""Mock ConfigMap data for testing."""
|
||||
from unittest.mock import Mock
|
||||
from kubernetes import client as k8s
|
||||
|
||||
mock_configmap = Mock(spec=k8s.V1ConfigMap)
|
||||
mock_configmap.metadata = Mock()
|
||||
mock_configmap.metadata.name = "test-configmap"
|
||||
mock_configmap.metadata.namespace = "test-namespace"
|
||||
mock_configmap.metadata.labels = {"app": "test-app"}
|
||||
mock_configmap.data = {"key1": "value1", "key2": "value2"}
|
||||
mock_configmap.binary_data = None
|
||||
|
||||
return mock_configmap
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_secret_data():
|
||||
"""Mock Secret data for testing."""
|
||||
from unittest.mock import Mock
|
||||
from kubernetes import client as k8s
|
||||
|
||||
mock_secret = Mock(spec=k8s.V1Secret)
|
||||
mock_secret.metadata = Mock()
|
||||
mock_secret.metadata.name = "test-secret"
|
||||
mock_secret.metadata.namespace = "test-namespace"
|
||||
mock_secret.metadata.labels = {"app": "test-app"}
|
||||
mock_secret.data = {"username": "dGVzdA==", "password": "cGFzcw=="} # base64 encoded
|
||||
mock_secret.type = "Opaque"
|
||||
|
||||
return mock_secret
|
||||
@@ -0,0 +1,34 @@
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
import jockey.api.main as main
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def disable_background(monkeypatch):
|
||||
"""Disable background deployment thread and event generation."""
|
||||
monkeypatch.setattr("jockey.worker.queue.health_check", lambda: True)
|
||||
monkeypatch.setattr("jockey.worker.queue.get_queue_length", lambda: 0)
|
||||
monkeypatch.setattr("jockey.worker.queue.get_processing_count", lambda: 0)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
"""Test client for the FastAPI app."""
|
||||
return TestClient(main.app)
|
||||
|
||||
|
||||
def test_health_check_healthy(client, monkeypatch):
|
||||
# The health check uses the mocked queue.health_check() from the fixture
|
||||
response = client.get("/health")
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"status": "healthy", "redis": "connected"}
|
||||
|
||||
|
||||
def test_health_check_unhealthy(client, monkeypatch):
|
||||
# Override the health check to simulate failure
|
||||
monkeypatch.setattr("jockey.worker.queue.health_check", lambda: False)
|
||||
response = client.get("/health")
|
||||
assert response.status_code == 200
|
||||
result = response.json()
|
||||
assert result["status"] == "unhealthy"
|
||||
assert result["redis"] == "disconnected"
|
||||
@@ -0,0 +1,310 @@
|
||||
"""Unit tests for the config module."""
|
||||
|
||||
import pytest
|
||||
from jockey.config import (
|
||||
DeploymentConfig,
|
||||
DeploymentPack,
|
||||
DEPLOYMENT_PACKS,
|
||||
_get_instance_build_files,
|
||||
)
|
||||
|
||||
|
||||
class TestDeploymentPacks:
|
||||
"""Test deployment pack functionality."""
|
||||
|
||||
def test_deployment_packs_dictionary_contains_all_packs(self):
|
||||
"""Test that DEPLOYMENT_PACKS contains all expected pack types."""
|
||||
expected_packs = {"FASTAPI", "CREWAI", "CREWAI_JOB"}
|
||||
assert set(DEPLOYMENT_PACKS.keys()) == expected_packs
|
||||
|
||||
# Verify they're the correct DeploymentPack instances
|
||||
assert DEPLOYMENT_PACKS["FASTAPI"] == DEPLOYMENT_PACKS["FASTAPI"]
|
||||
assert DEPLOYMENT_PACKS["CREWAI"] == DEPLOYMENT_PACKS["CREWAI"]
|
||||
assert DEPLOYMENT_PACKS["CREWAI_JOB"] == DEPLOYMENT_PACKS["CREWAI_JOB"]
|
||||
|
||||
def test_fastapi_pack_configuration(self):
|
||||
"""Test FASTAPI pack has correct configuration."""
|
||||
pack = DEPLOYMENT_PACKS["FASTAPI"]
|
||||
assert pack.dockerfile_template == "fastapi-agent"
|
||||
assert pack.ports == [8000]
|
||||
assert pack.build_files == {}
|
||||
|
||||
def test_crewai_pack_configuration(self):
|
||||
"""Test CREWAI pack has correct configuration."""
|
||||
pack = DEPLOYMENT_PACKS["CREWAI"]
|
||||
assert pack.dockerfile_template == "crewai-agent"
|
||||
assert pack.ports == [8080]
|
||||
assert isinstance(pack.build_files, dict)
|
||||
|
||||
def test_crewai_job_pack_configuration(self):
|
||||
"""Test CREWAI_JOB pack has correct configuration."""
|
||||
pack = DEPLOYMENT_PACKS["CREWAI_JOB"]
|
||||
assert pack.dockerfile_template == "crewai-job"
|
||||
assert pack.ports == [] # No ports for job execution
|
||||
assert isinstance(pack.build_files, dict)
|
||||
|
||||
|
||||
class TestDeploymentConfigFromPack:
|
||||
"""Test DeploymentConfig.from_pack() functionality."""
|
||||
|
||||
def test_from_pack_with_fastapi(self):
|
||||
"""Test creating config from FASTAPI pack."""
|
||||
config = DeploymentConfig.from_pack(
|
||||
"FASTAPI",
|
||||
namespace="test-ns",
|
||||
project_id="test-project"
|
||||
)
|
||||
|
||||
assert config.dockerfile_template == "fastapi-agent"
|
||||
assert config.ports == [8000]
|
||||
assert config.build_files == {}
|
||||
assert config.namespace == "test-ns"
|
||||
assert config.project_id == "test-project"
|
||||
|
||||
def test_from_pack_with_crewai(self):
|
||||
"""Test creating config from CREWAI pack."""
|
||||
config = DeploymentConfig.from_pack(
|
||||
"CREWAI",
|
||||
namespace="test-ns",
|
||||
project_id="test-project"
|
||||
)
|
||||
|
||||
assert config.dockerfile_template == "crewai-agent"
|
||||
assert config.ports == [8080]
|
||||
assert isinstance(config.build_files, dict)
|
||||
assert config.namespace == "test-ns"
|
||||
assert config.project_id == "test-project"
|
||||
|
||||
def test_from_pack_with_crewai_job(self):
|
||||
"""Test creating config from CREWAI_JOB pack."""
|
||||
config = DeploymentConfig.from_pack(
|
||||
"CREWAI_JOB",
|
||||
namespace="test-ns",
|
||||
project_id="test-project"
|
||||
)
|
||||
|
||||
assert config.dockerfile_template == "crewai-job"
|
||||
assert config.ports == []
|
||||
assert isinstance(config.build_files, dict)
|
||||
assert config.namespace == "test-ns"
|
||||
assert config.project_id == "test-project"
|
||||
|
||||
def test_from_pack_with_none_uses_fastapi_fallback(self):
|
||||
"""Test that None pack name falls back to FASTAPI."""
|
||||
config = DeploymentConfig.from_pack(
|
||||
None,
|
||||
namespace="test-ns",
|
||||
project_id="test-project"
|
||||
)
|
||||
|
||||
assert config.dockerfile_template == "fastapi-agent"
|
||||
assert config.ports == [8000]
|
||||
assert config.build_files == {}
|
||||
|
||||
def test_from_pack_with_invalid_name_raises_error(self):
|
||||
"""Test that invalid pack name raises ValueError."""
|
||||
with pytest.raises(ValueError, match="Invalid deployment pack name: INVALID"):
|
||||
DeploymentConfig.from_pack(
|
||||
"INVALID",
|
||||
namespace="test-ns",
|
||||
project_id="test-project"
|
||||
)
|
||||
|
||||
def test_from_pack_with_empty_string_raises_error(self):
|
||||
"""Test that empty string pack name raises ValueError."""
|
||||
with pytest.raises(ValueError, match="Invalid deployment pack name: "):
|
||||
DeploymentConfig.from_pack(
|
||||
"",
|
||||
namespace="test-ns",
|
||||
project_id="test-project"
|
||||
)
|
||||
|
||||
def test_from_pack_kwargs_override_pack_defaults(self):
|
||||
"""Test that kwargs override pack defaults."""
|
||||
config = DeploymentConfig.from_pack(
|
||||
"FASTAPI",
|
||||
namespace="test-ns",
|
||||
project_id="test-project",
|
||||
ports=[9000, 9001], # Override default FASTAPI ports
|
||||
dockerfile_template="custom-template", # Override default template
|
||||
replicas=3
|
||||
)
|
||||
|
||||
assert config.ports == [9000, 9001] # Should use provided ports
|
||||
assert config.dockerfile_template == "custom-template" # Should use provided template
|
||||
assert config.replicas == 3
|
||||
# Other pack defaults should still apply
|
||||
assert config.build_files == {} # FASTAPI has empty build_files
|
||||
|
||||
def test_from_pack_computes_derived_fields(self):
|
||||
"""Test that from_pack() properly computes tag and hostname."""
|
||||
config = DeploymentConfig.from_pack(
|
||||
"FASTAPI",
|
||||
namespace="test-ns",
|
||||
project_id="test-project-123"
|
||||
)
|
||||
|
||||
# Derived fields should be computed in __post_init__
|
||||
assert config.tag == "test-project-123"
|
||||
assert config.hostname == "test-project-123.deploy.agentops.ai"
|
||||
|
||||
def test_from_pack_with_all_optional_fields(self):
|
||||
"""Test from_pack with all optional fields provided."""
|
||||
config = DeploymentConfig.from_pack(
|
||||
"CREWAI",
|
||||
namespace="test-ns",
|
||||
project_id="test-project",
|
||||
repository_url="https://github.com/test/repo.git",
|
||||
branch="feature-branch",
|
||||
github_access_token="token123",
|
||||
entrypoint="main.py",
|
||||
watch_path="src/",
|
||||
agentops_api_key="key123",
|
||||
callback_url="https://callback.example.com",
|
||||
secret_names=["secret1", "secret2"],
|
||||
create_ingress=False,
|
||||
force_recreate=True
|
||||
)
|
||||
|
||||
# Pack defaults should be applied
|
||||
assert config.dockerfile_template == "crewai-agent"
|
||||
assert config.ports == [8080]
|
||||
assert isinstance(config.build_files, dict)
|
||||
|
||||
# Provided fields should be set
|
||||
assert config.repository_url == "https://github.com/test/repo.git"
|
||||
assert config.branch == "feature-branch"
|
||||
assert config.github_access_token == "token123"
|
||||
assert config.entrypoint == "main.py"
|
||||
assert config.watch_path == "src/"
|
||||
assert config.agentops_api_key == "key123"
|
||||
assert config.callback_url == "https://callback.example.com"
|
||||
assert config.secret_names == ["secret1", "secret2"]
|
||||
assert config.create_ingress is False
|
||||
assert config.force_recreate is True
|
||||
|
||||
|
||||
class TestDeploymentConfigSerialization:
|
||||
"""Test serialization/deserialization of DeploymentConfig."""
|
||||
|
||||
def test_serialize_config_created_from_pack(self):
|
||||
"""Test that config created from pack can be serialized."""
|
||||
config = DeploymentConfig.from_pack(
|
||||
"CREWAI",
|
||||
namespace="test-ns",
|
||||
project_id="test-project",
|
||||
repository_url="https://github.com/test/repo.git"
|
||||
)
|
||||
|
||||
serialized = config.serialize()
|
||||
|
||||
# Should contain all required fields
|
||||
assert serialized["namespace"] == "test-ns"
|
||||
assert serialized["project_id"] == "test-project"
|
||||
assert serialized["dockerfile_template"] == "crewai-agent"
|
||||
assert serialized["ports"] == [8080]
|
||||
assert serialized["repository_url"] == "https://github.com/test/repo.git"
|
||||
assert isinstance(serialized["build_files"], dict)
|
||||
|
||||
def test_deserialize_config_works(self):
|
||||
"""Test that serialized config can be deserialized."""
|
||||
original_config = DeploymentConfig.from_pack(
|
||||
"FASTAPI",
|
||||
namespace="test-ns",
|
||||
project_id="test-project"
|
||||
)
|
||||
|
||||
serialized = original_config.serialize()
|
||||
deserialized_config = DeploymentConfig.from_serialized(serialized)
|
||||
|
||||
# Should have same values
|
||||
assert deserialized_config.namespace == original_config.namespace
|
||||
assert deserialized_config.project_id == original_config.project_id
|
||||
assert deserialized_config.dockerfile_template == original_config.dockerfile_template
|
||||
assert deserialized_config.ports == original_config.ports
|
||||
assert deserialized_config.build_files == original_config.build_files
|
||||
|
||||
def test_roundtrip_serialization_preserves_data(self):
|
||||
"""Test that serialize -> deserialize preserves all data."""
|
||||
original_config = DeploymentConfig.from_pack(
|
||||
"CREWAI_JOB",
|
||||
namespace="test-ns",
|
||||
project_id="test-project",
|
||||
repository_url="https://github.com/test/repo.git",
|
||||
branch="main",
|
||||
replicas=2,
|
||||
secret_names=["secret1"],
|
||||
agentops_api_key="test-key"
|
||||
)
|
||||
|
||||
# Serialize and deserialize
|
||||
serialized = original_config.serialize()
|
||||
deserialized_config = DeploymentConfig.from_serialized(serialized)
|
||||
|
||||
# All fields should be preserved
|
||||
assert deserialized_config.namespace == original_config.namespace
|
||||
assert deserialized_config.project_id == original_config.project_id
|
||||
assert deserialized_config.dockerfile_template == original_config.dockerfile_template
|
||||
assert deserialized_config.repository_url == original_config.repository_url
|
||||
assert deserialized_config.branch == original_config.branch
|
||||
assert deserialized_config.replicas == original_config.replicas
|
||||
assert deserialized_config.secret_names == original_config.secret_names
|
||||
assert deserialized_config.agentops_api_key == original_config.agentops_api_key
|
||||
assert deserialized_config.ports == original_config.ports
|
||||
assert deserialized_config.build_files == original_config.build_files
|
||||
|
||||
|
||||
class TestInstanceBuildFiles:
|
||||
"""Test instance build files functionality."""
|
||||
|
||||
def test_get_instance_build_files_returns_dict(self):
|
||||
"""Test that _get_instance_build_files returns a dictionary."""
|
||||
build_files = _get_instance_build_files()
|
||||
assert isinstance(build_files, dict)
|
||||
|
||||
# Should contain Python files from instance directory if they exist
|
||||
for key, value in build_files.items():
|
||||
assert key.startswith("instance/")
|
||||
assert key.endswith(".py")
|
||||
assert isinstance(value, str) # File content should be string
|
||||
|
||||
def test_crewai_packs_have_same_build_files(self):
|
||||
"""Test that both CREWAI packs have the same build files."""
|
||||
crewai_pack = DEPLOYMENT_PACKS["CREWAI"]
|
||||
crewai_job_pack = DEPLOYMENT_PACKS["CREWAI_JOB"]
|
||||
|
||||
# Both should use the same build files
|
||||
assert crewai_pack.build_files == crewai_job_pack.build_files
|
||||
|
||||
# FASTAPI should have empty build files
|
||||
assert DEPLOYMENT_PACKS["FASTAPI"].build_files == {}
|
||||
|
||||
|
||||
class TestPackValidation:
|
||||
"""Test edge cases and validation for deployment packs."""
|
||||
|
||||
def test_all_pack_names_are_strings(self):
|
||||
"""Test that all pack names in DEPLOYMENT_PACKS are strings."""
|
||||
for pack_name in DEPLOYMENT_PACKS.keys():
|
||||
assert isinstance(pack_name, str)
|
||||
assert pack_name.isupper() # Convention: pack names should be uppercase
|
||||
|
||||
def test_all_packs_have_required_attributes(self):
|
||||
"""Test that all packs have the required DeploymentPack attributes."""
|
||||
for pack_name, pack in DEPLOYMENT_PACKS.items():
|
||||
assert isinstance(pack.dockerfile_template, str)
|
||||
assert isinstance(pack.ports, list)
|
||||
assert all(isinstance(port, int) for port in pack.ports)
|
||||
assert isinstance(pack.build_files, dict)
|
||||
|
||||
# All build file keys should be strings, values should be strings
|
||||
for key, value in pack.build_files.items():
|
||||
assert isinstance(key, str)
|
||||
assert isinstance(value, str)
|
||||
|
||||
def test_pack_names_match_constants(self):
|
||||
"""Test that DEPLOYMENT_PACKS keys match the pack constants."""
|
||||
# Ensure we have exactly the packs we expect
|
||||
expected_packs = {"FASTAPI", "CREWAI", "CREWAI_JOB"}
|
||||
actual_packs = set(DEPLOYMENT_PACKS.keys())
|
||||
assert actual_packs == expected_packs
|
||||
@@ -0,0 +1,196 @@
|
||||
"""Unit tests for event serialization and deserialization."""
|
||||
|
||||
import pytest
|
||||
from jockey.backend.event import EventStatus, deserialize_event, _registry
|
||||
from jockey.backend.models.deployment import DeploymentEvent
|
||||
from jockey.backend.models.image import BuildEvent
|
||||
from jockey.backend.models.pod import PodEvent
|
||||
from jockey.backend.models.repository import RepositoryEvent, RepositoryEventStep
|
||||
|
||||
|
||||
class TestEventSerialization:
|
||||
"""Test serialization and deserialization of all event types."""
|
||||
|
||||
def test_deployment_event_serialization(self):
|
||||
"""Test DeploymentEvent serialization and deserialization."""
|
||||
# Create a deployment event with all fields
|
||||
original_event = DeploymentEvent(
|
||||
EventStatus.PROGRESS,
|
||||
available_replicas=2,
|
||||
ready_replicas=1,
|
||||
desired_replicas=3,
|
||||
phase="Progressing",
|
||||
payload={"test_data": "deployment_test"},
|
||||
)
|
||||
|
||||
# Serialize the event
|
||||
serialized = original_event.serialize()
|
||||
|
||||
# Verify serialized structure
|
||||
assert serialized["event_type"] == "deployment"
|
||||
assert serialized["status"] == "progress"
|
||||
assert serialized["payload"]["test_data"] == "deployment_test"
|
||||
assert serialized["kwargs"]["available_replicas"] == 2
|
||||
assert serialized["kwargs"]["ready_replicas"] == 1
|
||||
assert serialized["kwargs"]["desired_replicas"] == 3
|
||||
assert serialized["kwargs"]["phase"] == "Progressing"
|
||||
|
||||
# Deserialize the event
|
||||
deserialized_event = deserialize_event(serialized)
|
||||
|
||||
# Verify deserialized event
|
||||
assert deserialized_event is not None
|
||||
assert isinstance(deserialized_event, DeploymentEvent)
|
||||
assert deserialized_event.status == EventStatus.PROGRESS
|
||||
assert deserialized_event.available_replicas == 2
|
||||
assert deserialized_event.ready_replicas == 1
|
||||
assert deserialized_event.desired_replicas == 3
|
||||
assert deserialized_event.phase == "Progressing"
|
||||
assert deserialized_event.payload["test_data"] == "deployment_test"
|
||||
|
||||
def test_build_event_serialization(self):
|
||||
"""Test BuildEvent serialization and deserialization."""
|
||||
original_event = BuildEvent(
|
||||
EventStatus.PROGRESS, stream="Building layer 1/5", payload={"build_id": "abc123"}
|
||||
)
|
||||
|
||||
# Serialize the event
|
||||
serialized = original_event.serialize()
|
||||
|
||||
# Verify serialized structure
|
||||
assert serialized["event_type"] == "build"
|
||||
assert serialized["status"] == "progress"
|
||||
assert serialized["payload"]["build_id"] == "abc123"
|
||||
assert serialized["kwargs"]["stream"] == "Building layer 1/5"
|
||||
|
||||
# Deserialize the event
|
||||
deserialized_event = deserialize_event(serialized)
|
||||
|
||||
# Verify deserialized event
|
||||
assert deserialized_event is not None
|
||||
assert isinstance(deserialized_event, BuildEvent)
|
||||
assert deserialized_event.status == EventStatus.PROGRESS
|
||||
assert deserialized_event.stream == "Building layer 1/5"
|
||||
assert deserialized_event.payload["build_id"] == "abc123"
|
||||
|
||||
def test_pod_event_serialization(self):
|
||||
"""Test PodEvent serialization and deserialization."""
|
||||
original_event = PodEvent(
|
||||
EventStatus.PROGRESS,
|
||||
phase="MODIFIED",
|
||||
container_name="test-container",
|
||||
container_state=None,
|
||||
payload={"pod_name": "test-pod"},
|
||||
)
|
||||
|
||||
# Serialize the event
|
||||
serialized = original_event.serialize()
|
||||
|
||||
# Verify serialized structure
|
||||
assert serialized["event_type"] == "pod"
|
||||
assert serialized["status"] == "progress"
|
||||
assert serialized["payload"]["pod_name"] == "test-pod"
|
||||
assert serialized["kwargs"]["phase"] == "MODIFIED"
|
||||
assert serialized["kwargs"]["container_name"] == "test-container"
|
||||
assert serialized["kwargs"]["container_state"] is None
|
||||
|
||||
# Deserialize the event
|
||||
deserialized_event = deserialize_event(serialized)
|
||||
|
||||
# Verify deserialized event
|
||||
assert deserialized_event is not None
|
||||
assert isinstance(deserialized_event, PodEvent)
|
||||
assert deserialized_event.status == EventStatus.PROGRESS
|
||||
assert deserialized_event.phase == "MODIFIED"
|
||||
assert deserialized_event.container_name == "test-container"
|
||||
assert deserialized_event.container_state is None
|
||||
assert deserialized_event.payload["pod_name"] == "test-pod"
|
||||
|
||||
def test_repository_event_serialization(self):
|
||||
"""Test RepositoryEvent serialization and deserialization."""
|
||||
original_event = RepositoryEvent(
|
||||
EventStatus.PROGRESS,
|
||||
step=RepositoryEventStep.CLONING,
|
||||
payload={"repo_url": "https://github.com/test/repo"},
|
||||
)
|
||||
|
||||
# Serialize the event
|
||||
serialized = original_event.serialize()
|
||||
|
||||
# Verify serialized structure
|
||||
assert serialized["event_type"] == "repository"
|
||||
assert serialized["status"] == "progress"
|
||||
assert serialized["payload"]["repo_url"] == "https://github.com/test/repo"
|
||||
assert serialized["kwargs"]["step"] == "cloning" # Enum gets converted to string
|
||||
|
||||
# Deserialize the event
|
||||
deserialized_event = deserialize_event(serialized)
|
||||
|
||||
# Verify deserialized event
|
||||
assert deserialized_event is not None
|
||||
assert isinstance(deserialized_event, RepositoryEvent)
|
||||
assert deserialized_event.status == EventStatus.PROGRESS
|
||||
assert deserialized_event.step == "cloning" # Will be a string after deserialization
|
||||
assert deserialized_event.payload["repo_url"] == "https://github.com/test/repo"
|
||||
|
||||
def test_all_registered_event_types(self):
|
||||
"""Test that all expected event types are registered."""
|
||||
expected_types = {"deployment", "build", "pod", "repository"}
|
||||
|
||||
# Get all registered event types
|
||||
registered_types = set(_registry.keys())
|
||||
|
||||
# Verify all expected types are registered
|
||||
assert expected_types.issubset(registered_types)
|
||||
|
||||
# Verify each registered type has a valid class
|
||||
for event_type, event_class in _registry.items():
|
||||
assert hasattr(event_class, 'event_type')
|
||||
assert event_class.event_type == event_type
|
||||
|
||||
def test_unknown_event_type_deserialization(self):
|
||||
"""Test that unknown event types raise ValueError."""
|
||||
fake_serialized = {
|
||||
"event_type": "unknown_type",
|
||||
"status": "progress",
|
||||
"message": "Test message",
|
||||
"payload": {},
|
||||
"kwargs": {},
|
||||
}
|
||||
|
||||
# Should raise ValueError for unknown type
|
||||
with pytest.raises(ValueError):
|
||||
deserialize_event(fake_serialized)
|
||||
|
||||
def test_message_preservation(self):
|
||||
"""Test that messages are preserved through serialization/deserialization."""
|
||||
# Create an event with an exception (fresh event should use format_message)
|
||||
original_event = DeploymentEvent(
|
||||
EventStatus.ERROR,
|
||||
available_replicas=0,
|
||||
ready_replicas=0,
|
||||
desired_replicas=1,
|
||||
exception=ValueError("Connection timeout"),
|
||||
payload={"error_context": "test"},
|
||||
)
|
||||
|
||||
# Get the dynamic message (should include exception info)
|
||||
original_message = original_event.message
|
||||
assert "Connection timeout" in original_message
|
||||
|
||||
# Serialize the event
|
||||
serialized = original_event.serialize()
|
||||
|
||||
# Verify the computed message is stored in serialized data
|
||||
assert serialized["message"] == original_message
|
||||
|
||||
# Deserialize the event
|
||||
deserialized_event = deserialize_event(serialized)
|
||||
|
||||
# Verify deserialized event has the exact same message
|
||||
assert deserialized_event is not None
|
||||
assert deserialized_event.message == original_message
|
||||
assert "Connection timeout" in deserialized_event.message
|
||||
|
||||
# The deserialized event should use the stored message, not format_message
|
||||
assert deserialized_event._message == original_message
|
||||
@@ -0,0 +1,183 @@
|
||||
"""
|
||||
Integration tests for the DeploymentRedisClient against a real Redis instance.
|
||||
|
||||
These tests use Docker containers to provide a clean Redis instance for testing.
|
||||
Run with: pytest tests/test_integration.py -m integration
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import time
|
||||
from datetime import datetime, UTC
|
||||
|
||||
from jockey.backend.event import EventStatus, BaseEvent, register_event
|
||||
|
||||
|
||||
class SimpleEvent(BaseEvent):
|
||||
"""Simple test event for integration testing."""
|
||||
|
||||
event_type = "integration_test"
|
||||
|
||||
def __init__(self, status: EventStatus, event_id: str, **kwargs):
|
||||
payload = kwargs.pop('payload', {})
|
||||
payload["event_id"] = event_id
|
||||
super().__init__(status, payload=payload, **kwargs)
|
||||
self.event_id = event_id
|
||||
|
||||
def format_message(self) -> str:
|
||||
return f"Test event: {self.event_id}"
|
||||
|
||||
|
||||
# Register the test event class
|
||||
register_event(SimpleEvent)
|
||||
|
||||
|
||||
@pytest.mark.integration
|
||||
class TestRedisIntegration:
|
||||
"""Integration tests using containerized Redis."""
|
||||
|
||||
def test_redis_connection(self, redis_client_with_container):
|
||||
"""Test that we can connect to Redis container."""
|
||||
result = redis_client_with_container.ping()
|
||||
assert result is True
|
||||
|
||||
def test_store_and_retrieve_events(self, clean_redis):
|
||||
"""Test storing and retrieving events end-to-end."""
|
||||
from jockey.worker.queue import queue_task
|
||||
from jockey.config import DeploymentConfig, TaskType
|
||||
|
||||
# Create a job first
|
||||
config = DeploymentConfig(
|
||||
project_id="test-project-id",
|
||||
namespace="integration_test",
|
||||
)
|
||||
job_id = queue_task(TaskType.SERVE, config, "test-project-id")
|
||||
|
||||
# Store multiple events
|
||||
events = [
|
||||
SimpleEvent(EventStatus.STARTED, "event_1"),
|
||||
SimpleEvent(EventStatus.PROGRESS, "event_2"),
|
||||
SimpleEvent(EventStatus.PROGRESS, "event_3"),
|
||||
SimpleEvent(EventStatus.COMPLETED, "event_4"),
|
||||
]
|
||||
|
||||
# Store events with small delays to ensure different timestamps
|
||||
for event in events:
|
||||
clean_redis.store_event(job_id, event)
|
||||
time.sleep(0.1) # Small delay to to timestamp ordering
|
||||
|
||||
# Retrieve all events
|
||||
retrieved_events = clean_redis.get_task_events(job_id)
|
||||
|
||||
# Verify all events were stored and retrieved
|
||||
assert len(retrieved_events) == 4
|
||||
|
||||
# Verify newest first ordering using payload data
|
||||
assert retrieved_events[0].payload["event_id"] == "event_4"
|
||||
assert retrieved_events[-1].payload["event_id"] == "event_1"
|
||||
|
||||
# Verify status retrieval
|
||||
status_event = clean_redis.get_task_status(job_id)
|
||||
assert status_event is not None
|
||||
assert status_event.status == EventStatus.COMPLETED
|
||||
|
||||
def test_timestamp_filtering(self, clean_redis):
|
||||
"""Test timestamp-based event filtering."""
|
||||
from jockey.worker.queue import queue_task
|
||||
from jockey.config import DeploymentConfig, TaskType
|
||||
|
||||
# Create a job first
|
||||
config = DeploymentConfig(
|
||||
project_id="test-project-id",
|
||||
namespace="integration_test",
|
||||
)
|
||||
job_id = queue_task(TaskType.SERVE, config, "test-project-id")
|
||||
|
||||
# Store events with known timestamps
|
||||
start_time = datetime.now(UTC)
|
||||
|
||||
# Store initial events
|
||||
clean_redis.store_event(job_id, SimpleEvent(EventStatus.STARTED, "before_filter"))
|
||||
time.sleep(1)
|
||||
|
||||
filter_time = datetime.now(UTC)
|
||||
time.sleep(1)
|
||||
|
||||
# Store events after filter time
|
||||
clean_redis.store_event(job_id, SimpleEvent(EventStatus.PROGRESS, "after_filter_1"))
|
||||
clean_redis.store_event(job_id, SimpleEvent(EventStatus.COMPLETED, "after_filter_2"))
|
||||
|
||||
# Get all events
|
||||
all_events = clean_redis.get_task_events(job_id)
|
||||
assert len(all_events) == 3
|
||||
|
||||
# Get events after filter time
|
||||
filtered_events = clean_redis.get_task_events(job_id, filter_time)
|
||||
|
||||
# Should only get the 2 events after filter_time
|
||||
assert len(filtered_events) == 2
|
||||
assert filtered_events[1].payload["event_id"] == "after_filter_1"
|
||||
assert filtered_events[0].payload["event_id"] == "after_filter_2"
|
||||
|
||||
def test_event_cleanup(self, clean_redis):
|
||||
"""Test that all events are kept (current implementation has no cleanup)."""
|
||||
from jockey.worker.queue import queue_task
|
||||
from jockey.config import DeploymentConfig, TaskType
|
||||
|
||||
# Create a job first
|
||||
config = DeploymentConfig(
|
||||
project_id="test-project-id",
|
||||
namespace="integration_test",
|
||||
)
|
||||
job_id = queue_task(TaskType.SERVE, config, "test-project-id")
|
||||
|
||||
# Store multiple events
|
||||
for i in range(10): # Smaller number to keep test fast
|
||||
event = SimpleEvent(EventStatus.PROGRESS, f"cleanup_event_{i}")
|
||||
clean_redis.store_event(job_id, event)
|
||||
|
||||
# Verify all events are kept (no cleanup in current implementation)
|
||||
all_events = clean_redis.get_task_events(job_id)
|
||||
assert len(all_events) == 10
|
||||
|
||||
# Verify newest events first (should have high numbers)
|
||||
newest_event = all_events[0]
|
||||
assert newest_event.payload["event_id"] == "cleanup_event_9" # Should be the last event stored
|
||||
|
||||
def test_real_event_types(self, clean_redis):
|
||||
"""Test with actual event types from the system."""
|
||||
from jockey.worker.queue import queue_task
|
||||
from jockey.config import DeploymentConfig, TaskType
|
||||
|
||||
# Create a job first
|
||||
config = DeploymentConfig(
|
||||
project_id="test-project-id",
|
||||
namespace="integration_test",
|
||||
)
|
||||
job_id = queue_task(TaskType.SERVE, config, "test-project-id")
|
||||
|
||||
# Store different event types
|
||||
completion_event = SimpleEvent(EventStatus.COMPLETED, "completion_test")
|
||||
error_event = SimpleEvent(EventStatus.ERROR, "error_test")
|
||||
|
||||
clean_redis.store_event(job_id, completion_event)
|
||||
clean_redis.store_event(job_id, error_event)
|
||||
|
||||
# Retrieve and verify
|
||||
events = clean_redis.get_task_events(job_id)
|
||||
assert len(events) == 2
|
||||
|
||||
# Verify event types and data
|
||||
error_event = events[0] # Most recent
|
||||
completion_event = events[1]
|
||||
|
||||
assert error_event.event_type == "integration_test"
|
||||
assert error_event.status == EventStatus.ERROR
|
||||
assert error_event.payload["event_id"] == "error_test"
|
||||
|
||||
assert completion_event.event_type == "integration_test"
|
||||
assert completion_event.status == EventStatus.COMPLETED
|
||||
assert completion_event.payload["event_id"] == "completion_test"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pytest.main([__file__, "-v", "-m", "integration"])
|
||||
@@ -0,0 +1,261 @@
|
||||
"""Unit tests for the queue module."""
|
||||
|
||||
import json
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch
|
||||
from datetime import datetime, UTC
|
||||
|
||||
from jockey.worker.queue import (
|
||||
queue_task,
|
||||
claim_next_task,
|
||||
get_task_data,
|
||||
get_queue_length,
|
||||
get_queued_tasks,
|
||||
_get_task_key,
|
||||
_get_queue_key,
|
||||
_get_event_key,
|
||||
TASKS_HASH_NAME,
|
||||
REDIS_KEY_PREFIX,
|
||||
)
|
||||
from jockey.config import DeploymentConfig, TaskType
|
||||
|
||||
|
||||
class TestQueueOperations:
|
||||
"""Test the core queue operations."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_redis(self):
|
||||
"""Mock Redis client for testing."""
|
||||
with patch('jockey.worker.queue._get_redis_client') as mock_get_client:
|
||||
mock_client = Mock()
|
||||
mock_get_client.return_value = mock_client
|
||||
yield mock_client
|
||||
|
||||
@pytest.fixture
|
||||
def sample_config(self):
|
||||
"""Sample deployment configuration for testing."""
|
||||
return DeploymentConfig(
|
||||
project_id="test-project-id",
|
||||
namespace="test-namespace",
|
||||
ports=[8080, 9090],
|
||||
replicas=2,
|
||||
)
|
||||
|
||||
def test_queue_task_creates_job_data_and_queues_id(self, mock_redis, sample_config):
|
||||
"""Test that queue_task creates job data and adds job ID to queue."""
|
||||
# Setup
|
||||
mock_redis.hset.return_value = True
|
||||
mock_redis.rpush.return_value = 1
|
||||
|
||||
# Execute
|
||||
job_id = queue_task(TaskType.SERVE, sample_config, "project-456")
|
||||
|
||||
# Verify job ID format (full UUID)
|
||||
assert len(job_id) == 36 # Full UUID string
|
||||
assert job_id.count('-') == 4 # UUID format
|
||||
|
||||
# Verify job data was stored in composite hash
|
||||
assert mock_redis.hset.call_count == 1
|
||||
hash_call = mock_redis.hset.call_args
|
||||
hash_name = hash_call[0][0]
|
||||
composite_key = hash_call[0][1]
|
||||
job_data_json = hash_call[0][2]
|
||||
|
||||
assert hash_name == TASKS_HASH_NAME
|
||||
assert composite_key == f"test-namespace:project-456:{job_id}"
|
||||
|
||||
# Parse and verify job data
|
||||
job_data = json.loads(job_data_json)
|
||||
assert job_data["job_id"] == job_id
|
||||
assert job_data["project_id"] == "project-456"
|
||||
assert job_data["namespace"] == "test-namespace"
|
||||
assert "queued_at" in job_data
|
||||
assert "config" in job_data
|
||||
|
||||
# Verify config was serialized
|
||||
config_data = job_data["config"]
|
||||
assert config_data["project_id"] == "test-project-id"
|
||||
assert config_data["namespace"] == "test-namespace"
|
||||
assert config_data["ports"] == [8080, 9090]
|
||||
assert config_data["replicas"] == 2
|
||||
|
||||
# Verify job ID was added to queue
|
||||
assert mock_redis.rpush.call_count == 1
|
||||
queue_call = mock_redis.rpush.call_args
|
||||
assert queue_call[0][0] == _get_queue_key()
|
||||
assert queue_call[0][1] == job_id
|
||||
|
||||
def test_claim_next_task_returns_job_data(self, mock_redis, sample_config):
|
||||
"""Test that claim_next_task returns job data for next job."""
|
||||
# Setup
|
||||
test_job_id = "abcd1234"
|
||||
mock_job_data = {
|
||||
"job_id": test_job_id,
|
||||
"project_id": "project-456",
|
||||
"namespace": "test-namespace",
|
||||
"queued_at": datetime.now(UTC).isoformat(),
|
||||
"config": sample_config.serialize(),
|
||||
}
|
||||
|
||||
mock_redis.lpop.return_value = test_job_id
|
||||
# Mock hscan to return the job data - hscan returns (cursor, fields_dict)
|
||||
mock_redis.hscan.return_value = (0, {f"test-namespace:project-456:{test_job_id}": json.dumps(mock_job_data)})
|
||||
|
||||
# Execute
|
||||
job_data = claim_next_task()
|
||||
|
||||
# Verify
|
||||
assert job_data is not None
|
||||
assert job_data["job_id"] == test_job_id
|
||||
# deployment_id field has been removed, only project_id remains
|
||||
assert job_data["project_id"] == "project-456"
|
||||
assert job_data["namespace"] == "test-namespace"
|
||||
|
||||
# Verify Redis calls
|
||||
mock_redis.lpop.assert_called_once_with(_get_queue_key())
|
||||
mock_redis.hscan.assert_called_once_with(TASKS_HASH_NAME, 0, match=f"*:*:{test_job_id}")
|
||||
|
||||
def test_claim_next_task_returns_none_when_queue_empty(self, mock_redis):
|
||||
"""Test that claim_next_task returns None when queue is empty."""
|
||||
# Setup
|
||||
mock_redis.lpop.return_value = None
|
||||
|
||||
# Execute
|
||||
job_data = claim_next_task()
|
||||
|
||||
# Verify
|
||||
assert job_data is None
|
||||
mock_redis.lpop.assert_called_once_with(_get_queue_key())
|
||||
mock_redis.hget.assert_not_called()
|
||||
|
||||
def test_claim_next_task_logs_error_when_job_data_missing(self, mock_redis):
|
||||
"""Test that claim_next_task logs error when job data is missing."""
|
||||
# Setup
|
||||
test_job_id = "abcd1234"
|
||||
mock_redis.lpop.return_value = test_job_id
|
||||
# Mock hscan to return no job data - hscan returns (cursor, fields_dict)
|
||||
mock_redis.hscan.return_value = (0, {})
|
||||
|
||||
# Execute
|
||||
with patch('jockey.worker.queue.logger') as mock_logger:
|
||||
job_data = claim_next_task()
|
||||
|
||||
# Verify
|
||||
assert job_data is None
|
||||
mock_logger.error.assert_called_once_with(
|
||||
f"Task {test_job_id} was in queue but task data not found in hash"
|
||||
)
|
||||
|
||||
def test_get_task_data_returns_job_data(self, mock_redis, sample_config):
|
||||
"""Test that get_task_data returns job data for a given job ID."""
|
||||
# Setup
|
||||
test_job_id = "abcd1234"
|
||||
mock_job_data = {
|
||||
"job_id": test_job_id,
|
||||
"project_id": "project-456",
|
||||
"namespace": "test-namespace",
|
||||
"queued_at": datetime.now(UTC).isoformat(),
|
||||
"config": sample_config.serialize(),
|
||||
}
|
||||
|
||||
# Mock hscan to return the job data - hscan returns (cursor, fields_dict)
|
||||
mock_redis.hscan.return_value = (0, {f"test-namespace:project-456:{test_job_id}": json.dumps(mock_job_data)})
|
||||
|
||||
# Execute
|
||||
job_data = get_task_data(test_job_id)
|
||||
|
||||
# Verify
|
||||
assert job_data is not None
|
||||
assert job_data["job_id"] == test_job_id
|
||||
assert job_data["namespace"] == "test-namespace"
|
||||
|
||||
mock_redis.hscan.assert_called_once_with(TASKS_HASH_NAME, 0, match=f"*:*:{test_job_id}")
|
||||
|
||||
def test_get_task_data_returns_none_when_not_found(self, mock_redis):
|
||||
"""Test that get_task_data returns None when job data not found."""
|
||||
# Setup
|
||||
test_job_id = "abcd1234"
|
||||
# Mock hscan to return no job data - hscan returns (cursor, fields_dict)
|
||||
mock_redis.hscan.return_value = (0, {})
|
||||
|
||||
# Execute
|
||||
job_data = get_task_data(test_job_id)
|
||||
|
||||
# Verify
|
||||
assert job_data is None
|
||||
mock_redis.hscan.assert_called_once_with(TASKS_HASH_NAME, 0, match=f"*:*:{test_job_id}")
|
||||
|
||||
def test_get_queue_length_returns_queue_length(self, mock_redis):
|
||||
"""Test that get_queue_length returns the number of jobs in queue."""
|
||||
# Setup
|
||||
mock_redis.llen.return_value = 5
|
||||
|
||||
# Execute
|
||||
length = get_queue_length()
|
||||
|
||||
# Verify
|
||||
assert length == 5
|
||||
mock_redis.llen.assert_called_once_with(_get_queue_key())
|
||||
|
||||
def test_get_queued_tasks_returns_job_ids(self, mock_redis):
|
||||
"""Test that get_queued_tasks returns list of job IDs."""
|
||||
# Setup
|
||||
mock_job_ids = ["abcd1234", "efgh5678", "ijkl9012"]
|
||||
mock_redis.lrange.return_value = mock_job_ids
|
||||
|
||||
# Execute
|
||||
job_ids = get_queued_tasks()
|
||||
|
||||
# Verify
|
||||
assert job_ids == mock_job_ids
|
||||
mock_redis.lrange.assert_called_once_with(_get_queue_key(), 0, -1)
|
||||
|
||||
def test_get_job_key_generates_correct_key(self):
|
||||
"""Test that _get_job_key generates correct Redis key."""
|
||||
namespace = "test-namespace"
|
||||
project_id = "project-456"
|
||||
job_id = "abcd1234"
|
||||
key = _get_task_key(namespace, project_id, job_id)
|
||||
assert key == f"{namespace}:{project_id}:{job_id}"
|
||||
|
||||
def test_job_data_includes_namespace(self, mock_redis, sample_config):
|
||||
"""Test that job data includes namespace from config."""
|
||||
# Setup
|
||||
mock_redis.hset.return_value = True
|
||||
mock_redis.rpush.return_value = 1
|
||||
|
||||
# Execute
|
||||
job_id = queue_task(TaskType.SERVE, sample_config, "project-456")
|
||||
|
||||
# Verify namespace is included
|
||||
hash_call = mock_redis.hset.call_args
|
||||
job_data_json = hash_call[0][2]
|
||||
job_data = json.loads(job_data_json)
|
||||
|
||||
assert job_data["namespace"] == "test-namespace"
|
||||
|
||||
def test_job_data_type_annotation(self, mock_redis, sample_config):
|
||||
"""Test that job data structure matches JobData TypedDict."""
|
||||
# Setup
|
||||
mock_redis.hset.return_value = True
|
||||
mock_redis.rpush.return_value = 1
|
||||
|
||||
# Execute
|
||||
job_id = queue_task(TaskType.SERVE, sample_config, "project-456")
|
||||
|
||||
# Get the job data that was stored
|
||||
hash_call = mock_redis.hset.call_args
|
||||
job_data_json = hash_call[0][2]
|
||||
job_data = json.loads(job_data_json)
|
||||
|
||||
# Verify all required JobData fields are present
|
||||
required_fields = ["job_id", "project_id", "namespace", "config", "queued_at"]
|
||||
for field in required_fields:
|
||||
assert field in job_data, f"Missing required field: {field}"
|
||||
|
||||
# Verify types (as much as we can from JSON)
|
||||
assert isinstance(job_data["job_id"], str)
|
||||
assert isinstance(job_data["project_id"], str)
|
||||
assert isinstance(job_data["namespace"], str)
|
||||
assert isinstance(job_data["config"], dict)
|
||||
assert isinstance(job_data["queued_at"], str)
|
||||
@@ -0,0 +1,375 @@
|
||||
"""
|
||||
Integration tests for the queue module using real Redis in Docker.
|
||||
|
||||
These tests verify the complete job lifecycle and event system using a real Redis instance.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import time
|
||||
import json
|
||||
from datetime import datetime, UTC
|
||||
from unittest.mock import Mock
|
||||
|
||||
from jockey.config import DeploymentConfig, TaskType
|
||||
from jockey.worker.queue import (
|
||||
queue_task,
|
||||
claim_next_task,
|
||||
get_tasks,
|
||||
get_task_data,
|
||||
get_queue_length,
|
||||
get_queued_tasks,
|
||||
store_event,
|
||||
get_task_events,
|
||||
get_task_status,
|
||||
health_check,
|
||||
TASKS_HASH_NAME,
|
||||
_get_queue_key,
|
||||
_get_task_key,
|
||||
_get_event_key,
|
||||
REDIS_KEY_PREFIX,
|
||||
)
|
||||
from jockey.backend.event import BaseEvent, EventStatus, register_event
|
||||
|
||||
|
||||
class IntegrationDeploymentEvent(BaseEvent):
|
||||
"""Test event for integration testing."""
|
||||
|
||||
event_type = "test_deployment"
|
||||
|
||||
def __init__(self, status: EventStatus, message: str = "", **kwargs):
|
||||
super().__init__(status, message=message, **kwargs)
|
||||
|
||||
def format_message(self) -> str:
|
||||
return self.message
|
||||
|
||||
|
||||
# Register the test event
|
||||
register_event(IntegrationDeploymentEvent)
|
||||
|
||||
|
||||
@pytest.mark.integration
|
||||
class TestQueueIntegration:
|
||||
"""Integration tests for queue operations with real Redis."""
|
||||
|
||||
@pytest.fixture
|
||||
def sample_config(self):
|
||||
"""Sample deployment configuration for testing."""
|
||||
return DeploymentConfig(
|
||||
project_id="test-project-id",
|
||||
namespace="integration-test",
|
||||
ports=[8080, 9090],
|
||||
replicas=2,
|
||||
repository_url="https://github.com/test/repo.git",
|
||||
branch="main",
|
||||
entrypoint="main.py",
|
||||
)
|
||||
|
||||
def test_health_check(self, redis_client_with_container):
|
||||
"""Test Redis health check functionality."""
|
||||
assert health_check() is True
|
||||
|
||||
def test_complete_job_lifecycle(self, redis_client_with_container, sample_config):
|
||||
"""Test the complete lifecycle: queue → claim → process → retrieve."""
|
||||
# 1. Queue a deployment
|
||||
project_id = "integration-test-project"
|
||||
job_id = queue_task(TaskType.SERVE, sample_config, project_id)
|
||||
|
||||
# Verify job ID is a full UUID
|
||||
assert len(job_id) == 36
|
||||
assert job_id.count('-') == 4
|
||||
|
||||
# 2. Verify job is in queue
|
||||
assert get_queue_length() == 1
|
||||
queued_jobs = get_queued_tasks()
|
||||
assert len(queued_jobs) == 1
|
||||
assert queued_jobs[0] == job_id
|
||||
|
||||
# 3. Claim the job
|
||||
claimed_job = claim_next_task()
|
||||
assert claimed_job is not None
|
||||
assert claimed_job["job_id"] == job_id
|
||||
assert claimed_job["project_id"] == project_id
|
||||
assert claimed_job["namespace"] == "integration-test"
|
||||
|
||||
# Verify job config was preserved
|
||||
config_data = claimed_job["config"]
|
||||
assert config_data["project_id"] == "test-project-id"
|
||||
assert config_data["namespace"] == "integration-test"
|
||||
|
||||
# 4. Verify queue is now empty
|
||||
assert get_queue_length() == 0
|
||||
assert get_queued_tasks() == []
|
||||
|
||||
# 5. Test that claiming from empty queue returns None
|
||||
empty_claim = claim_next_task()
|
||||
assert empty_claim is None
|
||||
|
||||
def test_job_data_persistence(self, redis_client_with_container, sample_config):
|
||||
"""Test that job data persists correctly in Redis."""
|
||||
project_id = "persistence-test"
|
||||
job_id = queue_task(TaskType.SERVE, sample_config, project_id)
|
||||
|
||||
# Test get_job_data by ID
|
||||
job_data = get_task_data(job_id)
|
||||
assert job_data is not None
|
||||
assert job_data["job_id"] == job_id
|
||||
assert job_data["project_id"] == project_id
|
||||
assert job_data["namespace"] == sample_config.namespace
|
||||
|
||||
# Verify timestamp format
|
||||
queued_at = datetime.fromisoformat(job_data["queued_at"])
|
||||
assert abs((datetime.now(UTC) - queued_at).total_seconds()) < 5
|
||||
|
||||
# Test get_jobs by project
|
||||
jobs = get_tasks(sample_config.namespace, project_id)
|
||||
assert len(jobs) == 1
|
||||
assert jobs[0]["job_id"] == job_id
|
||||
|
||||
def test_multiple_jobs_same_project(self, redis_client_with_container, sample_config):
|
||||
"""Test queuing multiple jobs for the same project."""
|
||||
project_id = "multi-job-test"
|
||||
|
||||
# Queue 3 jobs
|
||||
job_ids = []
|
||||
for i in range(3):
|
||||
config = DeploymentConfig(
|
||||
project_id=f"test-project-{i}",
|
||||
namespace="multi-test",
|
||||
)
|
||||
job_id = queue_task(TaskType.SERVE, config, project_id)
|
||||
job_ids.append(job_id)
|
||||
time.sleep(0.01) # Small delay to ensure different timestamps
|
||||
|
||||
# Verify all jobs are queued
|
||||
assert get_queue_length() == 3
|
||||
|
||||
# Get jobs for the project
|
||||
jobs = get_tasks("multi-test", project_id)
|
||||
assert len(jobs) == 3
|
||||
|
||||
# Jobs should be returned in order (implementation detail)
|
||||
returned_job_ids = [job["job_id"] for job in jobs]
|
||||
assert set(returned_job_ids) == set(job_ids)
|
||||
|
||||
# Claim all jobs and verify FIFO order
|
||||
claimed_jobs = []
|
||||
for _ in range(3):
|
||||
job = claim_next_task()
|
||||
assert job is not None
|
||||
claimed_jobs.append(job)
|
||||
|
||||
# First job queued should be first claimed (FIFO)
|
||||
assert claimed_jobs[0]["job_id"] == job_ids[0]
|
||||
assert claimed_jobs[1]["job_id"] == job_ids[1]
|
||||
assert claimed_jobs[2]["job_id"] == job_ids[2]
|
||||
|
||||
def test_event_storage_and_retrieval(self, redis_client_with_container, sample_config):
|
||||
"""Test storing and retrieving events for jobs."""
|
||||
project_id = "event-test"
|
||||
job_id = queue_task(TaskType.SERVE, sample_config, project_id)
|
||||
|
||||
# Store multiple events
|
||||
events = [
|
||||
IntegrationDeploymentEvent(EventStatus.STARTED, "Deployment started"),
|
||||
IntegrationDeploymentEvent(EventStatus.PROGRESS, "Building image"),
|
||||
IntegrationDeploymentEvent(EventStatus.PROGRESS, "Deploying to cluster"),
|
||||
IntegrationDeploymentEvent(EventStatus.COMPLETED, "Deployment completed"),
|
||||
]
|
||||
|
||||
for event in events:
|
||||
store_event(job_id, event)
|
||||
time.sleep(0.01) # Small delay for timestamp ordering
|
||||
|
||||
# Retrieve all events
|
||||
retrieved_events = get_task_events(job_id)
|
||||
assert len(retrieved_events) == 4
|
||||
|
||||
# Events should be in reverse chronological order (newest first)
|
||||
assert retrieved_events[0].status == EventStatus.COMPLETED
|
||||
assert retrieved_events[0].message == "Deployment completed"
|
||||
assert retrieved_events[-1].status == EventStatus.STARTED
|
||||
assert retrieved_events[-1].message == "Deployment started"
|
||||
|
||||
# Test get_task_status (should return latest event)
|
||||
latest_event = get_task_status(job_id)
|
||||
assert latest_event is not None
|
||||
assert latest_event.status == EventStatus.COMPLETED
|
||||
assert latest_event.message == "Deployment completed"
|
||||
|
||||
def test_event_timestamp_filtering(self, redis_client_with_container, sample_config):
|
||||
"""Test timestamp-based event filtering."""
|
||||
project_id = "timestamp-test"
|
||||
job_id = queue_task(TaskType.SERVE, sample_config, project_id)
|
||||
|
||||
# Store initial event
|
||||
store_event(job_id, IntegrationDeploymentEvent(EventStatus.STARTED, "Started"))
|
||||
time.sleep(1) # Ensure clear time separation
|
||||
|
||||
# Record filter time
|
||||
filter_time = datetime.now(UTC)
|
||||
time.sleep(1)
|
||||
|
||||
# Store events after filter time
|
||||
store_event(job_id, IntegrationDeploymentEvent(EventStatus.PROGRESS, "Building"))
|
||||
store_event(job_id, IntegrationDeploymentEvent(EventStatus.COMPLETED, "Done"))
|
||||
|
||||
# Get all events
|
||||
all_events = get_task_events(job_id)
|
||||
assert len(all_events) == 3
|
||||
|
||||
# Get events after filter time
|
||||
filtered_events = get_task_events(job_id, start_time=filter_time)
|
||||
assert len(filtered_events) == 2
|
||||
assert all(event.message in ["Building", "Done"] for event in filtered_events)
|
||||
|
||||
def test_redis_key_structure(self, redis_client_with_container, sample_config):
|
||||
"""Test that Redis keys are structured correctly."""
|
||||
project_id = "key-structure-test"
|
||||
job_id = queue_task(TaskType.SERVE, sample_config, project_id)
|
||||
|
||||
# Test key generation functions
|
||||
queue_key = _get_queue_key()
|
||||
job_key = _get_task_key(sample_config.namespace, project_id, job_id)
|
||||
event_key = _get_event_key(job_id)
|
||||
|
||||
assert queue_key == _get_queue_key()
|
||||
assert job_key == f"{sample_config.namespace}:{project_id}:{job_id}"
|
||||
assert event_key == _get_event_key(job_id)
|
||||
|
||||
# Verify actual Redis keys exist
|
||||
redis_client = redis_client_with_container
|
||||
|
||||
# Queue should contain the job ID
|
||||
assert redis_client.lrange(queue_key, 0, -1) == [job_id]
|
||||
|
||||
# Job hash should contain the job data
|
||||
job_data_raw = redis_client.hget(TASKS_HASH_NAME, job_key)
|
||||
assert job_data_raw is not None
|
||||
job_data = json.loads(job_data_raw)
|
||||
assert job_data["job_id"] == job_id
|
||||
|
||||
# Store an event and verify event key
|
||||
test_event = IntegrationDeploymentEvent(EventStatus.STARTED, "Test event")
|
||||
store_event(job_id, test_event)
|
||||
|
||||
# Event sorted set should exist
|
||||
event_count = redis_client.zcard(event_key)
|
||||
assert event_count == 1
|
||||
|
||||
def test_concurrent_job_claiming(self, redis_client_with_container, sample_config):
|
||||
"""Test that multiple workers can safely claim jobs concurrently."""
|
||||
project_id = "concurrent-test"
|
||||
|
||||
# Queue multiple jobs
|
||||
job_ids = []
|
||||
for i in range(5):
|
||||
config = DeploymentConfig(
|
||||
project_id=f"concurrent-project-{i}",
|
||||
namespace="concurrent-test",
|
||||
)
|
||||
job_id = queue_task(TaskType.SERVE, config, project_id)
|
||||
job_ids.append(job_id)
|
||||
|
||||
# Simulate concurrent claiming
|
||||
claimed_jobs = []
|
||||
for _ in range(5):
|
||||
job = claim_next_task()
|
||||
if job:
|
||||
claimed_jobs.append(job)
|
||||
|
||||
# All jobs should be claimed exactly once
|
||||
assert len(claimed_jobs) == 5
|
||||
claimed_job_ids = [job["job_id"] for job in claimed_jobs]
|
||||
assert set(claimed_job_ids) == set(job_ids)
|
||||
|
||||
# Queue should be empty
|
||||
assert get_queue_length() == 0
|
||||
assert claim_next_task() is None
|
||||
|
||||
def test_job_data_integrity(self, redis_client_with_container):
|
||||
"""Test that complex job data is preserved correctly."""
|
||||
complex_config = DeploymentConfig(
|
||||
project_id="complex-project",
|
||||
namespace="integrity-test",
|
||||
repository_url="https://github.com/complex/repo.git",
|
||||
branch="feature/complex-deployment",
|
||||
github_access_token="test-token-123",
|
||||
entrypoint="src/main.py",
|
||||
ports=[8080, 9090, 3000],
|
||||
replicas=3,
|
||||
secret_names=["db-secret", "api-key", "ssl-cert"],
|
||||
)
|
||||
|
||||
project_id = "integrity-test-project"
|
||||
job_id = queue_task(TaskType.SERVE, complex_config, project_id)
|
||||
|
||||
# Claim and verify all data is intact
|
||||
job_data = claim_next_task()
|
||||
assert job_data is not None
|
||||
|
||||
config = job_data["config"]
|
||||
assert config["project_id"] == "complex-project"
|
||||
assert config["namespace"] == "integrity-test"
|
||||
assert config["repository_url"] == "https://github.com/complex/repo.git"
|
||||
assert config["branch"] == "feature/complex-deployment"
|
||||
assert config["github_access_token"] == "test-token-123"
|
||||
assert config["entrypoint"] == "src/main.py"
|
||||
assert config["ports"] == [8080, 9090, 3000]
|
||||
assert config["replicas"] == 3
|
||||
assert config["secret_names"] == ["db-secret", "api-key", "ssl-cert"]
|
||||
|
||||
def test_event_data_integrity(self, redis_client_with_container, sample_config):
|
||||
"""Test that event data with complex payloads is preserved."""
|
||||
project_id = "event-integrity-test"
|
||||
job_id = queue_task(TaskType.SERVE, sample_config, project_id)
|
||||
|
||||
# Create event with complex payload
|
||||
complex_event = IntegrationDeploymentEvent(
|
||||
EventStatus.PROGRESS,
|
||||
"Complex deployment step",
|
||||
payload={
|
||||
"step": "image_build",
|
||||
"progress": 75,
|
||||
"details": {
|
||||
"image_size": "1.2GB",
|
||||
"layers": 12,
|
||||
"build_time": "3m45s"
|
||||
},
|
||||
"metrics": [
|
||||
{"name": "cpu_usage", "value": 85.5},
|
||||
{"name": "memory_usage", "value": 1024}
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
store_event(job_id, complex_event)
|
||||
|
||||
# Retrieve and verify data integrity
|
||||
events = get_task_events(job_id)
|
||||
assert len(events) == 1
|
||||
|
||||
retrieved_event = events[0]
|
||||
assert retrieved_event.status == EventStatus.PROGRESS
|
||||
assert retrieved_event.message == "Complex deployment step"
|
||||
assert retrieved_event.payload["step"] == "image_build"
|
||||
assert retrieved_event.payload["progress"] == 75
|
||||
assert retrieved_event.payload["details"]["image_size"] == "1.2GB"
|
||||
assert len(retrieved_event.payload["metrics"]) == 2
|
||||
|
||||
def test_error_handling(self, redis_client_with_container):
|
||||
"""Test error handling for edge cases."""
|
||||
# Test getting non-existent job
|
||||
non_existent_job = get_task_data("non-existent-job-id")
|
||||
assert non_existent_job is None
|
||||
|
||||
# Test getting events for non-existent job
|
||||
non_existent_events = get_task_events("non-existent-job-id")
|
||||
assert non_existent_events == []
|
||||
|
||||
# Test getting status for non-existent job
|
||||
non_existent_status = get_task_status("non-existent-job-id")
|
||||
assert non_existent_status is None
|
||||
|
||||
# Test getting jobs for non-existent project
|
||||
non_existent_project_jobs = get_tasks("non-existent-namespace", "non-existent-project")
|
||||
assert non_existent_project_jobs == []
|
||||
Generated
+1141
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,31 @@
|
||||
# dockerfile for worker (in the root dir because Railway makes us)
|
||||
|
||||
FROM python:3.12-slim-bookworm
|
||||
|
||||
ENV PYTHONPATH=/app
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
build-essential \
|
||||
git \
|
||||
awscli \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
|
||||
|
||||
#COPY jockey/pyproject.toml /app/
|
||||
COPY jockey /app/jockey
|
||||
|
||||
RUN uv pip install --system -e jockey
|
||||
|
||||
# Create non-root user
|
||||
RUN useradd --create-home --shell /bin/bash worker
|
||||
RUN chown -R worker:worker /app
|
||||
USER worker
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
|
||||
CMD python -m jockey.worker health
|
||||
|
||||
CMD ["sh", "-c", "python -m jockey setup-kubeconfig && python -m jockey.worker start"]
|
||||
@@ -0,0 +1,4 @@
|
||||
from .worker import Worker
|
||||
from .queue import queue_task, get_tasks
|
||||
|
||||
__all__ = ["Worker", "queue_task", "get_tasks"]
|
||||
@@ -0,0 +1,91 @@
|
||||
import click
|
||||
import signal
|
||||
import sys
|
||||
from jockey.worker.worker import Worker
|
||||
|
||||
|
||||
@click.group()
|
||||
def cli():
|
||||
"""Jockey deployment worker."""
|
||||
pass
|
||||
|
||||
|
||||
@cli.command()
|
||||
def start():
|
||||
"""Start the deployment worker to process queued jobs."""
|
||||
from jockey.environment import WORKER_POLL_INTERVAL
|
||||
|
||||
click.echo("🚀 Starting deployment worker...")
|
||||
click.echo("Press Ctrl+C to stop")
|
||||
click.echo(f"Polling interval: {WORKER_POLL_INTERVAL} seconds (from WORKER_POLL_INTERVAL env var)")
|
||||
|
||||
worker = Worker()
|
||||
|
||||
def signal_handler(signum, frame):
|
||||
click.echo("\n🛑 Received shutdown signal, stopping worker...")
|
||||
worker.stop()
|
||||
sys.exit(0)
|
||||
|
||||
signal.signal(signal.SIGINT, signal_handler)
|
||||
signal.signal(signal.SIGTERM, signal_handler)
|
||||
|
||||
try:
|
||||
worker.start()
|
||||
except KeyboardInterrupt:
|
||||
click.echo("\n🛑 Stopping deployment worker...")
|
||||
worker.stop()
|
||||
|
||||
|
||||
@cli.command()
|
||||
def status():
|
||||
"""Check worker and queue status."""
|
||||
from jockey.worker import queue
|
||||
|
||||
try:
|
||||
# Test Redis connection
|
||||
if queue.health_check():
|
||||
click.echo("✅ Redis connection: OK")
|
||||
else:
|
||||
click.echo("❌ Redis connection: Failed")
|
||||
raise click.Abort()
|
||||
|
||||
# Get pending jobs count
|
||||
pending_count = queue.get_queue_length()
|
||||
click.echo(f"📋 Pending jobs: {pending_count}")
|
||||
|
||||
# Get processing jobs count (jobs that exist but not in queue)
|
||||
all_job_keys = len(queue._get_redis_client().keys("jobs:*"))
|
||||
processing_count = all_job_keys - pending_count
|
||||
click.echo(f"⚙️ Processing jobs: {processing_count}")
|
||||
|
||||
# Simple status summary
|
||||
if pending_count > 0 or processing_count > 0:
|
||||
click.echo("📊 Queue status: Active")
|
||||
else:
|
||||
click.echo("📊 Queue status: Idle")
|
||||
|
||||
except Exception as e:
|
||||
click.echo(f"❌ Error checking status: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
@cli.command()
|
||||
def health():
|
||||
"""Health check for container monitoring."""
|
||||
from jockey.worker import queue
|
||||
|
||||
try:
|
||||
# Test Redis connection - this is our main dependency
|
||||
if queue.health_check():
|
||||
# Exit 0 for healthy
|
||||
sys.exit(0)
|
||||
else:
|
||||
# Exit 1 for unhealthy
|
||||
sys.exit(1)
|
||||
except Exception:
|
||||
# Exit 1 for any errors
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
cli()
|
||||
@@ -0,0 +1,359 @@
|
||||
from typing import Optional, TypedDict
|
||||
import threading
|
||||
from datetime import datetime, UTC
|
||||
import uuid
|
||||
import json
|
||||
import redis
|
||||
|
||||
from jockey.backend.event import BaseEvent, SerializedEvent, deserialize_event
|
||||
from jockey.config import DeploymentConfig, SerializedDeploymentConfig, TaskType
|
||||
from jockey.log import logger
|
||||
from jockey.environment import REDIS_HOST, REDIS_PORT, REDIS_DB, REDIS_USER, REDIS_PASSWORD
|
||||
|
||||
|
||||
# Redis key constants
|
||||
REDIS_KEY_PREFIX: str = "deployment"
|
||||
TASKS_HASH_NAME: str = f"{REDIS_KEY_PREFIX}:metadata"
|
||||
|
||||
|
||||
class JobData(TypedDict):
|
||||
"""Type definition for stored job data structure."""
|
||||
|
||||
job_id: str
|
||||
project_id: str # Links to upstream app/project
|
||||
namespace: str # Kubernetes namespace for deployment
|
||||
config: SerializedDeploymentConfig
|
||||
queued_at: str
|
||||
job_type: str # JobType enum value
|
||||
inputs: Optional[dict]
|
||||
callback_url: Optional[str]
|
||||
|
||||
|
||||
class EventData(TypedDict):
|
||||
"""Type definition for stored event data structure."""
|
||||
|
||||
project_id: str
|
||||
namespace: str
|
||||
event: SerializedEvent
|
||||
timestamp: str # ISO timestamp when event was stored
|
||||
|
||||
|
||||
# Thread-safe lazy initialization for Redis client
|
||||
_redis_client: Optional[redis.Redis] = None
|
||||
_redis_lock = threading.Lock()
|
||||
|
||||
|
||||
def _get_redis_client() -> redis.Redis:
|
||||
"""Get Redis client instance with thread-safe lazy initialization.
|
||||
|
||||
Returns:
|
||||
Redis client instance
|
||||
"""
|
||||
global _redis_client
|
||||
|
||||
if _redis_client is None:
|
||||
with _redis_lock:
|
||||
if _redis_client is None:
|
||||
_redis_client = redis.Redis(
|
||||
host=REDIS_HOST,
|
||||
port=REDIS_PORT,
|
||||
db=REDIS_DB,
|
||||
username=REDIS_USER,
|
||||
password=REDIS_PASSWORD,
|
||||
decode_responses=True,
|
||||
)
|
||||
|
||||
return _redis_client
|
||||
|
||||
|
||||
def _get_queue_key() -> str:
|
||||
"""Generate Redis key for the task queue.
|
||||
|
||||
Returns:
|
||||
Redis key for the task queue
|
||||
"""
|
||||
return f"{REDIS_KEY_PREFIX}:queue"
|
||||
|
||||
|
||||
def _get_task_key(namespace: str, project_id: str, task_id: str) -> str:
|
||||
"""Generate Redis composite key for a task.
|
||||
|
||||
Args:
|
||||
namespace: Kubernetes namespace
|
||||
project_id: Project identifier
|
||||
task_id: Task identifier
|
||||
|
||||
Returns:
|
||||
Redis composite key for task data
|
||||
"""
|
||||
return f"{namespace}:{project_id}:{task_id}"
|
||||
|
||||
|
||||
def _get_event_key(task_id: str) -> str:
|
||||
"""Generate Redis key for task events list.
|
||||
|
||||
Args:
|
||||
task_id: Task identifier
|
||||
|
||||
Returns:
|
||||
Redis key for events
|
||||
"""
|
||||
return f"{REDIS_KEY_PREFIX}:events:{task_id}"
|
||||
|
||||
|
||||
def queue_task(
|
||||
task_type: TaskType,
|
||||
config: DeploymentConfig,
|
||||
project_id: str | uuid.UUID,
|
||||
inputs: Optional[dict] = None,
|
||||
callback_url: Optional[str] = None,
|
||||
) -> str:
|
||||
"""Queue a task for background processing.
|
||||
|
||||
Args:
|
||||
task_type: Type of task to execute (build, serve, or run)
|
||||
config: Task configuration snapshot
|
||||
project_id: Project identifier
|
||||
inputs: Optional input data for run tasks
|
||||
|
||||
Returns:
|
||||
Task ID for tracking
|
||||
"""
|
||||
task_id = str(uuid.uuid4())
|
||||
|
||||
# Create task data with queue-specific fields
|
||||
task_data: JobData = {
|
||||
"job_id": task_id,
|
||||
"project_id": str(project_id),
|
||||
"namespace": config.namespace,
|
||||
"queued_at": datetime.now(UTC).isoformat(),
|
||||
"config": config.serialize(),
|
||||
"job_type": task_type.value,
|
||||
"inputs": inputs,
|
||||
"callback_url": callback_url,
|
||||
}
|
||||
|
||||
# Store task data in composite hash
|
||||
composite_key = _get_task_key(config.namespace, str(project_id), task_id)
|
||||
redis_client = _get_redis_client()
|
||||
redis_client.hset(TASKS_HASH_NAME, composite_key, json.dumps(task_data))
|
||||
|
||||
# Add task ID to queue for processing order
|
||||
redis_client.rpush(_get_queue_key(), task_id)
|
||||
|
||||
logger.info(f"Queued {task_type.value} task {task_id} for project {project_id}")
|
||||
return task_id
|
||||
|
||||
|
||||
def claim_next_task() -> Optional[JobData]:
|
||||
"""Claim the next task from the queue.
|
||||
|
||||
This operation is atomic because Redis LPOP removes and returns the leftmost
|
||||
element in a single operation. Multiple workers can safely call this function
|
||||
concurrently without risk of claiming the same task, as Redis processes one
|
||||
command at a time and LPOP guarantees only one worker will receive each task ID.
|
||||
|
||||
Returns:
|
||||
Task data dictionary or None if queue is empty
|
||||
"""
|
||||
if not (task_id := _get_redis_client().lpop(_get_queue_key())):
|
||||
return None
|
||||
|
||||
if task_data := get_task_data(task_id):
|
||||
return task_data
|
||||
|
||||
logger.error(f"Task {task_id} was in queue but task data not found in hash")
|
||||
return None
|
||||
|
||||
|
||||
def get_tasks(
|
||||
namespace: str,
|
||||
project_id: str,
|
||||
) -> list[JobData]:
|
||||
"""Get all tasks for a specific project.
|
||||
|
||||
Args:
|
||||
namespace: Kubernetes namespace
|
||||
project_id: Project identifier
|
||||
|
||||
Returns:
|
||||
List of task data dictionaries ordered by newest first
|
||||
"""
|
||||
tasks, cursor = [], 0
|
||||
while True:
|
||||
cursor, fields = _get_redis_client().hscan(
|
||||
TASKS_HASH_NAME,
|
||||
cursor,
|
||||
match=f"{namespace}:{project_id}:*",
|
||||
)
|
||||
|
||||
for _, task_data in fields.items():
|
||||
try:
|
||||
tasks.append(JobData(**json.loads(task_data)))
|
||||
except (json.JSONDecodeError, KeyError, TypeError):
|
||||
logger.error("Invalid task data")
|
||||
continue
|
||||
|
||||
if cursor == 0:
|
||||
break
|
||||
|
||||
return tasks
|
||||
|
||||
|
||||
def get_task_data(task_id: str) -> Optional[JobData]:
|
||||
"""Get task data by task ID.
|
||||
|
||||
Args:
|
||||
task_id: Task identifier
|
||||
|
||||
Returns:
|
||||
Task data dictionary or None if not found
|
||||
"""
|
||||
cursor = 0
|
||||
|
||||
while True:
|
||||
cursor, fields = _get_redis_client().hscan(
|
||||
TASKS_HASH_NAME,
|
||||
cursor,
|
||||
match=f"*:*:{task_id}",
|
||||
)
|
||||
|
||||
for _, task_data in fields.items():
|
||||
try:
|
||||
return JobData(**json.loads(task_data))
|
||||
except (json.JSONDecodeError, KeyError, TypeError):
|
||||
continue
|
||||
|
||||
if cursor == 0:
|
||||
break
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def get_queue_length() -> int:
|
||||
"""Get the number of tasks waiting in the queue.
|
||||
|
||||
Returns:
|
||||
Number of tasks in queue
|
||||
"""
|
||||
return _get_redis_client().llen(_get_queue_key()) # type: ignore
|
||||
|
||||
|
||||
def get_queued_tasks() -> list[str]:
|
||||
"""Get all task IDs currently in the queue.
|
||||
|
||||
Returns:
|
||||
List of task IDs waiting to be processed
|
||||
"""
|
||||
return _get_redis_client().lrange(_get_queue_key(), 0, -1) # type: ignore
|
||||
|
||||
|
||||
def get_processing_count() -> int:
|
||||
"""Get the number of tasks currently being processed.
|
||||
|
||||
Returns:
|
||||
Number of tasks being processed (tasks that exist but are not in queue)
|
||||
"""
|
||||
# Get all task keys and queued task IDs
|
||||
all_task_keys = len(_get_redis_client().keys(f"{REDIS_KEY_PREFIX}:*")) # type: ignore
|
||||
queued_count = get_queue_length()
|
||||
|
||||
# Processing tasks = total tasks - queued tasks
|
||||
return max(0, all_task_keys - queued_count)
|
||||
|
||||
|
||||
def store_event(task_id: str, event: BaseEvent) -> None:
|
||||
"""Store a task event in Redis using sorted sets for timestamp-based queries.
|
||||
|
||||
Args:
|
||||
task_id: Task identifier
|
||||
event: Event to store
|
||||
"""
|
||||
# Get task data to find namespace and project_id
|
||||
task_data = get_task_data(task_id)
|
||||
if not task_data:
|
||||
logger.error(f"Cannot store event for task {task_id}: task not found")
|
||||
return
|
||||
|
||||
timestamp = datetime.now(UTC)
|
||||
data: EventData = {
|
||||
"namespace": task_data["namespace"],
|
||||
"project_id": task_data["project_id"],
|
||||
"timestamp": timestamp.isoformat(),
|
||||
"event": event.serialize(),
|
||||
}
|
||||
|
||||
_get_redis_client().zadd(
|
||||
_get_event_key(task_id),
|
||||
{json.dumps(data): timestamp.timestamp()},
|
||||
)
|
||||
|
||||
|
||||
def get_task_status(task_id: str) -> Optional[BaseEvent]:
|
||||
"""Get the latest task status by getting the most recent event.
|
||||
|
||||
Args:
|
||||
task_id: Task identifier
|
||||
|
||||
Returns:
|
||||
EventStatus enum value from the most recent event or None
|
||||
"""
|
||||
# Get the highest scored (most recent) event from sorted set
|
||||
latest_events = _get_redis_client().zrevrange(_get_event_key(task_id), 0, 0)
|
||||
|
||||
try:
|
||||
event_data = json.loads(latest_events[0]) # type: ignore
|
||||
return deserialize_event(event_data["event"])
|
||||
except (IndexError, json.JSONDecodeError, KeyError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def get_task_events(
|
||||
task_id: str,
|
||||
start_time: Optional[datetime] = None,
|
||||
) -> list[BaseEvent]:
|
||||
"""Get task events history, optionally filtered by start time using Redis native operations.
|
||||
|
||||
Args:
|
||||
task_id: Task identifier
|
||||
start_time: Optional datetime object - return events after this time
|
||||
|
||||
Returns:
|
||||
List of BaseEvent instances, newest first
|
||||
"""
|
||||
key = _get_event_key(task_id)
|
||||
|
||||
if start_time:
|
||||
# Use Redis native range query: get events with timestamp > start_timestamp
|
||||
# zrevrangebyscore returns in descending order (newest first)
|
||||
# First arg is max, second is min. Add small epsilon to exclude exact timestamp
|
||||
min_score = start_time.timestamp() + 1e-9 # Use smallest possible increment
|
||||
events_json = _get_redis_client().zrevrangebyscore(key, '+inf', min_score)
|
||||
else:
|
||||
# Get all events in descending order (newest first)
|
||||
events_json = _get_redis_client().zrevrange(key, 0, -1)
|
||||
|
||||
events = []
|
||||
for event_json in events_json:
|
||||
try:
|
||||
event_data = json.loads(event_json)
|
||||
event = deserialize_event(event_data["event"])
|
||||
if event is not None:
|
||||
events.append(event)
|
||||
except (json.JSONDecodeError, KeyError):
|
||||
pass # TODO log this
|
||||
|
||||
return events
|
||||
|
||||
|
||||
def health_check() -> bool:
|
||||
"""Check if Redis connection is healthy.
|
||||
|
||||
Returns:
|
||||
True if Redis is accessible, False otherwise
|
||||
"""
|
||||
try:
|
||||
_get_redis_client().ping()
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
@@ -0,0 +1,178 @@
|
||||
import time
|
||||
import threading
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from jockey.config import (
|
||||
DeploymentConfig,
|
||||
TaskType,
|
||||
)
|
||||
from jockey.exec import (
|
||||
execute_serve,
|
||||
execute_build,
|
||||
execute_run,
|
||||
)
|
||||
from jockey.backend.event import BaseEvent
|
||||
from jockey.log import logger
|
||||
from jockey.environment import WORKER_POLL_INTERVAL
|
||||
from jockey.worker import queue
|
||||
|
||||
|
||||
class Worker:
|
||||
"""Background worker that processes tasks from Redis queue."""
|
||||
|
||||
running: bool = False
|
||||
worker_threads: dict[str, threading.Thread]
|
||||
worker_id: str
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize the task worker."""
|
||||
self.worker_threads = {}
|
||||
self.worker_id = str(uuid.uuid4())
|
||||
|
||||
def start(self) -> None:
|
||||
"""Start the worker polling loop."""
|
||||
self.running = True
|
||||
logger.info("Starting task worker")
|
||||
|
||||
while self.running:
|
||||
try:
|
||||
if task_data := self._get_next_task():
|
||||
self._process_task(task_data)
|
||||
|
||||
self._cleanup_threads()
|
||||
time.sleep(WORKER_POLL_INTERVAL)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Worker error: {e}")
|
||||
time.sleep(WORKER_POLL_INTERVAL)
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Stop the worker and wait for active tasks to complete."""
|
||||
logger.info("Stopping task worker")
|
||||
self.running = False
|
||||
|
||||
# Wait for active tasks to complete
|
||||
for thread in self.worker_threads.values():
|
||||
if thread.is_alive():
|
||||
thread.join(timeout=30) # 30 second timeout
|
||||
|
||||
def _get_next_task(self) -> Optional[queue.JobData]:
|
||||
"""Get the next task from the queue using atomic dequeue.
|
||||
|
||||
Returns:
|
||||
Task data dictionary or None if queue is empty
|
||||
"""
|
||||
task_data = queue.claim_next_task()
|
||||
if task_data:
|
||||
return task_data
|
||||
return None
|
||||
|
||||
def _process_task(self, task_data: queue.JobData) -> None:
|
||||
"""Process a task by starting it in a background thread.
|
||||
|
||||
Args:
|
||||
task_data: Task data containing configuration
|
||||
"""
|
||||
task_id = task_data["job_id"]
|
||||
project_id = task_data["project_id"]
|
||||
|
||||
# Don't start duplicate tasks
|
||||
if task_id in self.worker_threads and self.worker_threads[task_id].is_alive():
|
||||
logger.warning(f"Task {task_id} already running")
|
||||
return
|
||||
|
||||
logger.info(f"Starting task {task_id} for project {project_id}")
|
||||
thread = threading.Thread(
|
||||
target=self._run_task,
|
||||
args=(task_data,),
|
||||
daemon=True,
|
||||
name=f"task-{task_id}",
|
||||
)
|
||||
thread.start()
|
||||
self.worker_threads[task_id] = thread
|
||||
|
||||
def _run_task(self, task_data: queue.JobData) -> None:
|
||||
"""Run a task and store events in Redis.
|
||||
|
||||
Args:
|
||||
task_data: Task data containing configuration
|
||||
"""
|
||||
task_id = task_data["job_id"]
|
||||
project_id = task_data["project_id"]
|
||||
|
||||
try:
|
||||
config = DeploymentConfig.from_serialized(task_data["config"])
|
||||
task_type = TaskType(task_data["job_type"]) # Deserialize string back to enum
|
||||
logger.info(f"Processing {task_type.value} task for {config.tag} in {config.namespace}")
|
||||
|
||||
match task_type:
|
||||
case TaskType.SERVE:
|
||||
for event in execute_serve(config, job_id=task_id):
|
||||
if isinstance(event, BaseEvent):
|
||||
queue.store_event(task_id=task_id, event=event)
|
||||
case TaskType.BUILD:
|
||||
for event in execute_build(config, job_id=task_id):
|
||||
if isinstance(event, BaseEvent):
|
||||
queue.store_event(task_id=task_id, event=event)
|
||||
case TaskType.RUN:
|
||||
for event in execute_run(config, task_data.get("inputs"), job_id=task_id):
|
||||
if isinstance(event, BaseEvent):
|
||||
queue.store_event(task_id=task_id, event=event)
|
||||
case _:
|
||||
logger.error(f"Unknown task type: {task_type}")
|
||||
raise ValueError(f"Unknown task type: {task_type}")
|
||||
|
||||
except Exception:
|
||||
logger.error(f"Task {task_id} failed", exc_info=True)
|
||||
# note this will not store an event in redis; revisit this if we want to track failures
|
||||
finally:
|
||||
self._cleanup_task(task_id)
|
||||
|
||||
def _cleanup_task(self, task_id: str) -> None:
|
||||
"""Clean up task state after completion.
|
||||
|
||||
Args:
|
||||
task_id: Task identifier
|
||||
"""
|
||||
try:
|
||||
if task_id in self.worker_threads:
|
||||
del self.worker_threads[task_id]
|
||||
logger.debug(f"Cleaned up task {task_id}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error cleaning up task {task_id}: {e}")
|
||||
|
||||
def _cleanup_threads(self) -> None:
|
||||
"""Clean up completed task threads."""
|
||||
for task_id in self.get_running_tasks():
|
||||
logger.debug(f"Removing completed task {task_id} thread")
|
||||
del self.worker_threads[task_id]
|
||||
|
||||
def get_running_tasks(self) -> list[str]:
|
||||
"""Get currently active tasks.
|
||||
|
||||
Returns:
|
||||
List of task IDs that are currently running
|
||||
"""
|
||||
return [task_id for task_id, thread in self.worker_threads.items() if thread.is_alive()]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
"""Run the task worker as a standalone process."""
|
||||
import signal
|
||||
import sys
|
||||
|
||||
worker = Worker()
|
||||
|
||||
def signal_handler(signum, frame):
|
||||
print("\nReceived shutdown signal, stopping worker...")
|
||||
worker.stop()
|
||||
sys.exit(0)
|
||||
|
||||
signal.signal(signal.SIGINT, signal_handler)
|
||||
signal.signal(signal.SIGTERM, signal_handler)
|
||||
|
||||
try:
|
||||
worker.start()
|
||||
except KeyboardInterrupt:
|
||||
worker.stop()
|
||||
@@ -0,0 +1,36 @@
|
||||
[tool:pytest]
|
||||
# Pytest configuration for the deploy directory
|
||||
testpaths =
|
||||
jockey/tests
|
||||
|
||||
# Test discovery patterns
|
||||
python_files = test_*.py *_test.py
|
||||
python_classes = Test*
|
||||
python_functions = test_*
|
||||
|
||||
# Output and verbosity
|
||||
addopts =
|
||||
--tb=short
|
||||
-v
|
||||
--strict-markers
|
||||
--import-mode=importlib
|
||||
|
||||
# Custom markers
|
||||
markers =
|
||||
integration: marks tests as integration tests (may require external services)
|
||||
unit: marks tests as unit tests (fast, isolated)
|
||||
slow: marks tests as slow running
|
||||
|
||||
# Timeout settings
|
||||
timeout = 300
|
||||
timeout_method = thread
|
||||
|
||||
# Async support
|
||||
asyncio_mode = auto
|
||||
asyncio_default_fixture_loop_scope = session
|
||||
|
||||
# Python path setup
|
||||
pythonpath = .
|
||||
|
||||
# Minimum version
|
||||
minversion = 6.0
|
||||
@@ -0,0 +1,11 @@
|
||||
FROM redis:8
|
||||
|
||||
RUN apt-get update && apt-get install -y python3 python3-pip && \
|
||||
pip install flask boto3
|
||||
|
||||
COPY redis.conf /usr/local/etc/redis/redis.conf
|
||||
COPY backup_server.py /backup_server.py
|
||||
|
||||
VOLUME /data
|
||||
|
||||
CMD ["bash", "-c", "redis-server /usr/local/etc/redis/redis.conf & python3 /backup_server.py"]
|
||||
@@ -0,0 +1,43 @@
|
||||
import os
|
||||
import subprocess
|
||||
import gzip
|
||||
from datetime import datetime
|
||||
from flask import Flask, jsonify
|
||||
import boto3
|
||||
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
|
||||
@app.route("/backup", methods=["POST"])
|
||||
def backup():
|
||||
try:
|
||||
subprocess.run(["redis-cli", "save"], check=True)
|
||||
|
||||
rdb_path = "/data/dump.rdb"
|
||||
timestamp = datetime.utcnow().strftime("%Y%m%d-%H%M%S")
|
||||
gzip_path = f"/tmp/dump-{timestamp}.rdb.gz"
|
||||
s3_key = f"redis-backups/dump-{timestamp}.rdb.gz"
|
||||
|
||||
with open(rdb_path, "rb") as f_in, gzip.open(gzip_path, "wb") as f_out:
|
||||
f_out.writelines(f_in)
|
||||
|
||||
s3 = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=os.environ["S3_ENDPOINT"],
|
||||
aws_access_key_id=os.environ["S3_ACCESS_KEY_ID"],
|
||||
aws_secret_access_key=os.environ["S3_SECRET_ACCESS_KEY"],
|
||||
)
|
||||
|
||||
s3.upload_file(gzip_path, os.environ["S3_BUCKET"], s3_key)
|
||||
|
||||
os.remove(gzip_path)
|
||||
|
||||
return jsonify({"status": "ok", "uploaded": s3_key})
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({"status": "error", "error": str(e)}), 500
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=8080)
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Test script to verify secret environment variable naming fix."""
|
||||
|
||||
from jockey.backend.models.secret import SecretRef
|
||||
|
||||
def test_secret_ref_transformations():
|
||||
"""Test that SecretRef properly transforms between formats."""
|
||||
|
||||
# Test case 1: Creating from lowercase secret name
|
||||
secret_ref = SecretRef(key="agentops-api-key")
|
||||
print(f"Input key: {secret_ref.key}")
|
||||
print(f"Safe name (k8s secret): {secret_ref.safe_name}")
|
||||
print(f"Env name (env var): {secret_ref.env_name}")
|
||||
|
||||
# Generate the env var
|
||||
env_var = secret_ref.to_env_var()
|
||||
print(f"\nGenerated env var:")
|
||||
print(f" name: {env_var.name}")
|
||||
print(f" secret_name: {env_var.value_from.secret_key_ref.name}")
|
||||
print(f" secret_key: {env_var.value_from.secret_key_ref.key}")
|
||||
|
||||
assert env_var.name == "AGENTOPS_API_KEY", f"Expected AGENTOPS_API_KEY, got {env_var.name}"
|
||||
assert env_var.value_from.secret_key_ref.name == "agentops-api-key"
|
||||
assert env_var.value_from.secret_key_ref.key == "AGENTOPS_API_KEY"
|
||||
|
||||
print("\n✓ Test case 1 passed!")
|
||||
|
||||
# Test case 2: Creating with explicit env var name
|
||||
secret_ref2 = SecretRef(key="my-secret", env_var_name="CUSTOM_ENV_NAME")
|
||||
env_var2 = secret_ref2.to_env_var()
|
||||
print(f"\nTest case 2:")
|
||||
print(f" env var name: {env_var2.name}")
|
||||
assert env_var2.name == "CUSTOM_ENV_NAME"
|
||||
print("✓ Test case 2 passed!")
|
||||
|
||||
# Test case 3: Test create_secret function
|
||||
from jockey.deploy import create_secret
|
||||
print("\n\nTesting create_secret function:")
|
||||
print("Input: key='agentops-api-key', value='test-value'")
|
||||
|
||||
# This would normally create the secret in k8s, but we'll just check the data structure
|
||||
from jockey.backend.models.secret import Secret
|
||||
|
||||
# Simulate what create_secret does
|
||||
key = "agentops-api-key"
|
||||
data_key = key.upper().replace('-', '_')
|
||||
print(f"Data key in secret: {data_key}")
|
||||
assert data_key == "AGENTOPS_API_KEY"
|
||||
print("✓ create_secret transforms key correctly!")
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_secret_ref_transformations()
|
||||
print("\n✅ All tests passed!")
|
||||
Reference in New Issue
Block a user