diff --git a/pkg/datastore/target/netconf/CONTEXT.md b/pkg/datastore/target/netconf/CONTEXT.md index 2a0abcbe..c86d7eb1 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 and at any depth except inside the reply's ``, which is device content returned by `get`/`get-config`. 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. The exception is a capabilities-changed error: the session is retired without a discard, because the device rejects every RPC on it. +An `` in a reply whose `error-severity` is anything but `warning`, in any namespace prefix and at any depth except inside the reply's ``, which is device content returned by `get`/`get-config`. 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 a78de784..61cf7cad 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 { // rpc-error element inside , and 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 } var failing []*etree.Element for _, e := range replyRPCErrors(doc) { @@ -79,14 +90,11 @@ func parseReply(resp *response.NetconfResponse) (*etree.Document, error) { failing = append(failing, e) } } - if len(failing) > 0 { - return nil, replyError(resp, failing) - } // scrapligo flagged a failure that no rpc-error in the reply explains, e.g. 1.1 framing if resp.Failed != nil && len(doc.FindElements("//rpc-error")) == 0 { - return nil, resp.Failed + return nil, nil, resp.Failed } - return doc, nil + return doc, failing, nil } // replyRPCErrors returns the reply's rpc-errors at any depth, since some @@ -320,14 +328,30 @@ 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 { 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 + } return types.NewNetconfResponse(x), nil } +func hasLockOwner(failing []*etree.Element) bool { + for _, e := range failing { + 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 0a809aa6..a73992eb 100644 --- a/pkg/datastore/target/netconf/driver/scrapligo/scrapligo_test.go +++ b/pkg/datastore/target/netconf/driver/scrapligo/scrapligo_test.go @@ -340,3 +340,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..b2696860 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.retireCapabilitiesChanged(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 @@ -279,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() @@ -321,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) } @@ -430,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 @@ -454,56 +481,122 @@ 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 { + 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 _, err := drv.Unlock(config.NCCommitDatastoreCandidate); err != nil { + log.Error(err, "failed unlocking candidate datastore, retiring session") + t.retirePoisoned(ctx, drv, err) + } + } + + cleanupFailedCandidate := func() { 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) + resp, err := drv.EditConfig(config.NCCommitDatastoreCandidate, 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) } - // 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 isTransportError(err) { - return nil, t.handleTransportError(ctx, drv, err) - } - if errors.Is(err, nctypes.ErrCapabilitiesChanged) { - return nil, t.handleCapabilitiesChanged(ctx, drv, err) - } - discard() - return nil, err - } - commitWarnings, err := filterRPCErrors(commitResp.Doc, "warning") - if err != nil { - 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(), }, 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..5b20540c 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,592 @@ func Test_ncTarget_CapabilitiesChanged_StaleDriverDoesNotDisconnectOrAdvanceCool t.Errorf("stale driver failure must not advance nextCapsReconnect, got %v", tr.nextCapsReconnect) } } + +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. +type fakeCandidateDriver struct { + mu sync.Mutex + alive bool + closedCh chan struct{} + closeOnce sync.Once + running string + candidate string + candidateDirty bool + lockedBy lockOwner + + editErr error + commitErr error + discardErr error + unlockErr error + lockErr error + retryLockErr 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 == lockThisSession { + f.candidate = f.running + f.candidateDirty = false + f.lockedBy = lockNone + } + 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 != 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 = lockThisSession + 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 != lockThisSession { + return nil, errors.New("rpc-error: operation-failed: lock not held") + } + if f.candidateDirty { + f.candidate = f.running + f.candidateDirty = false + } + f.lockedBy = lockNone + } + 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 != lockNone && f.lockedBy != lockThisSession { + 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 != lockNone { + 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 != lockNone { + 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 = lockOtherSession + 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 != lockOtherSession { + t.Errorf("running mode touched candidate lock: lockedBy = %d, want %d", dev.lockedBy, lockOtherSession) + } + }) +} + +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 != lockNone { + 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 = lockOtherSession + 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("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 = "" + 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) + } + 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, 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 + 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 != 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) { + 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) + } + 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 != lockNone { + 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) + } + 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 != 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) + } + }) +} 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")