Skip to content

Extensions ​

NETCONF capabilities beyond RFC 6241's own, such as :with-defaults (RFC 6243), are implemented by opt-in extensions. Each extension has its own entry point, so you only load what you use. You enable an extension per connection. Its calls then appear under its id in the layer each one works at: client.ops.<id> for calls that send an operation and hand back XML or a reply, and client.content.<id> for calls that hand back decoded, typed data. An extension can contribute to both, under the same id:

ts
import { connect } from '@node-net/netconf';
import { withDefaults } from '@node-net/netconf/operations/with-defaults';
import { monitoring } from '@node-net/netconf/operations/monitoring';

const client = await connect({
  transport,
  extensions: [withDefaults, monitoring],
});
// fully typed
client.content.withDefaults.basicMode;
// XML or text back
await client.ops.monitoring.getSchema({ identifier: 'ietf-interfaces' });
// decoded SessionInfo[]
await client.content.monitoring.sessions();

After the hello, the client checks that the server has the capabilities each extension needs. By default a missing capability makes connect() fail. With extensionCheck: 'off', every extension is enabled anyway, and each operation is still checked before it's sent. That's useful for tools that list every operation.

ExtensionRFC
monitoring6022Download YANG modules; sessions, locks, statistics
with-defaults6243Control how default values are reported
nmda8342, 8526<get-data> and <edit-data> on any datastore
yang-library8525, 7895Which modules each datastore implements
compare9144Ask the server how two datastores differ
partial-lock5717Lock only part of running
notifications5277Event notification subscriptions
subscriptions8639–8641Subscriptions and YANG-Push

All are imported from @node-net/netconf/operations/<name>.

Two helpers sit beside the extensions. They aren't passed to extensions:

  • base-notifications (RFC 6470), imported from @node-net/netconf/operations/base-notifications, decodes the config-change, session and commit events that the notifications extension delivers.
  • withCandidate() (RFC 6241), imported from @node-net/netconf, locks, edits, validates and commits the candidate, with cleanup. configure() is built on it.

monitoring ​

ts
import { connect } from '@node-net/netconf';
import { monitoring } from '@node-net/netconf/operations/monitoring';

const client = await connect({ transport, extensions: [monitoring] });
const yang = await client.ops.monitoring.getSchema({
  identifier: 'ietf-interfaces',
  version: '2018-02-20',
});
const datastores = await client.content.monitoring.datastores();
const running = datastores.find((d) => d.name === 'running');
const holder = running?.globalLock?.sessionId;

client.content.monitoring has schemas(), sessions(), datastores() (including who holds each lock) and statistics(), which read and decode /netconf-state. They are also described as data (see Reads as operations), so client.ops.run('monitoring-sessions') runs sessions().

with-defaults ​

Adds a withDefaults option to client.ops.get(), getConfig() and copyConfig(), checked against the modes the server supports, and reports the server's modes as client.content.withDefaults:

ts
import { connect } from '@node-net/netconf';
import { withDefaults, isDefault } from '@node-net/netconf/operations/with-defaults';

const client = await connect({ transport, extensions: [withDefaults] });
// e.g. 'explicit'
client.content.withDefaults.basicMode;
// or 'trim', 'explicit', 'report-all-tagged'
await client.ops.getConfig({ withDefaults: 'report-all' });

With report-all-tagged, isDefault(element) tells you whether a leaf holds its default value.

nmda ​

ts
import { connect, subtree, x } from '@node-net/netconf';
import { nmda, origins } from '@node-net/netconf/operations/nmda';

const client = await connect({ transport, extensions: [nmda] });
const data = await client.ops.nmda.getData({
  datastore: 'operational',
  filter: subtree(x('interfaces', { xmlns: IF })),
  withOrigin: true,
});
// element → 'ietf-origin:intended' | 'ietf-origin:learned' | …
const where = origins(data);

await client.ops.nmda.editData({ datastore: 'running', config });

editData() takes config as XML or RFC 7951 JSON, and getData() a JSON filter, both converted with the datastore's schema. getData() also takes configFilter, originFilter, negatedOriginFilter, maxDepth and withDefaults. With format: 'json' it resolves with RFC 7951 JSON typed by the datastore's schema, and each origin becomes an annotation, "@": { "ietf-origin:origin": "ietf-origin:intended" }. A datastore is running, candidate, startup, intended or operational (see Datastores), or { name, namespace } for any other.

yang-library ​

ts
import { connect } from '@node-net/netconf';
import {
  yangLibrary,
  findDatastore,
} from '@node-net/netconf/operations/yang-library';

const client = await connect({ transport, extensions: [yangLibrary] });
const lib = await client.content.yangLibrary.load();
const running = findDatastore(lib, 'running');
running?.modules.find((m) => m.name === 'ietf-interfaces')?.features;

The result is plain JSON-serialisable data. To reuse it across sessions, store it keyed by device and lib.contentId: if the next hello has the same content-id, the library hasn't changed. On older servers that only have :yang-library:1.0, /modules-state is read and returned in the same shape.

A session reads its library at most once. This extension, the path API and the support checks in other extensions share that read.

To find out only which datastores a server has, you don't need this extension. client.content.datastores() reads the same list, and also works on servers without a YANG library. The same goes for a datastore's modules and features: client.content.modules() resolves the datastore to its schema for you, and can also list the features a module declares but the server doesn't support.

compare ​

ts
import { connect } from '@node-net/netconf';
import { compare } from '@node-net/netconf/operations/compare';

const client = await connect({ transport, extensions: [compare] });
const diff = await client.ops.compare.datastores({
  source: 'running',
  target: 'candidate',
  filter: client.content.toXPath('/ietf-interfaces:interfaces'),
});
for (const edit of diff.edits) {
  console.log(edit.operation, edit.target, edit.value, edit.sourceValue);
}

filter may also be an RFC 7951 JSON filter, converted with the source datastore's schema. The server works out the differences and returns them as a YANG Patch that would turn source into target. Before sending, the client checks the YANG library to make sure the server supports compare.

Few servers support compare. client.content.compareDatastores() works on any server: it reads both datastores and compares them in the client, and its result has the same shape on every server.

partial-lock ​

ts
import { connect } from '@node-net/netconf';
import { partialLock } from '@node-net/netconf/operations/partial-lock';

const client = await connect({ transport, extensions: [partialLock] });
await using lock = await client.ops.partialLock.lock([
  client.content.toXPath('/ietf-interfaces:interfaces/interface[name="eth0"]'),
]);
// ["/ietf-interfaces:interfaces/interface[name='eth0']"]
lock.lockedNodes;
await client.ops.editConfig({ target: 'running', config });
// leaving the scope sends <partial-unlock>

A conflict with another session's lock rejects with a PartialLockDeniedError, which gives the holder's session-id.

WARNING

No open-source NETCONF server implements partial lock, so this extension has only been tested against the built-in fake server.

Identities and paths in what extensions return ​

Identity values the extensions decode, such as a session's transport, a subscription's end reason, a datastore or an origin, are module-qualified as RFC 7951 writes them, the same as JSON reads give them:

ts
const [session] = await client.content.monitoring.sessions();
// 'ietf-netconf-monitoring:netconf-ssh'
session.transport;

Paths to data nodes, such as a partial lock's locked nodes or a config change's target, are RFC 7951 instance-identifiers, in the same syntax as the Content layer's paths: /ietf-interfaces:interfaces/interface[name='eth0'].

The server's prefixes are replaced by module names, so a value means the same whatever prefixes the server chose, and two identities with the same name from different modules stay distinct. A module is named by the session's own lookup (the same as moduleNamespace() in reverse), else a well-known IETF module's name; a namespace no source knows is written in place of the module name. Functions you call yourself, such as origins() and decodeBaseNotification(), take the session's lookup as an option:

ts
const moduleOf = (ns: string) => client.content.moduleOf(ns);
origins(data, { moduleOf });

Operations as data ​

Every operation the client can run is described by an OperationDescriptor: its RPC name, the client.ops method that sends it, its params (name, type, whether required, allowed values), the capabilities it requires, and whether it mutates anything. client.ops.list holds the descriptors for a connected client: the base operations, each extension's, and the device profile's. Tools build commands, help, completion and a read-only guard from them, with no code per operation; the CLI is built this way.

Without a client, BASE_OPERATIONS describes the RFC 6241 base operations, and buildOperation(name, args) builds one's request from the same plain arguments client.ops.run() takes, without sending it:

ts
import { BASE_OPERATIONS, buildOperation } from '@node-net/netconf';

const op = BASE_OPERATIONS.find((d) => d.name === 'edit-config');
// ['target: datastore', 'config: xml', 'url: string', …]
op?.params.map((p) => `${p.name}: ${p.type}`);

const request = buildOperation('lock', { target: 'candidate' });
// [':candidate']
console.log(request.requires);
// <lock><target><candidate/></target></lock>
request.element;

buildOperation() throws a TypeError for a name that isn't a base operation. Run what it builds with client.session.rpc(request.element), or let client.ops.run() build and send it in one step.

Reads as operations ​

Besides their RPCs, extensions describe their content readers, the helpers that read and decode state, with kind: 'read'. They appear in client.ops.list, never change anything, and client.ops.run(name, args) resolves with the decoded data:

NameRuns
monitoring-schemas, monitoring-sessions, monitoring-datastores, monitoring-statisticsclient.content.monitoring.schemas() … statistics()
notification-streamsclient.content.notifications.streams()
subscription-streams, subscription-list, subscription-supportclient.content.subscriptions.streams(), list(), support({ refresh })
yang-libraryclient.content.yangLibrary.load({ refresh })
ts
// SessionInfo[]
const sessions = await client.ops.run('monitoring-sessions');
await client.ops.run('yang-library', { refresh: true });

Read names are hyphenated, which device profile operation names can't be, so a profile's own sessions operation never clashes with them. This is how the CLI offers them as commands.

Writing your own ​

Third-party extensions use defineExtension(), the same API the built-in extensions use. An extension declares the capabilities it needs (requires) and any it adds to the client's hello. Its calls go in two sections, both built on the session's public RpcContext: ops(ctx) becomes client.ops.<id>, and content(ctx) becomes client.content.<id>. It also declares descriptors for its RPCs, and for its reads (kind: 'read', naming a method of its content section). It can also add options to base operations, the way with-defaults adds withDefaults.

ts
import { defineExtension, x } from '@node-net/netconf';

const NS = 'urn:example:uptime';

export const uptime = defineExtension({
  id: 'uptime',
  requires: ['urn:example:uptime:1.0'],
  ops: (ctx) => ({
    reset: () =>
      ctx.invoke({ element: x('reset-uptime', { xmlns: NS }), requires: [] }),
  }),
  content: (ctx) => ({
    seconds: async () => {
      const element = x('get-uptime', { xmlns: NS });
      const reply = await ctx.invoke({ element, requires: [] });
      return Number(reply.data?.text());
    },
  }),
});
// client.ops.uptime.reset(), client.content.uptime.seconds()

An operation that returns datastore content can offer format: 'json' the way nmda does: pass the data element to ctx.toJson(data, { datastore, requireSchema }), which converts it with the client's YANG schemas and rules.

ts
ops: (ctx) => ({
  counters: async ({ format }: { format?: 'xml' | 'json' } = {}) => {
    const element = x('get-counters', { xmlns: 'urn:example:counters' });
    const data = (await ctx.invoke({ element, requires: [] })).data!;
    return format === 'json'
      ? ctx.toJson(data, { datastore: 'operational' })
      : data;
  },
}),

An operation that takes datastore content can accept RFC 7951 JSON the same way: ctx.toXml(json, { datastore, filter }) converts it to the elements to send (with filter: true, to subtree-filter content), by the rules in Writing JSON.

To make an RPC runnable by name (client.ops.run(), the CLI), describe it and give it a request builder. The builder can type its own arguments: the client calls it only with the names its descriptor lists, so it needs no casts. Check any value a tool could send wrongly.

ts
import { defineExtension, x } from '@node-net/netconf';

const NS = 'urn:example:uptime';

export const uptime = defineExtension({
  id: 'uptime',
  descriptors: [
    {
      name: 'reset-uptime',
      namespace: NS,
      method: 'reset',
      description: 'Reset the uptime counter',
      mutates: true,
      requires: ['urn:example:uptime:1.0'],
      params: [
        {
          name: 'reason',
          kind: 'option',
          type: 'string',
          description: 'Why, for the log',
        },
      ],
    },
  ],
  requests: {
    'reset-uptime': (args: { readonly reason?: string }) => ({
      element: x('reset-uptime', { xmlns: NS },
        args.reason !== undefined && x('reason', args.reason)),
      requires: [],
    }),
  },
});
// await client.ops.run('reset-uptime', { reason: 'test' });

Leave a builder's parameter unannotated and it is never. Annotate it with your own type, as above, or with RequestArgs to take plain arguments and check each one.

An id can't be one that would hide a built-in member of a layer it contributes to, such as list or get in ops, or read in content. See defineExtension in the API reference.

Released under the MIT Licence.