You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
refactor(app): move driver lifecycle into internal app - #384
Keep cmd/dracpu focused on flag parsing, signal handling, and process exit behavior while making startup, HTTP serving, and shutdown lifecycle testable through explicit Go dependencies.
Add local startup coverage and keep the existing HTTP-before-driver shutdown order.
What type of PR is this?
/kind cleanup
What this PR does / why we need it
Move dracpu startup, HTTP server lifecycle, dependency construction, and shutdown handling from cmd/dracpu into internal/app.
Keep cmd/dracpu focused on flags, configuration resolution, signal handling, subcommands, and process exit behavior. Use an explicit Dependencies struct for tests; no dependency injection framework is introduced.
Add lifecycle tests for startup ordering, failure cleanup, HTTP and driver errors, cancellation, shutdown ordering, and isolated metrics. Add local E2E coverage for a bind failure before driver startup.
Skipping CI for Draft Pull Request.
If you want CI signal for your change, please convert it to an actual PR.
You can still manually trigger a test run with /test all
Auto incremental reviews are disabled on this repository.
Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.
You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.
Use the checkbox below for a quick retry:
Trigger review
Walkthrough
The driver lifecycle moves from cmd/dracpu into internal/app. The new application package provides injectable dependencies, HTTP health and metrics endpoints, startup and shutdown handling, and tests. The command entry point resolves configuration, dispatches subcommands, and handles termination signals.
Changes: Application startup and lifecycle
Layer / File(s)
Summary
Runtime dependencies and HTTP server internal/app/deps.go, internal/app/http.go, internal/app/http_test.go
Adds injectable production dependencies and an HTTP server with readiness-aware /healthz, instrumented /metrics, serve-error reporting, and shutdown handling.
Application lifecycle and cleanup cmd/dracpu/app.go, cmd/dracpu/app_test.go, internal/app/app.go, internal/app/app_test.go, internal/app/helpers_test.go
Removes the old command-package lifecycle and adds app.Run for dependency initialization, driver startup, runtime error handling, cancellation, and cleanup. Tests cover startup failures and ordering, driver stop behavior, and shutdown errors and ordering.
Command entry point and startup validation cmd/dracpu/main.go, Makefile, test/e2e_local/startup_test.go
Adds command dispatch, configuration resolution, and signal handling to cmd/dracpu. The unit-test target now tests ./pkg/... and ./internal/.... A local startup test checks that an occupied HTTP address causes a nonzero exit before the driver starts.
sequenceDiagram
participant Main as cmd/dracpu main
participant App as internal/app.Run
participant Dependencies as app.Dependencies
participant HTTP as HTTP server
participant Driver as driver
Main->>App: Pass context, logger, config, and dependencies
App->>Dependencies: Initialize sysfs, listener, Kubernetes client, node name, and driver
App->>HTTP: Start health and metrics endpoints
App->>Driver: Start with context
Driver-->>App: Return error channel
App->>HTTP: Mark ready
App->>HTTP: Shut down before driver stop
App->>Driver: Stop if started
Loading
Possibly related issues
kubernetes-sigs/dra-driver-cpu#204: The added application tests check returned errors on driver failure, which may support behavior-based error assertions.
kubernetes-sigs/dra-driver-cpu#234: The new command entry point retains subcommand dispatch and documents introspect metrics; the summaries do not establish the full configuration-schema cleanup.
Possibly related PRs
kubernetes-sigs/dra-driver-cpu#367: Both changes involve the driver lifecycle in cmd/dracpu; this change moves that lifecycle to internal/app.
This is a refactor that keeps existing startup, health-check and shutdown behavior. One minor cleanup gap remains after a partial driver startup failure. It matches the previous behavior and is unlikely to affect the single-run command. It is mergeable with owner awareness.
Pre-merge checks: 4
Check name
Status
Explanation
Description Check
Check skipped - CodeRabbit’s high-level summary is enabled.
Title check
The title clearly identifies the main change: moving driver lifecycle management into the internal app package. It is concise and directly matches the pull request objectives and changeset.
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
This pull-request has been approved by: alanhuangch Once this PR has been reviewed and has the lgtm label, please assign johnbelamaric for approval. For more information see the Code Review Process.
The full list of commands accepted by this bot can be found here.
Details
Needs approval from an approver in each of these files:
kubernetes-prowBot
added
cncf-cla: yes
Indicates the PR's author has signed the CNCF CLA.
size/XXL
Denotes a PR that changes 1000+ lines, ignoring generated files.
needs-rebase
Indicates a PR cannot be merged because it has merge conflicts with HEAD.
labels
Nov 3, 2026
Reviewing files that changed from the base of the PR and between ebbc686 and a22dc14.
Files selected for processing: 11
Makefile
cmd/dracpu/app.go
cmd/dracpu/app_test.go
cmd/dracpu/main.go
internal/app/app.go
internal/app/app_test.go
internal/app/deps.go
internal/app/helpers_test.go
internal/app/http.go
internal/app/http_test.go
test/e2e_local/startup_test.go
Files with no reviewable changes: 2
cmd/dracpu/app.go
cmd/dracpu/app_test.go
Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.
#!/bin/bashset -euo pipefail
cat -n go.mod | sed -n '1,40p'
cat -n pkg/driver/driver.go | sed -n '17,90p'
cat -n internal/app/dependencies.go | sed -n '1,220p'
cat -n AGENTS.md | sed -n '1,180p'
git diff ebbc68628df98d94ce7c392bc6f7342235982e96 a22dc14ac515896f29db1da7eee1e7ad889ec335 -- pkg/driver/driver.go
python3 - <<'PY'import io, urllib.request, zipfileurl = 'https://proxy.golang.org/k8s.io/dynamic-resource-allocation/@v/v0.37.0.zip'try: with urllib.request.urlopen(url, timeout=20) as r: z = zipfile.ZipFile(io.BytesIO(r.read())) for name in z.namelist(): if '/kubeletplugin/' not in name or not name.endswith('.go') or name.endswith('_test.go'): continue lines = z.read(name).decode().splitlines() hits = [i for i, line in enumerate(lines) if any(s in line for s in ['func Start(', 'func (', 'os.Remove(', 'net.Listen(', 'ctx.Done()', 'context.AfterFunc']) and any(s in line for s in ['Start(', 'Stop(', 'os.Remove(', 'net.Listen(', 'ctx.Done()', 'context.AfterFunc'])] if hits: print('\n###', name) intervals = [] for i in hits: lo, hi = max(0, i-12), min(len(lines), i+35) if intervals and lo <= intervals[-1][1]: intervals[-1] = (intervals[-1][0], max(hi, intervals[-1][1])) else: intervals.append((lo, hi)) for lo, hi in intervals: for j in range(lo, hi): print(f'{j+1:5} {lines[j]}')except Exception as e: print('DEPENDENCY FETCH FAILED:', repr(e))PY
Repository: kubernetes-sigs/dra-driver-cpu
Length of output: 5341
Script executed:
#!/bin/bash
git diff ebbc68628df98d94ce7c392bc6f7342235982e96 a22dc14ac515896f29db1da7eee1e7ad889ec335 -- pkg/driver/driver.go
rg -n -F -e 'func DefaultDependencies' -e 'func (cp *CPUDriver) Start' -- internal/app pkg/driver
iftest -f AGENTS.md;then cat -n AGENTS.md | sed -n '1,180p';fi
python3 - <<'PY'import io, urllib.request, zipfileurl = 'https://proxy.golang.org/k8s.io/dynamic-resource-allocation/@v/v0.37.0.zip'try: with urllib.request.urlopen(url, timeout=20) as r: z = zipfile.ZipFile(io.BytesIO(r.read())) for name in z.namelist(): if '/kubeletplugin/' not in name or not name.endswith('.go') or name.endswith('_test.go'): continue lines = z.read(name).decode().splitlines() hits = [i for i, line in enumerate(lines) if any(s in line for s in ['func Start(', ' Stop(', 'os.Remove(', 'net.Listen(', 'ctx.Done()', 'context.AfterFunc'])] if hits: print('\n###', name) intervals = [] for i in hits: lo, hi = max(0, i-12), min(len(lines), i+35) if intervals and lo <= intervals[-1][1]: intervals[-1] = (intervals[-1][0], max(hi, intervals[-1][1])) else: intervals.append((lo, hi)) for lo, hi in intervals: for j in range(lo, hi): print(f'{j+1:5} {lines[j]}')except Exception as e: print('DEPENDENCY FETCH FAILED:', repr(e))PY
Repository: kubernetes-sigs/dra-driver-cpu
Length of output: 20689
Script executed:
#!/bin/bash
cat -n internal/app/deps.go | sed -n '25,115p'
cat -n cmd/dracpu/main.go | sed -n '105,126p'
python3 - <<'PY'import io, urllib.request, zipfileurl='https://proxy.golang.org/k8s.io/dynamic-resource-allocation/@v/v0.37.0.zip'try: with urllib.request.urlopen(url,timeout=20) as r: z=zipfile.ZipFile(io.BytesIO(r.read())) for name in z.namelist(): if '/kubeletplugin/' not in name or not name.endswith('.go') or name.endswith('_test.go'): continue lines=z.read(name).decode().splitlines() if name.endswith('/endpoint.go'): print('\n###',name) for i,l in enumerate(lines,1): print(f'{i:5} {l}') else: hits=[i for i,l in enumerate(lines) if ('func ' in l and ('.stop(' in l or 'startGRPCServer(' in l or 'startRegistrar(' in l))] for i in hits: print('\n###',name) for j in range(max(i-3,0),min(i+75,len(lines))): print(f'{j+1:5} {lines[j]}')except Exception as e: print('DEPENDENCY FETCH FAILED:',repr(e))PY
Repository: kubernetes-sigs/dra-driver-cpu
Length of output: 11894
Script executed:
#!/bin/bash
rg -n -F -e 'Run(' -e 'DefaultDependencies' -e 'NewRegistry' -- internal/app
cat -n internal/app/http.go | sed -n '1,200p'
python3 - <<'PY'import io, urllib.request, zipfileurl='https://proxy.golang.org/k8s.io/dynamic-resource-allocation/@v/v0.37.0.zip'try: with urllib.request.urlopen(url,timeout=20) as r: z=zipfile.ZipFile(io.BytesIO(r.read())) for name in z.namelist(): if '/kubeletplugin/' not in name or not name.endswith('.go') or name.endswith('_test.go'): continue lines=z.read(name).decode().splitlines() for i,l in enumerate(lines): if l.startswith('func ') and ' stop()' in l: print('\n###',name) for j in range(max(i-3,0),min(i+26,len(lines))): print(f'{j+1:5} {lines[j]}')except Exception as e: print('DEPENDENCY FETCH FAILED:',repr(e))PY
Repository: kubernetes-sigs/dra-driver-cpu
Length of output: 7951
Wait for partial driver startup cleanup.
If registration times out, Run can return before the kubelet plugin removes its sockets. If another Run starts in the same process first, the old plugin can remove the new sockets and prevent registration.
Clean up the kubelet plugin on partial CPUDriver.Start failure. Do not call CPUDriver.Stop before the NRI plugin exists. AGENTS.md requires a reproducing test for bug fixes.
coderabbit report the driver startup cleanup. I agree this is a real partial-start cleanup gap, but it predates this refactor and is not required for moving the lifecycle into internal/app. Will handle it as a focused follow-up so this PR stays scoped to the refactor.
The reason will be displayed to describe this comment to others. Learn more.
Yes, you are right: the context passed to dracpu.Start is the one SIGTERM cancels, so kubeletplugin.Start starts tearing down before Run reaches dracpu.Stop(), and draPlugin.Stop() only waits for that. I will give the driver its own context in Run, cancel it after the HTTP server shuts down and before Stop, and keep the startup phase abortable with context.AfterFunc so a signal does not wait out the 30s registration timeout. The fake driver will watch its context so the shutdown-order test fails before the fix.
Keep cmd/dracpu focused on flag parsing, signal handling, and process
exit behavior while making startup, HTTP serving, and shutdown lifecycle
testable through explicit Go dependencies.
Treat HTTP serving failures as fatal. The previous behavior logged the
failure and left the driver running without reachable health and metrics
endpoints, which would hide a broken process from Kubernetes.
Add local startup coverage and make the HTTP-before-driver shutdown
order real. The driver used to share the context that SIGTERM cancels,
so the kubelet plugin started tearing down while the HTTP server was
still serving. Give the driver its own context, canceled after the HTTP
server drains, and keep the kubelet registration wait abortable so a
signal still aborts startup at once. The driver now stops when the drain
finishes instead of at signal time.
Signed-off-by: Alan Huang <huangch96@gmail.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cncf-cla: yesIndicates the PR's author has signed the CNCF CLA.kind/cleanupCategorizes issue or PR as related to cleaning up code, process, or technical debt.size/XXLDenotes a PR that changes 1000+ lines, ignoring generated files.
2 participants
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Keep cmd/dracpu focused on flag parsing, signal handling, and process exit behavior while making startup, HTTP serving, and shutdown lifecycle testable through explicit Go dependencies.
Add local startup coverage and keep the existing HTTP-before-driver shutdown order.
What type of PR is this?
/kind cleanup
What this PR does / why we need it
Move dracpu startup, HTTP server lifecycle, dependency construction, and shutdown handling from
cmd/dracpuintointernal/app.Keep
cmd/dracpufocused on flags, configuration resolution, signal handling, subcommands, and process exit behavior. Use an explicitDependenciesstruct for tests; no dependency injection framework is introduced.Add lifecycle tests for startup ordering, failure cleanup, HTTP and driver errors, cancellation, shutdown ordering, and isolated metrics. Add local E2E coverage for a bind failure before driver startup.
Which issue(s) this PR is related to
#359
follow up pr: #361
Special notes for reviewers
This is a draft for early review of the integrated refactor plan.
The shutdown order remains HTTP server first, then driver.
HTTP Serve errors now terminate the application through the run context.
Release note
AI usage disclosure
YES. AI was used to design and implement the refactor, add tests, and run validation. Reviewed by me.
Summary by CodeRabbit
dracpu-gatherinfoexecutable name continues to route to thegatherinfosubcommand.