From 5837558ac4690890b11ea0edde7f0ef41d6c9c53 Mon Sep 17 00:00:00 2001 From: Markus Vahlenkamp Date: Thu, 26 Nov 2026 11:24:18 +0100 Subject: [PATCH 1/2] fix(netconf): lock candidate on Set, recover dirty candidate, and retire poisoned sessions Signed-off-by: Markus Vahlenkamp --- pkg/datastore/target/netconf/CONTEXT.md | 7 +- pkg/datastore/target/netconf/driver.go | 3 +- .../netconf/driver/scrapligo/scrapligo.go | 20 +- .../driver/scrapligo/scrapligo_test.go | 40 ++ pkg/datastore/target/netconf/nc.go | 137 ++++-- .../target/netconf/nc_transport_error_test.go | 462 +++++++++++++++++- pkg/datastore/target/netconf/types/errors.go | 4 + 7 files changed, 633 insertions(+), 40 deletions(-) diff --git a/pkg/datastore/target/netconf/CONTEXT.md b/pkg/datastore/target/netconf/CONTEXT.md index 1676e91b..4c44d542 100644 --- a/pkg/datastore/target/netconf/CONTEXT.md +++ b/pkg/datastore/target/netconf/CONTEXT.md @@ -1,6 +1,6 @@ # NETCONF target -Implements the `Target`/`Driver` interfaces (see `pkg/datastore/target/`) for southbound NETCONF devices, translating `sdcpb` get/set requests into NETCONF RPCs (`get-config`, `edit-config`, `commit`, `discard-changes`) and back. +Implements the `Target`/`Driver` interfaces (see `pkg/datastore/target/`) for southbound NETCONF devices, translating `sdcpb` get/set requests into NETCONF RPCs (`get-config`, `lock`, `edit-config`, `commit`, `discard-changes`, `unlock`) and back. ## Language @@ -8,7 +8,10 @@ Implements the `Target`/`Driver` interfaces (see `pkg/datastore/target/`) for so A failure of the underlying connection to the device *during* an in-flight RPC (e.g. the device restarts mid-`edit-config`) — detected by `isTransportError` — as opposed to a semantic/validation error the device itself returned (e.g. a rejected `edit-config`). Transport errors retire the active session immediately, start a background `reconnect`, and wrap the error in `ErrNotConnected`. **RPC error**: -An `` in a reply whose `error-severity` is anything but `warning`, in any namespace prefix. Every `Driver` method fails on one, the same way; warning-only replies succeed and `Set` returns their warnings (from `edit-config` and `commit`) in `SetDataResponse.Warnings`. In candidate mode an RPC error from `edit-config` or `commit` is followed by `discard-changes`, so the rejected change can't be pushed by the next commit. +An `` in a reply whose `error-severity` is anything but `warning`, in any namespace prefix. Every `Driver` method fails on one, the same way; warning-only replies succeed and `Set` returns their warnings (from `edit-config` and `commit`) in `SetDataResponse.Warnings`. Candidate writes run inside `lock`/`unlock`: an RPC error from `edit-config` or `commit` triggers `discard-changes` followed by `unlock`, and if either `discard-changes` or `unlock` fails the poisoned session is retired and reconnected in the background while preserving the primary `Set` outcome. + +**Lock-held error** (`ErrLockHeld`, defined in `pkg/datastore/target/netconf/types`): +A `` `` carrying `error-info/session-id`, indicating another NETCONF session or non-NETCONF management entity holds the target datastore lock. `ncTarget` fails immediately on `ErrLockHeld` without issuing `discard-changes`, whereas a `` failure without `ErrLockHeld` (dirty unlocked candidate) triggers a single `discard-changes` and lock retry. **Capabilities-changed error** (`ErrCapabilitiesChanged`, defined in `pkg/datastore/target/netconf/types`): A device-returned `` carrying `error-severity=error`, `error-tag=resource-denied`, and `error-app-tag=capabilities-changed`, raised when out-of-band changes alter the device's advertised capability set after the initial `` exchange and the existing NETCONF session can no longer serve RPCs. Unlike validation RPC errors, `ncTarget` retires the stale session immediately, wraps the failure in `ErrNotConnected`, and schedules a fresh session with a cooldown (`defaultCapabilitiesReconnectCooldown`) between capabilities-triggered dials so a misbehaving peer cannot induce a tight reconnect loop. diff --git a/pkg/datastore/target/netconf/driver.go b/pkg/datastore/target/netconf/driver.go index fdcf3d09..f2ebbc5d 100644 --- a/pkg/datastore/target/netconf/driver.go +++ b/pkg/datastore/target/netconf/driver.go @@ -23,7 +23,8 @@ type Driver interface { GetConfig(source string, filter string) (*types.NetconfResponse, error) // EditConfig applies to the provided configuration target (candidate|running) the xml config provided in the config parameter EditConfig(target string, config string) (*types.NetconfResponse, error) - // lock a target datastore + // Lock acquires a datastore lock on target. When rejected because another + // session or entity already holds the lock, the returned error wraps types.ErrLockHeld. Lock(target string) (*types.NetconfResponse, error) // unlock a target datastore Unlock(target string) (*types.NetconfResponse, error) diff --git a/pkg/datastore/target/netconf/driver/scrapligo/scrapligo.go b/pkg/datastore/target/netconf/driver/scrapligo/scrapligo.go index 41c6ccfe..f74d1b1d 100644 --- a/pkg/datastore/target/netconf/driver/scrapligo/scrapligo.go +++ b/pkg/datastore/target/netconf/driver/scrapligo/scrapligo.go @@ -81,7 +81,7 @@ func parseReply(resp *response.NetconfResponse) (*etree.Document, error) { } } if len(failing) > 0 { - return nil, replyError(resp, failing) + return doc, replyError(resp, failing) } // scrapligo flagged a failure that is not an rpc-error, e.g. 1.1 framing if len(rpcErrs) == 0 && resp.Failed != nil { @@ -301,12 +301,30 @@ func (snt *ScrapligoNetconfTarget) Lock(target string) (*types.NetconfResponse, } x, err := parseReply(resp) if err != nil { + if hasLockOwner(x) && !errors.Is(err, types.ErrCapabilitiesChanged) { + return nil, fmt.Errorf("%w: %w", types.ErrLockHeld, err) + } return nil, err } return types.NewNetconfResponse(x), nil } +func hasLockOwner(doc *etree.Document) bool { + if doc == nil { + return false + } + for _, e := range doc.FindElements("//rpc-error") { + if childText(e, "error-severity") == "warning" { + continue + } + if info := e.SelectElement("error-info"); info != nil && childText(info, "session-id") != "" { + return true + } + } + return false +} + func (snt *ScrapligoNetconfTarget) Unlock(target string) (*types.NetconfResponse, error) { resp, err := snt.driver.Unlock(target) if err != nil { diff --git a/pkg/datastore/target/netconf/driver/scrapligo/scrapligo_test.go b/pkg/datastore/target/netconf/driver/scrapligo/scrapligo_test.go index 89296c5f..935a2be4 100644 --- a/pkg/datastore/target/netconf/driver/scrapligo/scrapligo_test.go +++ b/pkg/datastore/target/netconf/driver/scrapligo/scrapligo_test.go @@ -321,3 +321,43 @@ func Test_CapabilitiesChanged_OverSSH(t *testing.T) { t.Errorf("plain resource-denied must not match ErrCapabilitiesChanged, got %v", err) } } + +func Test_Lock_ClassifiesLockHeldBySessionID_OverSSH(t *testing.T) { + s := newFakeNetconfServer(t) + d := newTestTarget(t, s, 5*time.Second) + defer closeWithin(t, d, time.Second) + + s.setReplyBody(`` + + `protocol` + + `lock-denied` + + `error` + + `42` + + ``) + if _, err := d.Lock("candidate"); !errors.Is(err, nctypes.ErrLockHeld) { + t.Errorf("Lock held by session 42: error = %v, want ErrLockHeld", err) + } + + s.setReplyBody(`` + + `protocol` + + `lock-denied` + + `error` + + ` 0 ` + + ``) + if _, err := d.Lock("candidate"); !errors.Is(err, nctypes.ErrLockHeld) { + t.Errorf("Lock held by non-NETCONF entity (session 0): error = %v, want ErrLockHeld", err) + } + + s.setReplyBody(`` + + `protocol` + + `in-use` + + `error` + + `Candidate configuration has uncommitted changes` + + ``) + _, err := d.Lock("candidate") + if err == nil { + t.Fatal("expected Lock error when candidate has uncommitted changes") + } + if errors.Is(err, nctypes.ErrLockHeld) { + t.Errorf("dirty candidate without session-id must not match ErrLockHeld, got %v", err) + } +} diff --git a/pkg/datastore/target/netconf/nc.go b/pkg/datastore/target/netconf/nc.go index b7b7dd11..1e2ed830 100644 --- a/pkg/datastore/target/netconf/nc.go +++ b/pkg/datastore/target/netconf/nc.go @@ -177,11 +177,8 @@ func (t *ncTarget) internalGet(ctx context.Context, req *sdcpb.GetDataRequest) ( // execute the GetConfig rpc ncResponse, err := drv.GetConfig(source, filterDoc) if err != nil { - if isTransportError(err) { - return nil, t.handleTransportError(ctx, drv, err) - } - if errors.Is(err, nctypes.ErrCapabilitiesChanged) { - return nil, t.handleCapabilitiesChanged(ctx, drv, err) + if sessErr, ok := t.handleSessionError(ctx, drv, err); ok { + return nil, sessErr } return nil, err } @@ -242,16 +239,10 @@ func (t *ncTarget) Status() *types.TargetStatus { return result } -// handleTransportError retires the driver that failed, starts a background -// reconnect, and wraps err in types.ErrNotConnected so the caller's caller -// (ultimately the TransactionSet gRPC handler, via translateInternalToGrpcError) -// can classify it as recoverable. -// -// failed is the driver the failing RPC ran on. If it was already replaced by -// a concurrent failure or a reconnect, the current driver is left untouched. -// The old driver is closed in the background so the caller never waits on a -// dead peer. -func (t *ncTarget) handleTransportError(ctx context.Context, failed Driver, err error) error { +// retireDriver detaches failed from the target if it is still the active +// driver, starts a background reconnect, and closes failed asynchronously so +// the caller never blocks on a dead or wedged peer. +func (t *ncTarget) retireDriver(ctx context.Context, failed Driver) { t.dm.Lock() if failed != nil && t.driver == failed { t.driver = nil @@ -265,9 +256,40 @@ func (t *ncTarget) handleTransportError(ctx context.Context, failed Driver, err if failed != nil { go func() { _ = failed.Close() }() } +} + +// retirePoisoned retires failed when candidate cleanup or unlock fails, leaving +// the primary RPC result untouched while respecting capabilities-changed cooldown. +func (t *ncTarget) retirePoisoned(ctx context.Context, failed Driver, err error) { + if errors.Is(err, nctypes.ErrCapabilitiesChanged) { + _ = t.handleCapabilitiesChanged(ctx, failed, err) + return + } + t.retireDriver(ctx, failed) +} + +// handleTransportError retires the driver that failed, starts a background +// reconnect, and wraps err in types.ErrNotConnected so the caller's caller +// (ultimately the TransactionSet gRPC handler, via translateInternalToGrpcError) +// can classify it as recoverable. +func (t *ncTarget) handleTransportError(ctx context.Context, failed Driver, err error) error { + t.retireDriver(ctx, failed) return fmt.Errorf("%s: %w: %w", t.name, types.ErrNotConnected, err) } +// handleSessionError retires drv and wraps err in ErrNotConnected when err +// indicates a dead or stale session (transport drop or capabilities-changed). +// It reports false without side effects for semantic RPC errors. +func (t *ncTarget) handleSessionError(ctx context.Context, drv Driver, err error) (error, bool) { + if isTransportError(err) { + return t.handleTransportError(ctx, drv, err), true + } + if errors.Is(err, nctypes.ErrCapabilitiesChanged) { + return t.handleCapabilitiesChanged(ctx, drv, err), true + } + return err, false +} + // defaultCapabilitiesReconnectCooldown is the minimum interval between two // reconnect dials triggered by a capabilities-changed rpc-error. const defaultCapabilitiesReconnectCooldown = 30 * time.Second @@ -454,30 +476,47 @@ func (t *ncTarget) setToDevice(ctx context.Context, commitDatastore string, sour return nil, err } - // leftover candidate changes would otherwise be pushed by the next commit - discard := func() { + if commitDatastore == config.NCCommitDatastoreCandidate { + if err := t.lockCandidate(ctx, drv); err != nil { + return nil, err + } + } + + unlockCandidate := func() { + if commitDatastore != config.NCCommitDatastoreCandidate { + return + } + if _, err := drv.Unlock(config.NCCommitDatastoreCandidate); err != nil { + log.Error(err, "failed unlocking candidate datastore, retiring session") + t.retirePoisoned(ctx, drv, err) + } + } + + cleanupFailedCandidate := func() { + if commitDatastore != config.NCCommitDatastoreCandidate { + return + } if err := drv.Discard(); err != nil { - log.Error(err, "failed while discarding pending changes") + log.Error(err, "failed while discarding pending changes, retiring session") + t.retirePoisoned(ctx, drv, err) + return } + unlockCandidate() } // edit the config resp, err := drv.EditConfig(commitDatastore, xdoc) if err != nil { log.Error(err, "failed during edit-config") - if isTransportError(err) { - return nil, t.handleTransportError(ctx, drv, err) - } - if errors.Is(err, nctypes.ErrCapabilitiesChanged) { - return nil, t.handleCapabilitiesChanged(ctx, drv, err) - } - if commitDatastore == config.NCCommitDatastoreCandidate { - discard() + if sessErr, ok := t.handleSessionError(ctx, drv, err); ok { + return nil, sessErr } + cleanupFailedCandidate() return nil, err } rpcWarnings, err := filterRPCErrors(resp.Doc, "warning") if err != nil { + cleanupFailedCandidate() return nil, fmt.Errorf("filtering netconf rpc-errors with severity warnings: %w", err) } @@ -487,23 +526,57 @@ func (t *ncTarget) setToDevice(ctx context.Context, commitDatastore string, sour commitResp, err := drv.Commit() if err != nil { log.Error(err, "failed during commit") - if isTransportError(err) { - return nil, t.handleTransportError(ctx, drv, err) + if sessErr, ok := t.handleSessionError(ctx, drv, err); ok { + return nil, sessErr } - if errors.Is(err, nctypes.ErrCapabilitiesChanged) { - return nil, t.handleCapabilitiesChanged(ctx, drv, err) - } - discard() + cleanupFailedCandidate() return nil, err } commitWarnings, err := filterRPCErrors(commitResp.Doc, "warning") if err != nil { + unlockCandidate() return nil, fmt.Errorf("filtering netconf rpc-errors with severity warnings: %w", err) } rpcWarnings = append(rpcWarnings, commitWarnings...) + unlockCandidate() } return &sdcpb.SetDataResponse{ Warnings: rpcWarnings, Timestamp: time.Now().UnixNano(), }, nil } + +// lockCandidate acquires the candidate datastore lock, discarding uncommitted +// candidate changes and retrying once when lock failure reports no active lock holder. +func (t *ncTarget) lockCandidate(ctx context.Context, drv Driver) error { + log := logf.FromContext(ctx) + _, err := drv.Lock(config.NCCommitDatastoreCandidate) + if err == nil { + return nil + } + if sessErr, ok := t.handleSessionError(ctx, drv, err); ok { + return sessErr + } + if errors.Is(err, nctypes.ErrLockHeld) { + log.Error(err, "failed locking candidate datastore") + return err + } + + log.Info("candidate lock failed without active lock holder, discarding pending changes and retrying lock", "error", err.Error()) + if discardErr := drv.Discard(); discardErr != nil { + if sessErr, ok := t.handleSessionError(ctx, drv, discardErr); ok { + return sessErr + } + log.Error(discardErr, "failed discarding dirty candidate before lock retry") + return err + } + + if _, retryErr := drv.Lock(config.NCCommitDatastoreCandidate); retryErr != nil { + log.Error(retryErr, "failed locking candidate datastore after discard") + if sessErr, ok := t.handleSessionError(ctx, drv, retryErr); ok { + return sessErr + } + return retryErr + } + return nil +} diff --git a/pkg/datastore/target/netconf/nc_transport_error_test.go b/pkg/datastore/target/netconf/nc_transport_error_test.go index c95987a0..5e2142bc 100644 --- a/pkg/datastore/target/netconf/nc_transport_error_test.go +++ b/pkg/datastore/target/netconf/nc_transport_error_test.go @@ -20,6 +20,7 @@ import ( "fmt" "io" "strings" + "sync" "sync/atomic" "testing" "time" @@ -161,9 +162,10 @@ func Test_ncTarget_setToDevice_EditConfig_TransportError(t *testing.T) { closed := make(chan struct{}, 1) d := mocknetconf.NewMockDriver(mockCtrl) d.EXPECT().IsAlive().AnyTimes().Return(true) + d.EXPECT().Lock(config.NCCommitDatastoreCandidate).Return(&nctypes.NetconfResponse{Doc: rpcReplyDoc(t)}, nil) d.EXPECT().EditConfig(gomock.Any(), gomock.Any()).Return(nil, io.EOF) d.EXPECT().Close().DoAndReturn(func() error { closed <- struct{}{}; return nil }) - // Discard must NOT be called for a transport error. + // Discard and Unlock must NOT be called for a transport error. tr := &ncTarget{ name: "dev1", @@ -191,8 +193,12 @@ func Test_ncTarget_setToDevice_EditConfig_NonTransportError_DiscardsCandidate(t d := mocknetconf.NewMockDriver(mockCtrl) d.EXPECT().IsAlive().AnyTimes().Return(true) nonTransportErr := errors.New("rpc-error: data-exists") - d.EXPECT().EditConfig(gomock.Any(), gomock.Any()).Return(nil, nonTransportErr) - d.EXPECT().Discard().Return(nil) + gomock.InOrder( + d.EXPECT().Lock(config.NCCommitDatastoreCandidate).Return(&nctypes.NetconfResponse{Doc: rpcReplyDoc(t)}, nil), + d.EXPECT().EditConfig(gomock.Any(), gomock.Any()).Return(nil, nonTransportErr), + d.EXPECT().Discard().Return(nil), + d.EXPECT().Unlock(config.NCCommitDatastoreCandidate).Return(&nctypes.NetconfResponse{Doc: rpcReplyDoc(t)}, nil), + ) // Close must NOT be called for a non-transport error. tr := &ncTarget{ @@ -216,6 +222,7 @@ func Test_ncTarget_setToDevice_Commit_TransportError(t *testing.T) { closed := make(chan struct{}, 1) d := mocknetconf.NewMockDriver(mockCtrl) d.EXPECT().IsAlive().AnyTimes().Return(true) + d.EXPECT().Lock(config.NCCommitDatastoreCandidate).Return(&nctypes.NetconfResponse{Doc: rpcReplyDoc(t)}, nil) d.EXPECT().EditConfig(gomock.Any(), gomock.Any()).Return(&nctypes.NetconfResponse{Doc: rpcReplyDoc(t)}, nil) d.EXPECT().Commit().Return(nil, io.EOF) d.EXPECT().Close().DoAndReturn(func() error { closed <- struct{}{}; return nil }) @@ -247,9 +254,11 @@ func Test_ncTarget_setToDevice_Commit_NonTransportError_DiscardsCandidate(t *tes d.EXPECT().IsAlive().AnyTimes().Return(true) commitErr := errors.New("rpc-error: commit validation failed") gomock.InOrder( + d.EXPECT().Lock(config.NCCommitDatastoreCandidate).Return(&nctypes.NetconfResponse{Doc: rpcReplyDoc(t)}, nil), d.EXPECT().EditConfig(gomock.Any(), gomock.Any()).Return(&nctypes.NetconfResponse{Doc: rpcReplyDoc(t)}, nil), d.EXPECT().Commit().Return(nil, commitErr), d.EXPECT().Discard().Return(nil), + d.EXPECT().Unlock(config.NCCommitDatastoreCandidate).Return(&nctypes.NetconfResponse{Doc: rpcReplyDoc(t)}, nil), ) // Close must NOT be called for a non-transport error. @@ -274,12 +283,14 @@ func Test_ncTarget_setToDevice_ReturnsEditAndCommitWarnings(t *testing.T) { mockCtrl := gomock.NewController(t) d := mocknetconf.NewMockDriver(mockCtrl) d.EXPECT().IsAlive().AnyTimes().Return(true) + d.EXPECT().Lock(config.NCCommitDatastoreCandidate).Return(&nctypes.NetconfResponse{Doc: rpcReplyDoc(t)}, nil) d.EXPECT().EditConfig(gomock.Any(), gomock.Any()).Return(&nctypes.NetconfResponse{ Doc: replyDoc(t, ""+fmt.Sprintf(warning, "edit")+""), }, nil) d.EXPECT().Commit().Return(&nctypes.NetconfResponse{ Doc: replyDoc(t, ""+fmt.Sprintf(warning, "commit")+""), }, nil) + d.EXPECT().Unlock(config.NCCommitDatastoreCandidate).Return(&nctypes.NetconfResponse{Doc: rpcReplyDoc(t)}, nil) tr := &ncTarget{name: "dev1", driver: d, sbiConfig: testSBIConfig(), newDriver: failingDriverFactory} @@ -416,9 +427,10 @@ func Test_ncTarget_setToDevice_EditConfig_CapabilitiesChanged_SkipsDiscard(t *te closed := make(chan struct{}, 1) d := mocknetconf.NewMockDriver(mockCtrl) d.EXPECT().IsAlive().AnyTimes().Return(true) + d.EXPECT().Lock(config.NCCommitDatastoreCandidate).Return(&nctypes.NetconfResponse{Doc: rpcReplyDoc(t)}, nil) d.EXPECT().EditConfig(gomock.Any(), gomock.Any()).Return(nil, capsChangedErr()) d.EXPECT().Close().DoAndReturn(func() error { closed <- struct{}{}; return nil }) - // Discard must NOT be called when retiring a session due to capabilities-changed. + // Discard and Unlock must NOT be called when retiring a session due to capabilities-changed. ctx, stop := context.WithCancel(context.Background()) defer stop() @@ -440,6 +452,7 @@ func Test_ncTarget_setToDevice_Commit_CapabilitiesChanged_Reconnects(t *testing. closed := make(chan struct{}, 1) d := mocknetconf.NewMockDriver(mockCtrl) d.EXPECT().IsAlive().AnyTimes().Return(true) + d.EXPECT().Lock(config.NCCommitDatastoreCandidate).Return(&nctypes.NetconfResponse{Doc: rpcReplyDoc(t)}, nil) d.EXPECT().EditConfig(gomock.Any(), gomock.Any()).Return(&nctypes.NetconfResponse{Doc: rpcReplyDoc(t)}, nil) d.EXPECT().Commit().Return(nil, capsChangedErr()) d.EXPECT().Close().DoAndReturn(func() error { closed <- struct{}{}; return nil }) @@ -612,3 +625,444 @@ func Test_ncTarget_CapabilitiesChanged_StaleDriverDoesNotDisconnectOrAdvanceCool t.Errorf("stale driver failure must not advance nextCapsReconnect, got %v", tr.nextCapsReconnect) } } + +// fakeCandidateDriver models an RFC 6241 device with shared and +// datastores, session lock ownership, and auto-discard when a locked +// session closes. +type fakeCandidateDriver struct { + mu sync.Mutex + alive bool + closedCh chan struct{} + closeOnce sync.Once + running string + candidate string + candidateDirty bool + lockedBy int // 0 = unlocked, 1 = this session, >1 = another session + + editErr error + commitErr error + discardErr error + unlockErr error + lockErr error +} + +func newFakeCandidateDriver() *fakeCandidateDriver { + const initial = "" + return &fakeCandidateDriver{ + alive: true, + closedCh: make(chan struct{}), + running: initial, + candidate: initial, + } +} + +func (f *fakeCandidateDriver) okReply() *nctypes.NetconfResponse { + doc := etree.NewDocument() + _ = doc.ReadFromString("") + return &nctypes.NetconfResponse{Doc: doc} +} + +func (f *fakeCandidateDriver) Get(string) (*nctypes.NetconfResponse, error) { + return f.okReply(), nil +} + +func (f *fakeCandidateDriver) GetConfig(string, string) (*nctypes.NetconfResponse, error) { + return f.okReply(), nil +} + +func (f *fakeCandidateDriver) Validate(string) (*nctypes.NetconfResponse, error) { + return f.okReply(), nil +} + +func (f *fakeCandidateDriver) IsAlive() bool { + f.mu.Lock() + defer f.mu.Unlock() + return f.alive +} + +func (f *fakeCandidateDriver) Close() error { + f.mu.Lock() + f.alive = false + // Per RFC 6241 §8.3.4, uncommitted changes made under a session lock are + // discarded when the session holding the lock terminates. + if f.lockedBy == 1 { + f.candidate = f.running + f.candidateDirty = false + f.lockedBy = 0 + } + f.mu.Unlock() + f.closeOnce.Do(func() { close(f.closedCh) }) + return nil +} + +func (f *fakeCandidateDriver) Lock(target string) (*nctypes.NetconfResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + if f.lockErr != nil { + err := f.lockErr + f.lockErr = nil + return nil, err + } + if target != config.NCCommitDatastoreCandidate { + return f.okReply(), nil + } + if f.lockedBy != 0 { + return nil, fmt.Errorf("%w: locked by session %d", nctypes.ErrLockHeld, f.lockedBy) + } + if f.candidateDirty { + return nil, errors.New("rpc-error: in-use: candidate has uncommitted changes") + } + f.lockedBy = 1 + return f.okReply(), nil +} + +func (f *fakeCandidateDriver) Unlock(target string) (*nctypes.NetconfResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + if f.unlockErr != nil { + err := f.unlockErr + f.unlockErr = nil + return nil, err + } + if target == config.NCCommitDatastoreCandidate { + if f.lockedBy != 1 { + return nil, errors.New("rpc-error: operation-failed: lock not held") + } + if f.candidateDirty { + f.candidate = f.running + f.candidateDirty = false + } + f.lockedBy = 0 + } + return f.okReply(), nil +} + +func (f *fakeCandidateDriver) EditConfig(target, cfg string) (*nctypes.NetconfResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + if target == config.NCCommitDatastoreRunning { + if f.editErr != nil { + return nil, f.editErr + } + f.running = cfg + return f.okReply(), nil + } + // stop-on-error may partially modify candidate before returning an error + f.candidate = cfg + f.candidateDirty = true + if f.editErr != nil { + return nil, f.editErr + } + return f.okReply(), nil +} + +func (f *fakeCandidateDriver) Commit() (*nctypes.NetconfResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + if f.commitErr != nil { + return nil, f.commitErr + } + f.running = f.candidate + f.candidateDirty = false + return f.okReply(), nil +} + +func (f *fakeCandidateDriver) Discard() error { + f.mu.Lock() + defer f.mu.Unlock() + if f.discardErr != nil { + err := f.discardErr + f.discardErr = nil + return err + } + if f.lockedBy != 0 && f.lockedBy != 1 { + return errors.New("rpc-error: in-use: candidate locked by another session") + } + f.candidate = f.running + f.candidateDirty = false + return nil +} + +func Test_Set_CandidateLocksAndUnlocks(t *testing.T) { + t.Run("mid-flight transport drop releases lock and leaves candidate clean via session close", func(t *testing.T) { + dev := newFakeCandidateDriver() + dev.editErr = io.EOF + + ctx, stop := context.WithCancel(context.Background()) + defer stop() + tr := &ncTarget{ + name: "dev1", + driver: dev, + sbiConfig: testSBIConfig(), + lifeCtx: ctx, + lifeStop: stop, + newDriver: failingDriverFactory, + } + + _, err := tr.Set(ctx, newFakeTargetSource()) + if !errors.Is(err, types.ErrNotConnected) { + t.Fatalf("Set error = %v, want ErrNotConnected", err) + } + <-dev.closedCh + + if dev.candidateDirty { + t.Error("candidate remained dirty after mid-flight transport drop; expected Lock before EditConfig so session close discards candidate") + } + if dev.lockedBy != 0 { + t.Errorf("lockedBy = %d, want 0", dev.lockedBy) + } + }) + + t.Run("back-to-back candidate Sets succeed and release lock after commit", func(t *testing.T) { + dev := newFakeCandidateDriver() + tr := &ncTarget{ + name: "dev1", + driver: dev, + sbiConfig: testSBIConfig(), + newDriver: failingDriverFactory, + } + + if _, err := tr.Set(context.Background(), newFakeTargetSource()); err != nil { + t.Fatalf("first Set: %v", err) + } + if dev.lockedBy != 0 { + t.Fatalf("candidate remained locked after first Set (lockedBy=%d)", dev.lockedBy) + } + if _, err := tr.Set(context.Background(), newFakeTargetSource()); err != nil { + t.Fatalf("second Set: %v", err) + } + }) + + t.Run("running datastore mode does not lock candidate", func(t *testing.T) { + dev := newFakeCandidateDriver() + dev.lockedBy = 42 // another session holds candidate lock + cfg := testSBIConfig() + cfg.NetconfOptions.CommitDatastore = config.NCCommitDatastoreRunning + + tr := &ncTarget{ + name: "dev1", + driver: dev, + sbiConfig: cfg, + newDriver: failingDriverFactory, + } + + if _, err := tr.Set(context.Background(), newFakeTargetSource()); err != nil { + t.Fatalf("Set to running failed while candidate was locked: %v", err) + } + if dev.lockedBy != 42 { + t.Errorf("running mode touched candidate lock: lockedBy = %d, want 42", dev.lockedBy) + } + }) +} + +func Test_Set_DirtyCandidateRecoveryAndLockHeld(t *testing.T) { + t.Run("dirty unlocked candidate is discarded once and Set succeeds", func(t *testing.T) { + dev := newFakeCandidateDriver() + dev.candidate = "" + dev.candidateDirty = true + + tr := &ncTarget{ + name: "dev1", + driver: dev, + sbiConfig: testSBIConfig(), + newDriver: failingDriverFactory, + } + + if _, err := tr.Set(context.Background(), newFakeTargetSource()); err != nil { + t.Fatalf("Set on dirty unlocked candidate failed: %v", err) + } + if dev.candidateDirty { + t.Error("candidate remained dirty after Set") + } + if dev.lockedBy != 0 { + t.Errorf("lockedBy = %d, want 0", dev.lockedBy) + } + if !strings.Contains(dev.running, "eth0") { + t.Errorf("running = %q, want committed interface eth0", dev.running) + } + }) + + t.Run("lock held by another session fails without wiping candidate", func(t *testing.T) { + dev := newFakeCandidateDriver() + dev.lockedBy = 42 + dev.candidate = "" + dev.candidateDirty = true + + tr := &ncTarget{ + name: "dev1", + driver: dev, + sbiConfig: testSBIConfig(), + newDriver: failingDriverFactory, + } + + _, err := tr.Set(context.Background(), newFakeTargetSource()) + if !errors.Is(err, nctypes.ErrLockHeld) { + t.Fatalf("Set error = %v, want ErrLockHeld", err) + } + if dev.candidate != "" { + t.Errorf("candidate = %q, want operator changes preserved", dev.candidate) + } + if !tr.Status().IsConnected() { + t.Error("session must stay connected after lock-denied") + } + }) + + t.Run("failed pre-lock discard with non-transport error preserves healthy session", func(t *testing.T) { + dev := newFakeCandidateDriver() + dev.candidate = "" + dev.candidateDirty = true + dev.discardErr = errors.New("rpc-error: in-use") + + tr := &ncTarget{ + name: "dev1", + driver: dev, + sbiConfig: testSBIConfig(), + newDriver: failingDriverFactory, + } + + _, err := tr.Set(context.Background(), newFakeTargetSource()) + if err == nil { + t.Fatal("expected Set error when both Lock and pre-lock Discard fail") + } + if errors.Is(err, types.ErrNotConnected) { + t.Errorf("did not expect ErrNotConnected, got %v", err) + } + if !tr.Status().IsConnected() { + t.Error("session must stay connected when pre-lock Discard fails with non-transport error") + } + }) + + t.Run("transport error during pre-lock discard retires session", func(t *testing.T) { + dev := newFakeCandidateDriver() + dev.candidate = "" + dev.candidateDirty = true + dev.discardErr = io.EOF + + ctx, stop := context.WithCancel(context.Background()) + defer stop() + tr := &ncTarget{ + name: "dev1", + driver: dev, + sbiConfig: testSBIConfig(), + lifeCtx: ctx, + lifeStop: stop, + newDriver: failingDriverFactory, + } + + _, err := tr.Set(ctx, newFakeTargetSource()) + if !errors.Is(err, types.ErrNotConnected) { + t.Fatalf("Set error = %v, want ErrNotConnected", err) + } + <-dev.closedCh + }) +} + +func Test_Set_RetiresPoisonedSessionOnFailedDiscardOrUnlock(t *testing.T) { + t.Run("failed post-commit Discard retires session and preserves commit error", func(t *testing.T) { + poisoned := newFakeCandidateDriver() + commitErr := errors.New("rpc-error: must constraint violated") + poisoned.commitErr = commitErr + poisoned.discardErr = errors.New("rpc-error: discard failed") + + fresh := newFakeCandidateDriver() + + ctx, stop := context.WithCancel(context.Background()) + defer stop() + tr := &ncTarget{ + name: "dev1", + driver: poisoned, + sbiConfig: testSBIConfig(), + lifeCtx: ctx, + lifeStop: stop, + newDriver: func(*config.SBI) (Driver, error) { return fresh, nil }, + } + + _, err := tr.Set(ctx, newFakeTargetSource()) + if !errors.Is(err, commitErr) { + t.Fatalf("Set error = %v, want %v", err, commitErr) + } + if errors.Is(err, types.ErrNotConnected) { + t.Errorf("semantic commit error must not be wrapped in ErrNotConnected, got %v", err) + } + + select { + case <-poisoned.closedCh: + case <-time.After(time.Second): + t.Fatal("poisoned session was not closed after failed Discard") + } + if poisoned.candidateDirty || poisoned.lockedBy != 0 { + t.Errorf("closing poisoned session must release lock and dirty candidate (dirty=%v, lockedBy=%d)", poisoned.candidateDirty, poisoned.lockedBy) + } + }) + + t.Run("failed Unlock after failed EditConfig retires session and preserves edit error", func(t *testing.T) { + poisoned := newFakeCandidateDriver() + editErr := errors.New("rpc-error: unknown-element") + poisoned.editErr = editErr + poisoned.unlockErr = errors.New("rpc-error: unlock failed") + + ctx, stop := context.WithCancel(context.Background()) + defer stop() + tr := &ncTarget{ + name: "dev1", + driver: poisoned, + sbiConfig: testSBIConfig(), + lifeCtx: ctx, + lifeStop: stop, + newDriver: failingDriverFactory, + } + + _, err := tr.Set(ctx, newFakeTargetSource()) + if !errors.Is(err, editErr) { + t.Fatalf("Set error = %v, want %v", err, editErr) + } + if errors.Is(err, types.ErrNotConnected) { + t.Errorf("semantic edit error must not be wrapped in ErrNotConnected, got %v", err) + } + + select { + case <-poisoned.closedCh: + case <-time.After(time.Second): + t.Fatal("session with stuck lock was not closed after failed Unlock") + } + if poisoned.lockedBy != 0 { + t.Errorf("lockedBy = %d, want 0", poisoned.lockedBy) + } + }) + + t.Run("failed Unlock after successful Commit returns success and retires session to release lock", func(t *testing.T) { + poisoned := newFakeCandidateDriver() + poisoned.unlockErr = io.EOF + + ctx, stop := context.WithCancel(context.Background()) + defer stop() + tr := &ncTarget{ + name: "dev1", + driver: poisoned, + sbiConfig: testSBIConfig(), + lifeCtx: ctx, + lifeStop: stop, + newDriver: failingDriverFactory, + } + + rsp, err := tr.Set(ctx, newFakeTargetSource()) + if err != nil { + t.Fatalf("Set failed after Commit already succeeded: %v", err) + } + if rsp == nil { + t.Fatal("expected non-nil SetDataResponse") + } + if !strings.Contains(poisoned.running, "eth0") { + t.Errorf("running = %q, want committed eth0", poisoned.running) + } + + select { + case <-poisoned.closedCh: + case <-time.After(time.Second): + t.Fatal("session with stuck lock was not closed after post-Commit Unlock failure") + } + if poisoned.lockedBy != 0 { + t.Errorf("lockedBy = %d, want 0", poisoned.lockedBy) + } + }) +} diff --git a/pkg/datastore/target/netconf/types/errors.go b/pkg/datastore/target/netconf/types/errors.go index cd284490..f3c3552a 100644 --- a/pkg/datastore/target/netconf/types/errors.go +++ b/pkg/datastore/target/netconf/types/errors.go @@ -20,3 +20,7 @@ import "errors" // resource-denied, and error-app-tag capabilities-changed: the device rejects // RPCs on the current session because its capability set changed after hello. var ErrCapabilitiesChanged = errors.New("device capabilities changed") + +// ErrLockHeld marks a lock rpc-error carrying error-info/session-id: another +// NETCONF session or non-NETCONF management entity holds the target lock. +var ErrLockHeld = errors.New("datastore lock held by another entity") From 8e0a2e8b2cbfce593d864d9b5cd87961e3af58e8 Mon Sep 17 00:00:00 2001 From: Markus Vahlenkamp Date: Thu, 26 Nov 2026 11:38:57 +0100 Subject: [PATCH 2/2] refactor(netconf): split candidate/running Set paths and expand seam tests Signed-off-by: Markus Vahlenkamp --- .../netconf/driver/scrapligo/scrapligo.go | 40 ++-- pkg/datastore/target/netconf/nc.go | 94 +++++---- .../target/netconf/nc_transport_error_test.go | 198 +++++++++++++++--- 3 files changed, 253 insertions(+), 79 deletions(-) diff --git a/pkg/datastore/target/netconf/driver/scrapligo/scrapligo.go b/pkg/datastore/target/netconf/driver/scrapligo/scrapligo.go index f74d1b1d..0ff256a9 100644 --- a/pkg/datastore/target/netconf/driver/scrapligo/scrapligo.go +++ b/pkg/datastore/target/netconf/driver/scrapligo/scrapligo.go @@ -66,12 +66,23 @@ func normalizeTransportError(err error) error { // resp.ErrorMessages misses namespace-prefixed elements and tags split by // NETCONF 1.1 chunk markers. func parseReply(resp *response.NetconfResponse) (*etree.Document, error) { + doc, failing, err := parseReplyElements(resp) + if err != nil { + return nil, err + } + if len(failing) > 0 { + return nil, replyError(resp, failing) + } + return doc, nil +} + +func parseReplyElements(resp *response.NetconfResponse) (*etree.Document, []*etree.Element, error) { doc := etree.NewDocument() if err := doc.ReadFromString(resp.Result); err != nil { if resp.Failed != nil { - return nil, resp.Failed + return nil, nil, resp.Failed } - return nil, err + return nil, nil, err } rpcErrs := doc.FindElements("//rpc-error") var failing []*etree.Element @@ -80,14 +91,11 @@ func parseReply(resp *response.NetconfResponse) (*etree.Document, error) { failing = append(failing, e) } } - if len(failing) > 0 { - return doc, replyError(resp, failing) - } // scrapligo flagged a failure that is not an rpc-error, e.g. 1.1 framing if len(rpcErrs) == 0 && resp.Failed != nil { - return nil, resp.Failed + return nil, nil, resp.Failed } - return doc, nil + return doc, failing, nil } // replyError returns resp.Failed (or an equivalent error when scrapligo missed @@ -299,9 +307,13 @@ func (snt *ScrapligoNetconfTarget) Lock(target string) (*types.NetconfResponse, if err != nil { return nil, normalizeTransportError(err) } - x, err := parseReply(resp) + x, failing, err := parseReplyElements(resp) if err != nil { - if hasLockOwner(x) && !errors.Is(err, types.ErrCapabilitiesChanged) { + return nil, err + } + if len(failing) > 0 { + err := replyError(resp, failing) + if hasLockOwner(failing) && !errors.Is(err, types.ErrCapabilitiesChanged) { return nil, fmt.Errorf("%w: %w", types.ErrLockHeld, err) } return nil, err @@ -310,14 +322,8 @@ func (snt *ScrapligoNetconfTarget) Lock(target string) (*types.NetconfResponse, return types.NewNetconfResponse(x), nil } -func hasLockOwner(doc *etree.Document) bool { - if doc == nil { - return false - } - for _, e := range doc.FindElements("//rpc-error") { - if childText(e, "error-severity") == "warning" { - continue - } +func hasLockOwner(failing []*etree.Element) bool { + for _, e := range failing { if info := e.SelectElement("error-info"); info != nil && childText(info, "session-id") != "" { return true } diff --git a/pkg/datastore/target/netconf/nc.go b/pkg/datastore/target/netconf/nc.go index 1e2ed830..b2696860 100644 --- a/pkg/datastore/target/netconf/nc.go +++ b/pkg/datastore/target/netconf/nc.go @@ -262,7 +262,7 @@ func (t *ncTarget) retireDriver(ctx context.Context, failed Driver) { // the primary RPC result untouched while respecting capabilities-changed cooldown. func (t *ncTarget) retirePoisoned(ctx context.Context, failed Driver, err error) { if errors.Is(err, nctypes.ErrCapabilitiesChanged) { - _ = t.handleCapabilitiesChanged(ctx, failed, err) + t.retireCapabilitiesChanged(ctx, failed, err) return } t.retireDriver(ctx, failed) @@ -301,15 +301,7 @@ func (t *ncTarget) capabilitiesCooldown() time.Duration { return defaultCapabilitiesReconnectCooldown } -// handleCapabilitiesChanged retires failed after a capabilities-changed -// rpc-error and schedules a background reconnect so the new session performs a -// fresh hello exchange. -// -// Dials triggered by capabilities-changed are spaced by at least the target's -// capabilities cooldown; if another session hits capabilities-changed inside -// that window, it is still retired immediately while dialing waits out the -// remaining cooldown. -func (t *ncTarget) handleCapabilitiesChanged(ctx context.Context, failed Driver, err error) error { +func (t *ncTarget) retireCapabilitiesChanged(ctx context.Context, failed Driver, err error) { log := logf.FromContext(ctx) cooldown := t.capabilitiesCooldown() @@ -343,6 +335,18 @@ func (t *ncTarget) handleCapabilitiesChanged(ctx context.Context, failed Driver, if failed != nil { go func() { _ = failed.Close() }() } +} + +// handleCapabilitiesChanged retires failed after a capabilities-changed +// rpc-error and schedules a background reconnect so the new session performs a +// fresh hello exchange. +// +// Dials triggered by capabilities-changed are spaced by at least the target's +// capabilities cooldown; if another session hits capabilities-changed inside +// that window, it is still retired immediately while dialing waits out the +// remaining cooldown. +func (t *ncTarget) handleCapabilitiesChanged(ctx context.Context, failed Driver, err error) error { + t.retireCapabilitiesChanged(ctx, failed, err) return fmt.Errorf("%s: %w: %w", t.name, types.ErrNotConnected, err) } @@ -452,6 +456,7 @@ func filterRPCErrors(xml *etree.Document, severity string) ([]string, error) { func (t *ncTarget) setToDevice(ctx context.Context, commitDatastore string, source types.TargetSource) (*sdcpb.SetDataResponse, error) { log := logf.FromContext(ctx).WithValues("commit-datastore", commitDatastore) + ctx = logf.IntoContext(ctx, log) xtree, err := source.ToXML(ctx, true, t.sbiConfig.NetconfOptions.IncludeNS, t.sbiConfig.NetconfOptions.OperationWithNamespace, t.sbiConfig.NetconfOptions.UseOperationRemove) if err != nil { return nil, err @@ -477,15 +482,37 @@ func (t *ncTarget) setToDevice(ctx context.Context, commitDatastore string, sour } if commitDatastore == config.NCCommitDatastoreCandidate { - if err := t.lockCandidate(ctx, drv); err != nil { - return nil, err + return t.setCandidate(ctx, drv, xdoc) + } + return t.setRunning(ctx, drv, xdoc) +} + +func (t *ncTarget) setRunning(ctx context.Context, drv Driver, xdoc string) (*sdcpb.SetDataResponse, error) { + resp, err := drv.EditConfig(config.NCCommitDatastoreRunning, xdoc) + if err != nil { + logf.FromContext(ctx).Error(err, "failed during edit-config") + if sessErr, ok := t.handleSessionError(ctx, drv, err); ok { + return nil, sessErr } + return nil, err + } + rpcWarnings, err := filterRPCErrors(resp.Doc, "warning") + if err != nil { + return nil, fmt.Errorf("filtering netconf rpc-errors with severity warnings: %w", err) + } + return &sdcpb.SetDataResponse{ + Warnings: rpcWarnings, + Timestamp: time.Now().UnixNano(), + }, nil +} + +func (t *ncTarget) setCandidate(ctx context.Context, drv Driver, xdoc string) (*sdcpb.SetDataResponse, error) { + log := logf.FromContext(ctx) + if err := t.lockCandidate(ctx, drv); err != nil { + return nil, err } unlockCandidate := func() { - if commitDatastore != config.NCCommitDatastoreCandidate { - return - } if _, err := drv.Unlock(config.NCCommitDatastoreCandidate); err != nil { log.Error(err, "failed unlocking candidate datastore, retiring session") t.retirePoisoned(ctx, drv, err) @@ -493,9 +520,6 @@ func (t *ncTarget) setToDevice(ctx context.Context, commitDatastore string, sour } cleanupFailedCandidate := func() { - if commitDatastore != config.NCCommitDatastoreCandidate { - return - } if err := drv.Discard(); err != nil { log.Error(err, "failed while discarding pending changes, retiring session") t.retirePoisoned(ctx, drv, err) @@ -504,8 +528,7 @@ func (t *ncTarget) setToDevice(ctx context.Context, commitDatastore string, sour unlockCandidate() } - // edit the config - resp, err := drv.EditConfig(commitDatastore, xdoc) + resp, err := drv.EditConfig(config.NCCommitDatastoreCandidate, xdoc) if err != nil { log.Error(err, "failed during edit-config") if sessErr, ok := t.handleSessionError(ctx, drv, err); ok { @@ -520,26 +543,23 @@ func (t *ncTarget) setToDevice(ctx context.Context, commitDatastore string, sour return nil, fmt.Errorf("filtering netconf rpc-errors with severity warnings: %w", err) } - // candidate stores need to commit the changes to running - if commitDatastore == config.NCCommitDatastoreCandidate { - log.Info("committing changes on target") - commitResp, err := drv.Commit() - if err != nil { - log.Error(err, "failed during commit") - if sessErr, ok := t.handleSessionError(ctx, drv, err); ok { - return nil, sessErr - } - cleanupFailedCandidate() - return nil, err - } - commitWarnings, err := filterRPCErrors(commitResp.Doc, "warning") - if err != nil { - unlockCandidate() - return nil, fmt.Errorf("filtering netconf rpc-errors with severity warnings: %w", err) + log.Info("committing changes on target") + commitResp, err := drv.Commit() + if err != nil { + log.Error(err, "failed during commit") + if sessErr, ok := t.handleSessionError(ctx, drv, err); ok { + return nil, sessErr } - rpcWarnings = append(rpcWarnings, commitWarnings...) + cleanupFailedCandidate() + return nil, err + } + commitWarnings, err := filterRPCErrors(commitResp.Doc, "warning") + if err != nil { unlockCandidate() + return nil, fmt.Errorf("filtering netconf rpc-errors with severity warnings: %w", err) } + rpcWarnings = append(rpcWarnings, commitWarnings...) + unlockCandidate() return &sdcpb.SetDataResponse{ Warnings: rpcWarnings, Timestamp: time.Now().UnixNano(), diff --git a/pkg/datastore/target/netconf/nc_transport_error_test.go b/pkg/datastore/target/netconf/nc_transport_error_test.go index 5e2142bc..5b20540c 100644 --- a/pkg/datastore/target/netconf/nc_transport_error_test.go +++ b/pkg/datastore/target/netconf/nc_transport_error_test.go @@ -626,6 +626,14 @@ func Test_ncTarget_CapabilitiesChanged_StaleDriverDoesNotDisconnectOrAdvanceCool } } +type lockOwner int + +const ( + lockNone lockOwner = 0 + lockThisSession lockOwner = 1 + lockOtherSession lockOwner = 42 +) + // fakeCandidateDriver models an RFC 6241 device with shared and // datastores, session lock ownership, and auto-discard when a locked // session closes. @@ -637,13 +645,14 @@ type fakeCandidateDriver struct { running string candidate string candidateDirty bool - lockedBy int // 0 = unlocked, 1 = this session, >1 = another session - - editErr error - commitErr error - discardErr error - unlockErr error - lockErr error + lockedBy lockOwner + + editErr error + commitErr error + discardErr error + unlockErr error + lockErr error + retryLockErr error } func newFakeCandidateDriver() *fakeCandidateDriver { @@ -685,10 +694,10 @@ func (f *fakeCandidateDriver) Close() error { f.alive = false // Per RFC 6241 §8.3.4, uncommitted changes made under a session lock are // discarded when the session holding the lock terminates. - if f.lockedBy == 1 { + if f.lockedBy == lockThisSession { f.candidate = f.running f.candidateDirty = false - f.lockedBy = 0 + f.lockedBy = lockNone } f.mu.Unlock() f.closeOnce.Do(func() { close(f.closedCh) }) @@ -706,13 +715,18 @@ func (f *fakeCandidateDriver) Lock(target string) (*nctypes.NetconfResponse, err if target != config.NCCommitDatastoreCandidate { return f.okReply(), nil } - if f.lockedBy != 0 { + if f.lockedBy != lockNone { return nil, fmt.Errorf("%w: locked by session %d", nctypes.ErrLockHeld, f.lockedBy) } if f.candidateDirty { + if f.retryLockErr != nil { + // arm retryLockErr for the retry attempt that follows Discard() + f.lockErr = f.retryLockErr + f.retryLockErr = nil + } return nil, errors.New("rpc-error: in-use: candidate has uncommitted changes") } - f.lockedBy = 1 + f.lockedBy = lockThisSession return f.okReply(), nil } @@ -725,14 +739,14 @@ func (f *fakeCandidateDriver) Unlock(target string) (*nctypes.NetconfResponse, e return nil, err } if target == config.NCCommitDatastoreCandidate { - if f.lockedBy != 1 { + if f.lockedBy != lockThisSession { return nil, errors.New("rpc-error: operation-failed: lock not held") } if f.candidateDirty { f.candidate = f.running f.candidateDirty = false } - f.lockedBy = 0 + f.lockedBy = lockNone } return f.okReply(), nil } @@ -775,7 +789,7 @@ func (f *fakeCandidateDriver) Discard() error { f.discardErr = nil return err } - if f.lockedBy != 0 && f.lockedBy != 1 { + if f.lockedBy != lockNone && f.lockedBy != lockThisSession { return errors.New("rpc-error: in-use: candidate locked by another session") } f.candidate = f.running @@ -808,7 +822,7 @@ func Test_Set_CandidateLocksAndUnlocks(t *testing.T) { if dev.candidateDirty { t.Error("candidate remained dirty after mid-flight transport drop; expected Lock before EditConfig so session close discards candidate") } - if dev.lockedBy != 0 { + if dev.lockedBy != lockNone { t.Errorf("lockedBy = %d, want 0", dev.lockedBy) } }) @@ -825,7 +839,7 @@ func Test_Set_CandidateLocksAndUnlocks(t *testing.T) { if _, err := tr.Set(context.Background(), newFakeTargetSource()); err != nil { t.Fatalf("first Set: %v", err) } - if dev.lockedBy != 0 { + if dev.lockedBy != lockNone { t.Fatalf("candidate remained locked after first Set (lockedBy=%d)", dev.lockedBy) } if _, err := tr.Set(context.Background(), newFakeTargetSource()); err != nil { @@ -835,7 +849,7 @@ func Test_Set_CandidateLocksAndUnlocks(t *testing.T) { t.Run("running datastore mode does not lock candidate", func(t *testing.T) { dev := newFakeCandidateDriver() - dev.lockedBy = 42 // another session holds candidate lock + dev.lockedBy = lockOtherSession cfg := testSBIConfig() cfg.NetconfOptions.CommitDatastore = config.NCCommitDatastoreRunning @@ -849,8 +863,8 @@ func Test_Set_CandidateLocksAndUnlocks(t *testing.T) { if _, err := tr.Set(context.Background(), newFakeTargetSource()); err != nil { t.Fatalf("Set to running failed while candidate was locked: %v", err) } - if dev.lockedBy != 42 { - t.Errorf("running mode touched candidate lock: lockedBy = %d, want 42", dev.lockedBy) + if dev.lockedBy != lockOtherSession { + t.Errorf("running mode touched candidate lock: lockedBy = %d, want %d", dev.lockedBy, lockOtherSession) } }) } @@ -874,7 +888,7 @@ func Test_Set_DirtyCandidateRecoveryAndLockHeld(t *testing.T) { if dev.candidateDirty { t.Error("candidate remained dirty after Set") } - if dev.lockedBy != 0 { + if dev.lockedBy != lockNone { t.Errorf("lockedBy = %d, want 0", dev.lockedBy) } if !strings.Contains(dev.running, "eth0") { @@ -884,7 +898,7 @@ func Test_Set_DirtyCandidateRecoveryAndLockHeld(t *testing.T) { t.Run("lock held by another session fails without wiping candidate", func(t *testing.T) { dev := newFakeCandidateDriver() - dev.lockedBy = 42 + dev.lockedBy = lockOtherSession dev.candidate = "" dev.candidateDirty = true @@ -907,6 +921,69 @@ func Test_Set_DirtyCandidateRecoveryAndLockHeld(t *testing.T) { } }) + t.Run("transport or capabilities-changed error on initial Lock skips Discard and retires session", func(t *testing.T) { + for _, tc := range []struct { + name string + lockErr error + }{ + {"transport error", io.EOF}, + {"capabilities-changed", capsChangedErr()}, + } { + t.Run(tc.name, func(t *testing.T) { + dev := newFakeCandidateDriver() + dev.candidate = "" + dev.candidateDirty = true + dev.lockErr = tc.lockErr + + ctx, stop := context.WithCancel(context.Background()) + defer stop() + tr := &ncTarget{ + name: "dev1", + driver: dev, + sbiConfig: testSBIConfig(), + lifeCtx: ctx, + lifeStop: stop, + newDriver: failingDriverFactory, + } + + _, err := tr.Set(ctx, newFakeTargetSource()) + if !errors.Is(err, types.ErrNotConnected) { + t.Fatalf("Set error = %v, want ErrNotConnected", err) + } + if tr.Status().IsConnected() { + t.Error("expected Status() to be disconnected after session error on Lock") + } + <-dev.closedCh + if dev.candidate != "" { + t.Errorf("candidate = %q, want untouched when Lock failed with session error", dev.candidate) + } + }) + } + }) + + t.Run("retry Lock failure stops after single Discard", func(t *testing.T) { + dev := newFakeCandidateDriver() + dev.candidate = "" + dev.candidateDirty = true + retryErr := errors.New("rpc-error: lock-denied on retry") + dev.retryLockErr = retryErr + + tr := &ncTarget{ + name: "dev1", + driver: dev, + sbiConfig: testSBIConfig(), + newDriver: failingDriverFactory, + } + + _, err := tr.Set(context.Background(), newFakeTargetSource()) + if !errors.Is(err, retryErr) { + t.Fatalf("Set error = %v, want %v", err, retryErr) + } + if !tr.Status().IsConnected() { + t.Error("session must stay connected when retry Lock fails with non-transport error") + } + }) + t.Run("failed pre-lock discard with non-transport error preserves healthy session", func(t *testing.T) { dev := newFakeCandidateDriver() dev.candidate = "" @@ -953,12 +1030,15 @@ func Test_Set_DirtyCandidateRecoveryAndLockHeld(t *testing.T) { if !errors.Is(err, types.ErrNotConnected) { t.Fatalf("Set error = %v, want ErrNotConnected", err) } + if tr.Status().IsConnected() { + t.Error("expected Status() to be disconnected") + } <-dev.closedCh }) } func Test_Set_RetiresPoisonedSessionOnFailedDiscardOrUnlock(t *testing.T) { - t.Run("failed post-commit Discard retires session and preserves commit error", func(t *testing.T) { + t.Run("failed post-commit Discard retires session, reconnects to fresh session, and preserves commit error", func(t *testing.T) { poisoned := newFakeCandidateDriver() commitErr := errors.New("rpc-error: must constraint violated") poisoned.commitErr = commitErr @@ -990,9 +1070,23 @@ func Test_Set_RetiresPoisonedSessionOnFailedDiscardOrUnlock(t *testing.T) { case <-time.After(time.Second): t.Fatal("poisoned session was not closed after failed Discard") } - if poisoned.candidateDirty || poisoned.lockedBy != 0 { + if poisoned.candidateDirty || poisoned.lockedBy != lockNone { t.Errorf("closing poisoned session must release lock and dirty candidate (dirty=%v, lockedBy=%d)", poisoned.candidateDirty, poisoned.lockedBy) } + + deadline := time.Now().Add(2 * time.Second) + for !tr.Status().IsConnected() { + if time.Now().After(deadline) { + t.Fatal("target did not reconnect to fresh session") + } + time.Sleep(time.Millisecond) + } + if _, err := tr.Set(ctx, newFakeTargetSource()); err != nil { + t.Fatalf("Set on reconnected fresh session failed: %v", err) + } + if !strings.Contains(fresh.running, "eth0") { + t.Errorf("fresh.running = %q, want committed eth0", fresh.running) + } }) t.Run("failed Unlock after failed EditConfig retires session and preserves edit error", func(t *testing.T) { @@ -1019,13 +1113,16 @@ func Test_Set_RetiresPoisonedSessionOnFailedDiscardOrUnlock(t *testing.T) { if errors.Is(err, types.ErrNotConnected) { t.Errorf("semantic edit error must not be wrapped in ErrNotConnected, got %v", err) } + if tr.Status().IsConnected() { + t.Error("expected Status() to be disconnected after retiring poisoned session") + } select { case <-poisoned.closedCh: case <-time.After(time.Second): t.Fatal("session with stuck lock was not closed after failed Unlock") } - if poisoned.lockedBy != 0 { + if poisoned.lockedBy != lockNone { t.Errorf("lockedBy = %d, want 0", poisoned.lockedBy) } }) @@ -1055,14 +1152,65 @@ func Test_Set_RetiresPoisonedSessionOnFailedDiscardOrUnlock(t *testing.T) { if !strings.Contains(poisoned.running, "eth0") { t.Errorf("running = %q, want committed eth0", poisoned.running) } + if tr.Status().IsConnected() { + t.Error("expected Status() to be disconnected after retiring session with failed Unlock") + } select { case <-poisoned.closedCh: case <-time.After(time.Second): t.Fatal("session with stuck lock was not closed after post-Commit Unlock failure") } - if poisoned.lockedBy != 0 { + if poisoned.lockedBy != lockNone { t.Errorf("lockedBy = %d, want 0", poisoned.lockedBy) } }) + + t.Run("capabilities-changed on post-edit Discard honors cooldown while preserving edit error", func(t *testing.T) { + poisoned := newFakeCandidateDriver() + editErr := errors.New("rpc-error: bad-element") + poisoned.editErr = editErr + poisoned.discardErr = capsChangedErr() + + const cooldown = 100 * time.Millisecond + var dialed atomic.Bool + fresh := newFakeCandidateDriver() + + ctx, stop := context.WithCancel(context.Background()) + defer stop() + tr := &ncTarget{ + name: "dev1", + driver: poisoned, + sbiConfig: testSBIConfig(), + lifeCtx: ctx, + lifeStop: stop, + capsReconnectCooldown: cooldown, + nextCapsReconnect: time.Now().Add(cooldown), + newDriver: func(*config.SBI) (Driver, error) { + dialed.Store(true) + return fresh, nil + }, + } + + start := time.Now() + _, err := tr.Set(ctx, newFakeTargetSource()) + if !errors.Is(err, editErr) || errors.Is(err, types.ErrNotConnected) { + t.Fatalf("Set error = %v, want unwrapped %v", err, editErr) + } + if tr.Status().IsConnected() { + t.Error("expected Status() to be disconnected immediately") + } + if time.Since(start) < cooldown/2 && dialed.Load() { + t.Error("reconnect dialed before capabilities-changed cooldown elapsed") + } + <-poisoned.closedCh + + deadline := time.Now().Add(2 * time.Second) + for !tr.Status().IsConnected() { + if time.Now().After(deadline) { + t.Fatal("target did not reconnect after cooldown") + } + time.Sleep(time.Millisecond) + } + }) }