Metadata-Version: 2.4
Name: k8s-trafficctl
Version: 0.1.0
Summary: Pod-level traffic control for Kubernetes using labels
Home-page: https://github.com/Manikandan-t/k8s-trafficctl
Author: Manikandan
Author-email: Manikandan <manikandan.tm06@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/Manikandan-t/k8s-trafficctl
Project-URL: Bug Reports, https://github.com/Manikandan-t/k8s-trafficctl/issues
Project-URL: Source, https://github.com/Manikandan-t/k8s-trafficctl
Project-URL: Documentation, https://github.com/Manikandan-t/k8s-trafficctl#readme
Keywords: kubernetes,k8s,traffic-control,pod-management,devops,sre
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: System Administrators
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: kubernetes>=12.0.0
Requires-Dist: click>=8.0.0
Requires-Dist: rich>=10.0.0
Requires-Dist: questionary>=1.10.0
Dynamic: author
Dynamic: home-page
Dynamic: license-file
Dynamic: requires-python

# k8s-trafficctl

[![PyPI version](https://badge.fury.io/py/k8s-trafficctl.svg)](https://badge.fury.io/py/k8s-trafficctl)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)

**Pod-level traffic control for Kubernetes using labels — no service mesh required.**

---

## 🚀 Quick Start

```bash
# Install from PyPI
pip install k8s-trafficctl

# Enable traffic to 3 pods
trafficctl apply --namespace demo --deployment web-server --count 3

# Watch pods in real-time
trafficctl watch --namespace demo --deployment web-server

# Interactive mode
trafficctl interactive --namespace demo --deployment web-server
```

---

## 📖 Overview

`k8s-trafficctl` is a lightweight CLI that enables **dynamic traffic routing at the pod level** by manipulating labels used by Kubernetes Service selectors.

Instead of relying on:

* Service mesh (Istio / Linkerd)
* Complex ingress rules
* Deployment-level rollouts

You can directly control:

> **Which pods receive traffic — in real time**

### ✨ Features

- 🎯 **Enhanced Status Display** - View pod IP, node, readiness, and labels in rich tables
- 👀 **Watch Mode** - Real-time monitoring with auto-refresh
- 🖱️ **Interactive TUI** - Menu-driven interface for easy pod selection
- 🔄 **Reconciliation** - Maintain desired pod count with traffic labels
- 🛡️ **Safety First** - Only targets ready pods, no restarts required
- 📦 **Zero Dependencies** - No service mesh or additional infrastructure needed

---

## 🎯 Problem

Kubernetes Services route traffic using label selectors:

```yaml
selector:
  role: philos-traffic-ingress
```

However:

* You cannot dynamically control **how many pods receive traffic**
* Canary rollouts require **additional tooling**
* Debugging individual pods requires **manual intervention**
* No native mechanism exists for **fine-grained traffic control**

---

## 💡 Solution

`k8s-trafficctl` introduces:

> **Label-driven traffic control at pod level**

It works by:

* Adding a label → pod starts receiving traffic
* Removing a label → pod stops receiving traffic

All routing changes are handled **natively by Kubernetes**.

---

## 📦 Installation

### From PyPI (Recommended)

```bash
pip install k8s-trafficctl
```

### From Source

```bash
git clone https://github.com/Manikandan-t/k8s-trafficctl.git
cd k8s-trafficctl
pip install -e .
```

### Requirements

- Python 3.8+
- Kubernetes cluster access (via kubeconfig or in-cluster config)
- Dependencies: `kubernetes`, `click`, `rich`, `questionary`

---

## 🧪 Complete Usage Guide

### Setting Up Your Service

First, ensure your Kubernetes Service uses label selectors for traffic routing:

```yaml
apiVersion: v1
kind: Service
metadata:
  name: philos-service
spec:
  selector:
    app: philos-server
    role: philos-traffic-ingress  # This is the traffic control label or you can change based on what you set as label
  ports:
    - port: 80
      targetPort: 8080
```

---

### Command Reference

#### 1. **Status** - View Pod Information

Show labeled pods with detailed information:

```bash
trafficctl status \
  --namespace bronze \
  --deployment philos-server
```

Show all pods (not just labeled ones):

```bash
trafficctl status \
  --namespace bronze \
  --deployment philos-server \
  --show-all
```

**Output includes:**
- Pod name
- Status (Running/Pending/Failed)
- Readiness indicator (✓/✗)
- IP address
- Node name
- Label values

---

#### 2. **Apply** - Enable Traffic to N Pods

Enable traffic to 3 pods:

```bash
trafficctl apply \
  --namespace bronze \
  --deployment philos-server \
  --count 3
```

Custom label key/value:

```bash
trafficctl apply \
  --namespace bronze \
  --deployment philos-server \
  --count 2 \
  --label-key "traffic" \
  --label-value "enabled"
```

---

#### 3. **Remove** - Disable Traffic from N Pods

Disable traffic from 1 pod:

```bash
trafficctl remove \
  --namespace bronze \
  --deployment philos-server \
  --count 1
```

---

#### 4. **Reconcile** - Maintain Desired State

Ensure exactly 2 pods have traffic enabled:

```bash
trafficctl reconcile \
  --namespace bronze \
  --deployment philos-server \
  --desired 2
```

This will:
- Add labels if current count < desired
- Remove labels if current count > desired
- Do nothing if already at desired state

---

#### 5. **Watch** - Real-time Monitoring

Monitor pods with auto-refresh every 5 seconds:

```bash
trafficctl watch \
  --namespace bronze \
  --deployment philos-server
```

Custom refresh interval (2 seconds):

```bash
trafficctl watch \
  --namespace bronze \
  --deployment philos-server \
  --interval 2
```

Watch all pods in deployment:

```bash
trafficctl watch \
  --namespace bronze \
  --deployment philos-server \
  --show-all
```

**Press Ctrl+C to exit watch mode**

---

#### 6. **Interactive** - TUI Mode

Launch interactive menu for easy pod management:

```bash
trafficctl interactive \
  --namespace bronze \
  --deployment philos-server
```

**Interactive features:**
- View all pods or labeled pods only
- Select specific pods to label/unlabel (with checkboxes)
- Reconcile to target count
- Visual pod selection with IP/Node/Ready status
- Confirmation prompts for safety

---

### 🔐 Using Custom Kubeconfig

All commands support custom kubeconfig:

```bash
trafficctl --kubeconfig /path/to/config \
  status \
  --namespace default \
  --deployment my-app
```

For role-based access setup, see: [NameSpace Access](https://github.com/Manikandan-t/initbox/tree/main/k8s-installation/namespace-access)

---

## 💼 Use Cases

### 1. Canary Deployment (Without Service Mesh)

Gradually increase traffic to new version:

```bash
# Start with 1 pod
trafficctl reconcile --namespace prod --deployment api-v2 --desired 1

# Monitor performance
trafficctl watch --namespace prod --deployment api-v2

# Gradually increase
trafficctl reconcile --namespace prod --deployment api-v2 --desired 3
trafficctl reconcile --namespace prod --deployment api-v2 --desired 5
```

---

### 2. Debugging Production Pods

Isolate a problematic pod without downtime:

```bash
# View all pods
trafficctl status --namespace prod --deployment web-server --show-all

# Remove traffic from specific pod using interactive mode
trafficctl interactive --namespace prod --deployment web-server
# Select the problematic pod and unlabel it

# Debug the pod without affecting traffic
kubectl logs <pod-name> -n prod
kubectl exec -it <pod-name> -n prod -- /bin/bash
```

---

### 3. Load Shedding During High Traffic

Limit active pods to conserve resources:

```bash
# During traffic spike, reduce to essential pods
trafficctl reconcile --namespace prod --deployment api --desired 3

# Monitor with watch mode
trafficctl watch --namespace prod --deployment api
```

---

### 4. Blue-Green Deployment

Switch traffic between versions:

```bash
# Green (new version) deployment
kubectl apply -f deployment-v2.yaml

# Wait for pods to be ready
kubectl rollout status deployment/app-v2 -n prod

# Enable traffic to green deployment
trafficctl apply --namespace prod --deployment app-v2 --count 5

# Disable traffic to blue deployment
trafficctl remove --namespace prod --deployment app-v1 --count 5
```

---

## 🧠 Architecture

### How It Works

```text
User CLI
   ↓
k8s-trafficctl
   ↓
Kubernetes API Server
   ↓
Pod Labels Updated
   ↓
Endpoints Controller
   ↓
Service Endpoints Updated
   ↓
kube-proxy
   ↓
Traffic redistributed
```

### Key Insight

This tool leverages:

> **Kubernetes' native label-selector and endpoint reconciliation mechanism**

No sidecars. No proxies. No service mesh.

### Kubernetes Integration

Interacts **directly with the Kubernetes API Server** using the official Python client.

Supports:

* ✅ Local kubeconfig (`~/.kube/config`)
* ✅ Custom kubeconfig (`--kubeconfig`)
* ✅ In-cluster config (when running inside Kubernetes)

---

## 🛡️ Safety Features

* **Ready Pods Only** - Only targets pods in Ready state
* **No Restarts** - Labels are updated without pod restarts
* **No Deployment Changes** - Deployment specs remain unchanged
* **Fully Reversible** - All operations can be undone
* **Confirmation Prompts** - Interactive mode asks before operations
* **Non-Destructive** - Never deletes or modifies pod configuration

---

## ⚠️ Limitations

* **Count-Based Control** - Traffic control is pod-count based, not exact percentage
* **No Metrics** - No metric-based routing (CPU, latency, error rate) yet
* **CLI-Driven** - No continuous reconciliation loop (must be triggered manually)
* **Label Dependency** - Requires service to use label selectors for routing

---

### Development Setup

```bash
# Clone repository
git clone https://github.com/Manikandan-t/k8s-trafficctl.git
cd k8s-trafficctl

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install in editable mode
pip install -e .

# Install development dependencies
pip install -r requirements.txt
```

### Running Locally

```bash
# Run commands directly
python -m trafficctl.cli --help

# Or use the installed command
trafficctl --help
```

### Project Structure

```
k8s-trafficctl/
├── trafficctl/
│   ├── __init__.py
│   ├── cli.py           # CLI commands
│   ├── k8s.py           # Kubernetes API interactions
│   ├── utils.py         # Utility functions (logging, tables)
│   ├── selector.py      # Pod selection logic
│   ├── labeling.py      # Label operations
│   ├── reconcile.py     # Reconciliation logic
│   └── interactive.py   # Interactive TUI mode
├── examples/
│   ├── deployment.yaml  # Sample deployment
│   └── quickstart.sh    # Quick start script
├── setup.py
├── requirements.txt
└── README.md
```

---

## Credits

Inspired by the need for lightweight, mesh-free traffic control in Kubernetes environments.

---

## 📚 Related Projects

- [initbox](https://github.com/Manikandan-t/initbox) - Kubernetes installation and configuration guides
- [Namespace Access Guide](https://github.com/Manikandan-t/initbox/tree/main/k8s-installation/namespace-access) - Role-based kubeconfig generation
