Test 1: ChunkHound Response
Complete Code Path: kubectl apply -f deployment.yaml to Running Pods
Section titled “Complete Code Path: kubectl apply -f deployment.yaml to Running Pods”This document traces the complete journey from executing kubectl apply -f deployment.yaml to pods running on nodes, showing all major components, key functions, and data structures involved in the process.
Overview
Section titled “Overview”The flow involves six major components working together:
- kubectl client - Parses YAML and sends API requests
- API Server - Validates and stores Deployment objects
- Deployment Controller - Creates ReplicaSets from Deployments
- ReplicaSet Controller - Creates Pods from ReplicaSets
- Scheduler - Assigns Pods to nodes
- kubelet - Creates containers on assigned nodes
1. kubectl apply Command Implementation
Section titled “1. kubectl apply Command Implementation”Entry Point
Section titled “Entry Point”- File:
cmd/kubectl/kubectl.go:18 - Function:
main()→cmd.NewDefaultKubectlCommand()
Core Apply Logic
Section titled “Core Apply Logic”- File:
staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go - Key Functions:
NewCmdApply()(line 198): Creates apply command with Run functionApplyOptions.Run()(line 500): Main apply execution- Calls
o.GetObjects()to parse YAML files intoresource.Infoobjects - Iterates through each object calling
o.applyOneObject(info)
- Calls
applyOneObject()(line 555): Handles individual resource application- Creates
resource.Helperwith client and mapping information - For server-side apply: calls
helper.Patch()withApplyPatchType - Uses
staging/src/k8s.io/cli-runtime/pkg/resource/helper.go:241Patch method - Makes REST call to API server:
m.RESTClient.Patch(pt).NamespaceIfScoped(...).Do()
- Creates
Data Flow
Section titled “Data Flow”YAML file → Unstructured objects → REST PATCH request → API server2. API Server Request Handling for Deployments
Section titled “2. API Server Request Handling for Deployments”Registry Implementation
Section titled “Registry Implementation”- File:
pkg/registry/apps/deployment/storage/storage.go - Function:
NewREST()(line 93): Creates deployment REST storage withgeneric.Store
Validation Strategy
Section titled “Validation Strategy”- File:
pkg/registry/apps/deployment/strategy.go - Key Functions:
PrepareForCreate()(line 73): Sets initial status, generation = 1Validate()(line 83): Callsappsvalidation.ValidateDeployment()ValidateUpdate()(line 127): Validates deployment updates
Processing Flow
Section titled “Processing Flow”- HTTP PATCH request hits API server
- Authentication/authorization checks
- Admission controllers run
- Validation via deployment strategy
- Object stored in etcd
- Event sent to watchers
3. Deployment Controller Creating ReplicaSets
Section titled “3. Deployment Controller Creating ReplicaSets”Controller Setup
Section titled “Controller Setup”- File:
cmd/kube-controller-manager/app/apps.go:120 - Function:
newDeploymentController(): Creates deployment controller with informers
Core Controller Logic
Section titled “Core Controller Logic”- File:
pkg/controller/deployment/deployment_controller.go - Key Functions:
NewDeploymentController()(line 101): Sets up informers and event handlerssyncHandler = dc.syncDeployment(line 149): Main sync function
ReplicaSet Creation Logic
Section titled “ReplicaSet Creation Logic”- File:
pkg/controller/deployment/sync.go - Key Functions:
getNewReplicaSet()(line 200+): Core ReplicaSet creation logic- Generates ReplicaSet from deployment template
- Calls
dc.client.AppsV1().ReplicaSets(d.Namespace).Create()(line 231) - Handles hash collisions and retries
Data Structures
Section titled “Data Structures”- Input:
apps.Deploymentobject - Output:
apps.ReplicaSetwith:- Template from
deployment.Spec.Template OwnerReferencepointing to deployment- Generated name with hash suffix
- Template from
4. ReplicaSet Controller Creating Pods
Section titled “4. ReplicaSet Controller Creating Pods”Controller Setup
Section titled “Controller Setup”- File:
cmd/kube-controller-manager/app/apps.go:93 - Function:
newReplicaSetController(): Creates ReplicaSet controller
Core Logic
Section titled “Core Logic”- File:
pkg/controller/replicaset/replica_set.go - Key Functions:
syncReplicaSet()(line 702): Main sync function- Calls
rsc.claimPods()to find existing pods - Calls
rsc.manageReplicas()to scale up/down
- Calls
manageReplicas()(line 596): Pod creation logic- Calculates diff between desired and actual replicas
- For scale up: calls
slowStartBatch()with pod creation function - Pod Creation:
rsc.podControl.CreatePods()(line 625)- Creates pods from
ReplicaSet.Spec.Template - Sets
OwnerReferenceto ReplicaSet - Calls API server to create pod objects
- Creates pods from
Data Flow
Section titled “Data Flow”ReplicaSet → Pod templates → API server pod creation5. Scheduler Pod Assignment Logic
Section titled “5. Scheduler Pod Assignment Logic”Main Scheduler
Section titled “Main Scheduler”- File:
pkg/scheduler/schedule_one.go - Key Functions:
ScheduleOne()(line 66): Main scheduling loop- Gets next pod from queue via
sched.NextPod() - Calls
sched.schedulingCycle()which callssched.SchedulePod()
- Gets next pod from queue via
schedulePod()(line 430): Core scheduling algorithm- Updates node snapshot:
sched.Cache.UpdateSnapshot() - Filtering:
sched.findNodesThatFitPod()- runs predicates/filters - Scoring:
prioritizeNodes()- scores feasible nodes - Selection:
selectHost()- picks highest scoring node - Returns
ScheduleResult{SuggestedHost: host}
- Updates node snapshot:
Algorithm Flow
Section titled “Algorithm Flow”- Pod predicates: NodeResourcesFit, NodeAffinity, etc.
- Node scoring: Resource balancing, affinity preferences
- Host selection: Highest scoring node
- Binding creation: Creates Binding object to assign pod to node
6. kubelet Pod Creation and Container Runtime
Section titled “6. kubelet Pod Creation and Container Runtime”kubelet Main Loop
Section titled “kubelet Main Loop”- File:
pkg/kubelet/kubelet.go - Key Components:
podWorkers(line 1140+): Manages pod lifecycle state machine- States: syncing (syncPod), terminating, terminated
UpdatePod(): Notifies workers of pod changes (line 2958)
Pod Sync Process
Section titled “Pod Sync Process”- Function:
SyncPod()(around line 2050)- Pre-sync: Create pod directories, ensure cgroups exist
- Volume Setup:
kl.volumeManager.WaitForAttachAndMount() - Container Runtime:
kl.containerRuntime.SyncPod()
Container Runtime Integration
Section titled “Container Runtime Integration”- File:
pkg/kubelet/kuberuntime/kuberuntime_manager.go - Key Functions:
SyncPod(): Main container sync logiccomputePodActions()(line 1007): Determines what containers need creation/restart- Pod Sandbox: Creates pod sandbox (network namespace)
- Container Creation: Creates and starts individual containers
- CRI Interface: Communicates with container runtime (Docker, containerd, CRI-O)
Controller Coordination and Data Flow
Section titled “Controller Coordination and Data Flow”Objects Passed Between Components
Section titled “Objects Passed Between Components”- kubectl:
resource.Infocontaining*apps.Deployment - API Server:
apps.Deployment→ etcd storage - Deployment Controller:
apps.Deployment→apps.ReplicaSet - ReplicaSet Controller:
apps.ReplicaSet→v1.Pod - Scheduler:
v1.Pod→v1.Binding - kubelet:
v1.Pod→ Container runtime calls
Control Flow Coordination
Section titled “Control Flow Coordination”- Event-driven Architecture: All controllers watch API server via informers
- Work Queues: Controllers use rate-limited queues for retries
- Owner References: Child objects point to parents for cleanup
- Expectations: Controllers track expected vs actual state changes
State Transitions
Section titled “State Transitions”kubectl apply → API Server → Deployment Controller → ReplicaSet Controller → Scheduler → kubelet → Container Runtime ↓ ↓ ↓ ↓ ↓ ↓ PATCH request → Deployment → ReplicaSet created → Pod created → Pod scheduled → Container runningSummary of Key File Locations
Section titled “Summary of Key File Locations”| Component | File Path | Key Function | Line |
|---|---|---|---|
| kubectl apply | staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go | ApplyOptions.Run() | 500 |
| Deployment registry | pkg/registry/apps/deployment/storage/storage.go | NewREST() | 93 |
| Deployment controller | pkg/controller/deployment/sync.go | ReplicaSet creation | 231 |
| ReplicaSet controller | pkg/controller/replicaset/replica_set.go | Pod creation | 625 |
| Scheduler | pkg/scheduler/schedule_one.go | schedulePod() | 430 |
| kubelet | pkg/kubelet/kubelet.go | SyncPod() | 2050+ |
This complete trace shows how a single kubectl apply command triggers a cascade of controllers, each watching for changes and creating the next level of objects until pods are running on nodes with containers started by the container runtime.