Skip to content

refactor(app): move driver lifecycle into internal app - #384

Open
alanhuangch wants to merge 1 commit into
kubernetes-sigs:mainfrom
alanhuangch:refactor/internal-app
Open

alanhuangch wants to merge 1 commit into
kubernetes-sigs:mainfrom
alanhuangch:refactor/internal-app

Conversation

@alanhuangch

@alanhuangch alanhuangch commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

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.

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

None

AI usage disclosure

YES. AI was used to design and implement the refactor, add tests, and run validation. Reviewed by me.

Summary by CodeRabbit

  • New Features
    • The application now resolves configuration in this order: defaults, configuration file, then explicitly set command-line flags.
    • Startup provides health and metrics endpoints, with health checks indicating when the service is ready.
    • On shutdown, the service attempts to stop its HTTP server and driver gracefully; startup and runtime errors are reported before exit.
    • The dracpu-gatherinfo executable name continues to route to the gatherinfo subcommand.

@kubernetes-prow kubernetes-prow Bot added do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. kind/cleanup Categorizes issue or PR as related to cleaning up code, process, or technical debt. labels Nov 3, 2026
@kubernetes-prow

Copy link
Copy Markdown
Contributor

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

@coderabbitai

coderabbitai Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Explain Change →

Important

Review skipped

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.

Run configuration

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.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

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

Merge Risk: Low · previous review a22dc

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: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed 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 Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.

@kubernetes-prow

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

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:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@netlify

netlify Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

👷 Deploy request for dra-driver-cpu pending review.

Visit the deploys page to approve it

Name Link
🔨 Latest commit 6d21233

@kubernetes-prow kubernetes-prow Bot 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
@alanhuangch

Copy link
Copy Markdown
Contributor Author

/test all

@alanhuangch
alanhuangch force-pushed the refactor/internal-app branch from de8f318 to 68dd337 Compare November 6, 2026 05:17
@kubernetes-prow kubernetes-prow Bot removed the needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. label Nov 6, 2026
@alanhuangch
alanhuangch force-pushed the refactor/internal-app branch from 68dd337 to a22dc14 Compare November 11, 2026 08:44
@alanhuangch
alanhuangch marked this pull request as ready for review November 11, 2026 09:01
@kubernetes-prow kubernetes-prow Bot removed the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Nov 11, 2026
@kubernetes-prow
kubernetes-prow Bot requested a review from pravk03 November 11, 2026 09:01

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Review info

Run configuration

Commits

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.

Comment thread internal/app/app.go Outdated
Comment on lines +118 to +125
asyncErr, err := dracpu.Start(ctx)
if err != nil {
if stop, cause := startupStopCause(ctx); stop {
return cause
}
return fmt.Errorf("driver failed to start: %w", err)
}
driverStarted = true

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Stability & Availability · Quick win

Supported by static analysis

Script executed:

#!/bin/bash
set -euo pipefail
ast-grep outline pkg/driver/driver.go --match 'Start|Stop|waitForRegistration' --view expanded
cat -n pkg/driver/driver.go | sed -n '312,389p'
cat -n internal/app/app.go | sed -n '36,53p;110,133p'
cat -n internal/app/app_test.go | sed -n '159,174p'

Repository: kubernetes-sigs/dra-driver-cpu

Length of output: 6162


Script executed:

#!/bin/bash
set -euo pipefail
cat -n pkg/driver/driver.go | sed -n '335,485p'
cat -n internal/app/app.go | sed -n '1,160p'
rg -n -F -e 'app.Run(' -e 'os.Exit(' -- cmd/dracpu
rg -n -F -e 'k8s.io/dynamic-resource-allocation' -e 'replace (' -- go.mod
git diff ebbc68628df98d94ce7c392bc6f7342235982e96 a22dc14ac515896f29db1da7eee1e7ad889ec335 -- cmd/dracpu internal/app/app.go
find "$(go env GOPATH 2>/dev/null)/pkg/mod/k8s.io" -path '*/kubeletplugin/*.go' -type f 2>/dev/null | sort | sed -n '1,40p' || :

Repository: kubernetes-sigs/dra-driver-cpu

Length of output: 33296


Script executed:

#!/bin/bash
set -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, zipfile
url = '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
if test -f AGENTS.md; then cat -n AGENTS.md | sed -n '1,180p'; fi
python3 - <<'PY'
import io, urllib.request, zipfile
url = '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, zipfile
url='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, zipfile
url='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.

@alanhuangch

Copy link
Copy Markdown
Contributor Author

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.

@Tal-or Tal-or left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looking good. I only have one comment which is not an actual bug, but its more related to cleanup order.

Comment thread internal/app/app.go
var dracpu Driver
driverStarted := false
defer func() {
cancel(nil)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from my understanding going through the code, the app and the driver are sharing the same context:
https://github.com/alanhuangch/dra-driver-cpu/blob/a22dc14ac515896f29db1da7eee1e7ad889ec335/internal/app/app.go#L38
the context created here is passing to
https://github.com/alanhuangch/dra-driver-cpu/blob/refactor/internal-app/internal/app/app.go#L118 .
so calling cancel here, already cancels the kubeletplugins, which is being stopped again in dracpu.Stop.

if the intent is to shutdown the server first, then be aware that the kubeletplugin is in the middle of cleanup even before dracpu.Stop() is called.

The solution would be using a separate context for app and driver

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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>
@alanhuangch
alanhuangch force-pushed the refactor/internal-app branch from a22dc14 to 6d21233 Compare November 26, 2026 03:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cncf-cla: yes Indicates the PR's author has signed the CNCF CLA. kind/cleanup Categorizes issue or PR as related to cleaning up code, process, or technical debt. size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants