Search in sources :

Example 56 with EffectiveModelContext

use of org.opendaylight.yangtools.yang.model.api.EffectiveModelContext in project lighty-netconf-simulator by PANTHEONtech.

the class Main method start.

@SuppressFBWarnings({ "SLF4J_SIGN_ONLY_FORMAT", "OBL_UNSATISFIED_OBLIGATION" })
public void start(String[] args, boolean registerShutdownHook, final boolean initDatastore) {
    int port = getPortFromArgs(args);
    LOG.info("Lighty-Network-Topology device started {}", port);
    LOG.info(" _______          __ ________              .__");
    LOG.info(" \\      \\   _____/  |\\______ \\   _______  _|__| ____  ____");
    LOG.info(" /   |   \\_/ __ \\   __\\    |  \\_/ __ \\  \\/ /  |/ ___\\/ __ ");
    LOG.info("/    |    \\  ___/|  | |    `   \\  ___/\\   /|  \\  \\__\\  ___/");
    LOG.info("\\____|__  /\\___  >__|/_______  /\\___  >\\_/ |__|\\___  >___  >");
    LOG.info(" \\/     \\/            \\/     \\/             \\/    \\/");
    LOG.info("[https://lighty.io]");
    // 1. Load models from classpath
    Set<YangModuleInfo> modules = ModelUtils.getModelsFromClasspath(ModuleId.from("urn:tech.pantheon.netconfdevice.network.topology.rpcs", "network-topology-rpcs", "2018-03-20"), ModuleId.from("urn:opendaylight:netconf-node-topology", "netconf-node-topology", "2015-01-14"));
    // 2. Initialize DataStores
    InputStream initialOperationalData = null;
    InputStream initialConfigurationData = null;
    if (initDatastore) {
        initialOperationalData = Main.class.getResourceAsStream("/initial-network-topo-operational-datastore.xml");
        initialConfigurationData = Main.class.getResourceAsStream("/initial-network-topo-config-datastore.xml");
    }
    // 3. Initialize RPCs
    NetworkTopologyServiceImpl networkTopologyService = new NetworkTopologyServiceImpl();
    // 4. Initialize Netconf device
    NetconfDevice netconfDevice = new NetconfDeviceBuilder().setCredentials("admin", "admin").setBindingPort(port).withModels(modules).withDefaultRequestProcessors().withDefaultCapabilities().setInitialOperationalData(initialOperationalData).setInitialConfigurationData(initialConfigurationData).withRequestProcessor(new NetworkTopologyServiceGetTopologiesProcessor(networkTopologyService)).withRequestProcessor(new NetworkTopologyServiceGetTopologyByIdProcessor(networkTopologyService)).withRequestProcessor(new NetworkTopologyServiceGetTopologyIdsProcessor(networkTopologyService)).withRequestProcessor(new NetworkTopologyServiceGetNodeFromTopologyProcessor(networkTopologyService)).withRequestProcessor(new NetworkTopologyServiceCreateTopologyProcessor(networkTopologyService)).withRequestProcessor(new NetworkTopologyServiceAddNodeToTopologyProcessor(networkTopologyService)).withRequestProcessor(new NetworkTopologyServiceRemoveTopologyProcessor(networkTopologyService)).withRequestProcessor(new NetworkTopologyServiceRemoveAllTopologiesProcessor(networkTopologyService)).withRequestProcessor(new NetworkTopologyServiceRemoveNodeProcessor(networkTopologyService)).withDefaultNotificationProcessor().build();
    netconfDevice.start();
    final DataBroker dataBroker = netconfDevice.getNetconfDeviceServices().getDataBroker();
    networkTopologyService.setDataBrokerService(dataBroker);
    DataTreeChangeListenerActivator listenerActivator = new DataTreeChangeListenerActivator(netconfDevice.getNetconfDeviceServices().getNotificationPublishService(), dataBroker);
    listenerActivator.init();
    networkTopologyService.setDataBrokerService(netconfDevice.getNetconfDeviceServices().getDataBroker());
    EffectiveModelContext effectiveModelContext = netconfDevice.getNetconfDeviceServices().getAdapterContext().currentSerializer().getRuntimeContext().getEffectiveModelContext();
    networkTopologyService.setEffectiveModelContext(effectiveModelContext);
    // 5. Register shutdown hook
    this.shutdownHook = new ShutdownHook(netconfDevice, networkTopologyService, listenerActivator);
    if (registerShutdownHook) {
        Runtime.getRuntime().addShutdownHook(this.shutdownHook);
    }
}
Also used : NetworkTopologyServiceImpl(io.lighty.netconf.device.topology.rpcs.NetworkTopologyServiceImpl) InputStream(java.io.InputStream) NetworkTopologyServiceRemoveAllTopologiesProcessor(io.lighty.netconf.device.topology.processors.NetworkTopologyServiceRemoveAllTopologiesProcessor) NetworkTopologyServiceAddNodeToTopologyProcessor(io.lighty.netconf.device.topology.processors.NetworkTopologyServiceAddNodeToTopologyProcessor) NetworkTopologyServiceRemoveNodeProcessor(io.lighty.netconf.device.topology.processors.NetworkTopologyServiceRemoveNodeProcessor) DataBroker(org.opendaylight.mdsal.binding.api.DataBroker) NetworkTopologyServiceGetNodeFromTopologyProcessor(io.lighty.netconf.device.topology.processors.NetworkTopologyServiceGetNodeFromTopologyProcessor) DataTreeChangeListenerActivator(io.lighty.netconf.device.topology.datastore.DataTreeChangeListenerActivator) NetworkTopologyServiceGetTopologyIdsProcessor(io.lighty.netconf.device.topology.processors.NetworkTopologyServiceGetTopologyIdsProcessor) NetworkTopologyServiceCreateTopologyProcessor(io.lighty.netconf.device.topology.processors.NetworkTopologyServiceCreateTopologyProcessor) YangModuleInfo(org.opendaylight.yangtools.yang.binding.YangModuleInfo) NetconfDevice(io.lighty.netconf.device.NetconfDevice) NetconfDeviceBuilder(io.lighty.netconf.device.NetconfDeviceBuilder) NetworkTopologyServiceRemoveTopologyProcessor(io.lighty.netconf.device.topology.processors.NetworkTopologyServiceRemoveTopologyProcessor) NetworkTopologyServiceGetTopologyByIdProcessor(io.lighty.netconf.device.topology.processors.NetworkTopologyServiceGetTopologyByIdProcessor) NetworkTopologyServiceGetTopologiesProcessor(io.lighty.netconf.device.topology.processors.NetworkTopologyServiceGetTopologiesProcessor) EffectiveModelContext(org.opendaylight.yangtools.yang.model.api.EffectiveModelContext) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 57 with EffectiveModelContext

use of org.opendaylight.yangtools.yang.model.api.EffectiveModelContext in project netconf by opendaylight.

the class DeviceMountPointContext method create.

static MountPointContext create(final MountPointContext emptyContext, final ContainerNode mountData) {
    final Optional<DataContainerChild> optMountPoint = mountData.findChildByArg(MOUNT_POINT);
    if (optMountPoint.isEmpty()) {
        LOG.debug("mount-point list not present in {}", mountData);
        return emptyContext;
    }
    final EffectiveModelContext schemaContext = emptyContext.getEffectiveModelContext();
    final DataContainerChild mountPoint = optMountPoint.get();
    checkArgument(mountPoint instanceof MapNode, "mount-point list %s is not a MapNode", mountPoint);
    final Map<MountPointIdentifier, NetconfMountPointContextFactory> mountPoints = new HashMap<>();
    for (MapEntryNode entry : ((MapNode) mountPoint).body()) {
        final String moduleName = entry.findChildByArg(MODULE).map(mod -> {
            checkArgument(mod instanceof LeafNode, "Unexpected module leaf %s", mod);
            final Object value = mod.body();
            checkArgument(value instanceof String, "Unexpected module leaf value %s", value);
            return (String) value;
        }).orElseThrow(() -> new IllegalArgumentException("Mount module missing in " + entry));
        final Iterator<? extends Module> it = schemaContext.findModules(moduleName).iterator();
        checkArgument(it.hasNext(), "Failed to find a module named %s", moduleName);
        final QNameModule module = it.next().getQNameModule();
        final MountPointIdentifier mountId = MountPointIdentifier.of(QName.create(module, entry.findChildByArg(LABEL).map(lbl -> {
            checkArgument(lbl instanceof LeafNode, "Unexpected label leaf %s", lbl);
            final Object value = lbl.body();
            checkArgument(value instanceof String, "Unexpected label leaf value %s", value);
            return (String) value;
        }).orElseThrow(() -> new IllegalArgumentException("Mount module missing in " + entry))));
        final DataContainerChild child = entry.findChildByArg(SCHEMA_REF).orElseThrow(() -> new IllegalArgumentException("Missing schema-ref choice in " + entry));
        checkArgument(child instanceof ChoiceNode, "Unexpected schema-ref choice %s", child);
        final ChoiceNode schemaRef = (ChoiceNode) child;
        final Optional<DataContainerChild> maybeShared = schemaRef.findChildByArg(SHARED_SCHEMA);
        if (maybeShared.isEmpty()) {
            LOG.debug("Ignoring non-shared mountpoint entry {}", entry);
            continue;
        }
        mountPoints.put(mountId, new NetconfMountPointContextFactory(schemaContext));
    }
    return new DeviceMountPointContext(schemaContext, mountPoints);
}
Also used : NodeIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier) SchemaMountConstants(org.opendaylight.yangtools.rfc8528.model.api.SchemaMountConstants) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) MountPointIdentifier(org.opendaylight.yangtools.rfc8528.data.api.MountPointIdentifier) QNameModule(org.opendaylight.yangtools.yang.common.QNameModule) Objects.requireNonNull(java.util.Objects.requireNonNull) Map(java.util.Map) MapNode(org.opendaylight.yangtools.yang.data.api.schema.MapNode) MountPointContextFactory(org.opendaylight.yangtools.rfc8528.data.api.MountPointContextFactory) AbstractEffectiveModelContextProvider(org.opendaylight.yangtools.yang.model.spi.AbstractEffectiveModelContextProvider) ContainerNode(org.opendaylight.yangtools.yang.data.api.schema.ContainerNode) LeafNode(org.opendaylight.yangtools.yang.data.api.schema.LeafNode) Immutable(org.opendaylight.yangtools.concepts.Immutable) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) Module(org.opendaylight.yangtools.yang.model.api.Module) ImmutableMap(com.google.common.collect.ImmutableMap) DataContainerChild(org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild) EffectiveModelContext(org.opendaylight.yangtools.yang.model.api.EffectiveModelContext) MountPointContext(org.opendaylight.yangtools.rfc8528.data.api.MountPointContext) QName(org.opendaylight.yangtools.yang.common.QName) Optional(java.util.Optional) MapEntryNode(org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode) NonNull(org.eclipse.jdt.annotation.NonNull) ChoiceNode(org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode) HashMap(java.util.HashMap) MapNode(org.opendaylight.yangtools.yang.data.api.schema.MapNode) MapEntryNode(org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode) DataContainerChild(org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild) LeafNode(org.opendaylight.yangtools.yang.data.api.schema.LeafNode) QNameModule(org.opendaylight.yangtools.yang.common.QNameModule) ChoiceNode(org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode) MountPointIdentifier(org.opendaylight.yangtools.rfc8528.data.api.MountPointIdentifier) EffectiveModelContext(org.opendaylight.yangtools.yang.model.api.EffectiveModelContext)

Example 58 with EffectiveModelContext

use of org.opendaylight.yangtools.yang.model.api.EffectiveModelContext in project netconf by opendaylight.

the class NetconfUtilTest method testWriteNormalizedNode.

@Test
public void testWriteNormalizedNode() throws Exception {
    final EffectiveModelContext context = BindingRuntimeHelpers.createEffectiveModel(Collections.singletonList($YangModuleInfoImpl.getInstance()));
    final LeafNode<?> username = Builders.leafBuilder().withNodeIdentifier(new NodeIdentifier(QName.create(Session.QNAME, "username"))).withValue("admin").build();
    final MapEntryNode session1 = Builders.mapEntryBuilder().withNodeIdentifier(NodeIdentifierWithPredicates.of(Session.QNAME, QName.create(Session.QNAME, "session-id"), 1L)).withChild(username).build();
    final MapNode sessionList = Builders.mapBuilder().withNodeIdentifier(new NodeIdentifier(Session.QNAME)).withChild(session1).build();
    final ContainerNode sessions = Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(Sessions.QNAME)).withChild(sessionList).build();
    final DOMResult result = new DOMResult(XmlUtil.newDocument());
    final SchemaPath path = SchemaPath.create(true, NetconfState.QNAME);
    NetconfUtil.writeNormalizedNode(sessions, result, path, context);
    final Document actual = (Document) result.getNode();
    final Document expected = XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/sessions.xml"));
    final Diff diff = XMLUnit.compareXML(expected, actual);
    assertTrue(diff.toString(), diff.similar());
}
Also used : DOMResult(javax.xml.transform.dom.DOMResult) SchemaPath(org.opendaylight.yangtools.yang.model.api.SchemaPath) Diff(org.custommonkey.xmlunit.Diff) NodeIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier) ContainerNode(org.opendaylight.yangtools.yang.data.api.schema.ContainerNode) MapNode(org.opendaylight.yangtools.yang.data.api.schema.MapNode) MapEntryNode(org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode) Document(org.w3c.dom.Document) EffectiveModelContext(org.opendaylight.yangtools.yang.model.api.EffectiveModelContext) Test(org.junit.Test)

Example 59 with EffectiveModelContext

use of org.opendaylight.yangtools.yang.model.api.EffectiveModelContext in project netconf by opendaylight.

the class JSONRestconfServiceImplTest method setup.

@Before
public void setup() throws FileNotFoundException {
    final EffectiveModelContext mountPointSchemaContext = TestUtils.loadSchemaContext("/full-versions/test-module");
    final ControllerContext controllerContext = TestRestconfUtils.newControllerContext(schemaContext, mockMountPoint);
    doReturn(java.util.Optional.of(FixedDOMSchemaService.of(() -> mountPointSchemaContext))).when(mockMountPoint).getService(eq(DOMSchemaService.class));
    service = new JSONRestconfServiceImpl(controllerContext, RestconfImpl.newInstance(brokerFacade, controllerContext));
}
Also used : ControllerContext(org.opendaylight.netconf.sal.restconf.impl.ControllerContext) FixedDOMSchemaService(org.opendaylight.mdsal.dom.spi.FixedDOMSchemaService) DOMSchemaService(org.opendaylight.mdsal.dom.api.DOMSchemaService) EffectiveModelContext(org.opendaylight.yangtools.yang.model.api.EffectiveModelContext) JSONRestconfServiceImpl(org.opendaylight.netconf.sal.restconf.impl.JSONRestconfServiceImpl) Before(org.junit.Before)

Example 60 with EffectiveModelContext

use of org.opendaylight.yangtools.yang.model.api.EffectiveModelContext in project netconf by opendaylight.

the class RestconfDataServiceImpl method readData.

@Override
public Response readData(final String identifier, final UriInfo uriInfo) {
    final ReadDataParams readParams = QueryParams.newReadDataParams(uriInfo);
    final EffectiveModelContext schemaContextRef = schemaContextHandler.get();
    final InstanceIdentifierContext<?> instanceIdentifier = ParserIdentifier.toInstanceIdentifier(identifier, schemaContextRef, Optional.of(mountPointService));
    final DOMMountPoint mountPoint = instanceIdentifier.getMountPoint();
    // FIXME: this looks quite crazy, why do we even have it?
    if (mountPoint == null && identifier != null && identifier.contains(STREAMS_PATH) && !identifier.contains(STREAM_PATH_PART)) {
        createAllYangNotificationStreams(schemaContextRef, uriInfo);
    }
    final QueryParameters queryParams = QueryParams.newQueryParameters(readParams, instanceIdentifier);
    final List<YangInstanceIdentifier> fieldPaths = queryParams.fieldPaths();
    final RestconfStrategy strategy = getRestconfStrategy(mountPoint);
    final NormalizedNode node;
    if (fieldPaths != null && !fieldPaths.isEmpty()) {
        node = ReadDataTransactionUtil.readData(readParams.content(), instanceIdentifier.getInstanceIdentifier(), strategy, readParams.withDefaults(), schemaContextRef, fieldPaths);
    } else {
        node = ReadDataTransactionUtil.readData(readParams.content(), instanceIdentifier.getInstanceIdentifier(), strategy, readParams.withDefaults(), schemaContextRef);
    }
    // FIXME: this is utter craziness, refactor it properly!
    if (identifier != null && identifier.contains(STREAM_PATH) && identifier.contains(STREAM_ACCESS_PATH_PART) && identifier.contains(STREAM_LOCATION_PATH_PART)) {
        final String value = (String) node.body();
        final String streamName = value.substring(value.indexOf(NOTIFICATION_STREAM + '/'));
        delegRestconfSubscrService.subscribeToStream(streamName, uriInfo);
    }
    if (node == null) {
        throw new RestconfDocumentedException("Request could not be completed because the relevant data model content does not exist", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
    }
    switch(readParams.content()) {
        case ALL:
        case CONFIG:
            final QName type = node.getIdentifier().getNodeType();
            return Response.status(Status.OK).entity(NormalizedNodePayload.ofReadData(instanceIdentifier, node, queryParams)).header("ETag", '"' + type.getModule().getRevision().map(Revision::toString).orElse(null) + "-" + type.getLocalName() + '"').header("Last-Modified", FORMATTER.format(LocalDateTime.now(Clock.systemUTC()))).build();
        default:
            return Response.status(Status.OK).entity(NormalizedNodePayload.ofReadData(instanceIdentifier, node, queryParams)).build();
    }
}
Also used : ReadDataParams(org.opendaylight.restconf.nb.rfc8040.ReadDataParams) RestconfDocumentedException(org.opendaylight.restconf.common.errors.RestconfDocumentedException) QName(org.opendaylight.yangtools.yang.common.QName) DOMMountPoint(org.opendaylight.mdsal.dom.api.DOMMountPoint) RestconfStrategy(org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfStrategy) MdsalRestconfStrategy(org.opendaylight.restconf.nb.rfc8040.rests.transactions.MdsalRestconfStrategy) QueryParameters(org.opendaylight.restconf.nb.rfc8040.legacy.QueryParameters) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) Revision(org.opendaylight.yangtools.yang.common.Revision) NormalizedNode(org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode) EffectiveModelContext(org.opendaylight.yangtools.yang.model.api.EffectiveModelContext)

Aggregations

EffectiveModelContext (org.opendaylight.yangtools.yang.model.api.EffectiveModelContext)182 Test (org.junit.Test)99 Module (org.opendaylight.yangtools.yang.model.api.Module)37 QName (org.opendaylight.yangtools.yang.common.QName)29 ContainerNode (org.opendaylight.yangtools.yang.data.api.schema.ContainerNode)28 DataSchemaNode (org.opendaylight.yangtools.yang.model.api.DataSchemaNode)26 NormalizedNode (org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode)24 LeafSchemaNode (org.opendaylight.yangtools.yang.model.api.LeafSchemaNode)24 ContainerSchemaNode (org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode)21 YangInstanceIdentifier (org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier)18 QNameModule (org.opendaylight.yangtools.yang.common.QNameModule)16 NodeIdentifier (org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier)16 NormalizedNodeStreamWriter (org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter)16 IRSchemaSource (org.opendaylight.yangtools.yang.parser.rfc7950.ir.IRSchemaSource)14 DOMMountPoint (org.opendaylight.mdsal.dom.api.DOMMountPoint)13 RestconfDocumentedException (org.opendaylight.restconf.common.errors.RestconfDocumentedException)13 RpcDefinition (org.opendaylight.yangtools.yang.model.api.RpcDefinition)13 MapEntryNode (org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode)11 IOException (java.io.IOException)9 Collection (java.util.Collection)9